GROUP BY turns detailed records into one summary row per category or category combination. HAVING filters those groups after aggregation. Together they power common interview and reporting tasks such as employee counts by unit, revenue by month, and customers with several purchases.
Key Takeaways at a Glance:
- •GROUP BY collapses rows sharing identical values into summary rows.
- •HAVING filters aggregated groups based on summary conditions (e.g. HAVING COUNT(*) > 5).
- •Execution sequence: WHERE filters rows -> GROUP BY forms groups -> HAVING filters groups -> SELECT projects -> ORDER BY sorts.
- •Under ONLY_FULL_GROUP_BY, selected columns must either appear in GROUP BY or be enclosed in aggregate functions.
In Simple Words (The Mental Model)
GROUP BY organizes your data into categorized buckets (like putting all Engineering employees in one bucket and Sales in another). Once the buckets are full, HAVING lets you throw away buckets that don't meet your criteria (e.g. 'only keep departments with more than 10 people').
Real-World Analogy
Think of sorting coins into separate piggy banks: one for quarters, one for dimes, one for nickels (GROUP BY). After counting each piggy bank, you say: 'Only take the banks that have more than $10 total to the coin counter' (HAVING).