Skip to content

Instantly share code, notes, and snippets.

@Charmatzis
Last active February 14, 2023 07:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Charmatzis/4c87b8a4941e2ebddb63a29a34e04b3f to your computer and use it in GitHub Desktop.
Save Charmatzis/4c87b8a4941e2ebddb63a29a34e04b3f to your computer and use it in GitHub Desktop.
Count for null and not null columns
select count(a.id), sum(case when b.id is null then 0 else 1 end) as b_exists,
sum(case when b.id is null then 1 else 0 end) as b_does_not_exist
from a left join b on a.b_id = b.id;
-- Or even better
select count(a.id),
count(b.id) filter b.id is not null as b_exists,
count(b.id) filter b.id is null as b_does_not_exist
from a left join b on a.b_id = b.id;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment