Interview Prep

4 GROUP BY Traps, Wrong vs Right

WHERE vs HAVING, nullable grouping keys, bare SELECT columns: 4 GROUP BY traps that run without errors yet fail take-homes, each with the fix.

Anuj SainiOct 2, 20262 min read

The killer detail: all four run without errors. The take-home grader doesn't check that your query executed — it checks the output.

Trap 1: WHERE on aggregates

WHERE SUM(x) > 100 filters before grouping, so the condition never sees aggregated values. Move it to HAVING SUM(x) > 100 after GROUP BY.

Trap 2: Bare SELECT columns

Selecting name while grouping by dept works in MySQL and explodes in Postgres — and in interviews. Group by every non-aggregated column or aggregate it.

Trap 3: NULLs in the grouping key

NULLs form a hidden group. Half your rows vanish and the total still "looks right." Fix: COALESCE(key, 'UNKNOWN') plus an explicit null-rate audit.

Trap 4: HAVING without GROUP BY

Valid syntax, nonsense semantics. Move the condition to WHERE or add the grouping. Interviewers plant it to see if you flinch.

Drill all four with wrong-vs-right outputs at Topfolio Practice.

Related: Sql 30 Interview Questions Practice · What Is Sql

Frequently Asked Questions

Why can't I use WHERE on aggregated values?

WHERE filters rows before grouping, so it never sees aggregated values. Filter on aggregates with HAVING, which runs after GROUP BY.

What happens to NULLs in a GROUP BY key?

They form their own silent group. Totals can look right while rows vanish into a bucket nobody asked for — audit with COALESCE plus an explicit null check.

Why does MySQL accept queries Postgres rejects?

MySQL permits bare non-aggregated columns in GROUP BY; Postgres and interviewers treat them as errors. Write portable SQL.

Anuj Saini

Written by

Anuj SainiFounder & Lead Instructor

Founder at Topfolio with 6+ years in data & analytics across JPMC, Ultrahuman, and high-growth startups. Sat on hiring panels, reviewed 500+ resumes, and writes practical SQL & data guides.