QuickDevGuide

Home › SQL Database

Aggregates, GROUP BY & HAVING — SQL Database

Aggregate functions collapse many rows into one value: COUNT, SUM, AVG, MIN, MAX (plus STRINGAGG/GROUPCONCAT for text). Logical query order SQL is written in one order but evaluated in another — this explains most GROUP BY errors: Step Clause Can use aggregates? 1 FROM / JOIN — 2 WHERE ❌ filters rows 3 GROUP BY — 4 HAVING ✅ filters groups 5 SELECT ✅ 6 ORDER BY ✅ (can use SELECT aliases) 7 LIMIT / OFFSET — Rules Every selected column must be either in the GROUP BY or inside an aggregate. COUNT() counts rows; COUNT(col) ignores NULLs; COUNT(DISTINCT col) counts unique values. Put row filters in WHERE (cheaper) and aggregate filters in HAVING.

Key Takeaways