Java Zero to All All questionsPractise free
Interview questions › Databases & Persistence › SQL Mastery & Joins

How do GROUP BY and aggregate functions handle NULLs, and what surprises people about COUNT?

Level II · JuniorSQL Mastery & Joins
Short answer

Aggregate functions ignore NULLs: SUM, AVG, MIN, MAX, and COUNT(column) skip NULL values, so AVG is over non-null rows only, which can differ from what you expect if you assumed NULL meant zero.

Explanation

COUNT(*) counts all rows including those with NULLs, whereas COUNT(column) counts only non-null values of that column, and COUNT(DISTINCT column) further deduplicates. GROUP BY treats all NULLs as a single group. These distinctions cause real reporting bugs, e.g. AVG(amount) understating totals when missing amounts should have counted as zero.

Common mistakes
  • Expecting COUNT(column) to count NULL rows.
  • Forgetting AVG ignores NULLs.

Can you say this out loud in two minutes? Drill it in a timed mock interview, with flashcards and runnable code for SQL Mastery & Joins.

Practise free

More on SQL Mastery & Joins