Sitemap
Production Ready

Production Ready: backend engineering that survives production — Spring Boot, data, distributed systems, JVM tuning, and AI in prod, with runnable code and honest tradeoffs.

Stop Guessing at WHERE vs HAVING: One Idea Makes GROUP BY Click

9 min read4 hours ago

--

Stop memorizing rules about WHERE vs HAVING. Build the mental model of how SQL groups, aggregates, and filters — then GROUPING SETS, ROLLUP, FILTER, and DISTINCT aggregates all fall into place. Runnable PostgreSQL throughout.

The One Idea That Explains Everything

Press enter or click to view image in full size

If you’ve ever added a column to a SELECT and gotten the dreaded "must appear in the GROUP BY clause" error, you've been memorizing rules instead of understanding one idea. Here it is: GROUP BY does exactly one thing — it collapses many rows into one row per group. Every confusing part of aggregation, from WHERE vs HAVING to why COUNT(*) and COUNT(col) disagree, falls out of that single fact once you actually see it.

After grouping, each group is a single output row. So the only things you can put in the SELECT list are: (a) the columns you grouped by (constant within the group), and (b) aggregate functions that reduce the group's many values to one. Ask "does this produce one value per group?" and every rule answers itself.

PostgreSQL syntax throughout; MySQL differences noted.

The Data

--

--

Anupam Sinha
Anupam Sinha

Written by Anupam Sinha

Java · Spring Boot · Microservices · AI. Technical Architect with 17 years of enterprise experience. Writing what I wish I had when I started.

Production Ready
Production Ready

Published in Production Ready

Production Ready: backend engineering that survives production — Spring Boot, data, distributed systems, JVM tuning, and AI in prod, with runnable code and honest tradeoffs.