0

I am trying to find the number of rows in a table with a particular column value = NULL in PostgreSQL. This is my query:

SELECT count(*) 
FROM database.table 
WHERE place_id = 3 AND user = (NULL);

And I get the count as 0. But there a pretty number of rows matching the query. What am I doing wrong here?

2
  • 5
    ... and user is null Commented Jan 9, 2018 at 15:50
  • worked! thank you @jarlh Commented Jan 9, 2018 at 16:03

2 Answers 2

3

You should use IS NULL:

Select count (*) from database.table where place_id = 3 and user IS NULL;

Do not write expression = NULL because NULL is not "equal to" NULL. (The null value represents an unknown value, and it is not known whether two unknown values are equal.) This behavior conforms to the SQL standard.

Sign up to request clarification or add additional context in comments.

2 Comments

And the reverse is also true: NULL is neither equal nor not equal to NULL.
Thanks @Rogério Carvalho Batista
0

If the value NULL comes from a variable, you can use IS DISTINCT FROM or IS NOT DISTINCT FROM which can compare NULL values:

SELECT COUNT(*) from database.table
WHERE place_id = 3 and user IS NOT DISTINCT FROM NULL

This query will also work for other values, especially parameters. The query

SELECT COUNT(*) from database.table
WHERE place_id = 3 and user IS NOT DISTINCT FROM $1

will work for $1 = 'Tom' and even $1 = NULL.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.