COUNT(*) vs COUNT(col) and WHERE vs HAVING
Given rows (dept='eng', bonus=100), (dept='eng', bonus=NULL), (dept='ops', bonus=NULL), predict the result.
Code Snippet
SELECT dept, COUNT(*) AS total, COUNT(bonus) AS paid
FROM staff
GROUP BY dept
HAVING COUNT(*) >= 1;Expected Output & Explanation
eng | 2 | 1
ops | 1 | 0 COUNT(*) counts every row in the group including NULLs; COUNT(col) ignores NULL values in col. WHERE filters individual rows before grouping, while HAVING filters grouped aggregates after GROUP BY.
Follow-up Interview Question · Can you filter a single aggregate cleanly with COUNT(*) FILTER (WHERE bonus > 0) in Postgres?
Module Context & References
SQL & PostgreSQL · Query behavior & trap drills Predict query results for NULL logic, JOIN filters, aggregates and window functions
Personal Notes · Markdown