0

I have this query joining two "fake" tables:

select count(tb2.col2) from (select unnest(array['A','B']) col1) tb1 left join (select unnest(array['B','C']) col2) tb2 on tb1.col1=tb2.col2 where tb2.col2 IS NULL;

http://sqlfiddle.com/#!15/9eecb7db59d16c80417c72d1e1f4fbf1/22712

You can see that I expect the count of NULL to be 1 but it shows 0

So how to count the non-match rows?

 col1 | col2
------+------
 A    |
 B    | B

1 Answer 1

2

Use select count(*) instead of select count(tb2.col2).

  • count(*) is the number of rows.
  • count(expr) is the number of rows where expr is non-null.
Sign up to request clarification or add additional context in comments.

4 Comments

I wanted to count non-match (aka NULL), not the other way around.
But that's what count(*) does. You're already filtering by where tb2.col2 IS NULL.
@jspcal is correct. the count(*) simply references the row count. Any function applied directly against a 'NULL' column will fail. His approach is correct.
The other way to do this is to make a column like CASE WHEN my_column IS NULL THEN 1 ELSE 0 END which can be SUM'd

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.