Aggregate functions collapse many rows into one value with COUNT, SUM, AVG, MIN, and MAX — the whole result unless you GROUP BY. WHERE filters rows before grouping; HAVING filters groups after. COUNT(*) counts rows, while COUNT(col) ignores NULL in that column.
This SQL cheat sheet is written for people searching for a fast, accurate reference: students, junior developers, and teams shipping production software. Pin it, copy the snippets, and come back when syntax slips.
Quick reference
- COUNT(*): Rows in the group, including NULLs in other columns.
- COUNT(col): Non-NULL values of
col. - SUM / AVG: Ignore NULL.
AVGof{10, NULL}is 10, not 5. - MIN / MAX: Work on numbers, dates, and strings (collation matters).
- GROUP BY: List the non-aggregated SELECT columns.
- HAVING:
HAVING COUNT(*) >= 2after grouping. - DISTINCT:
COUNT(DISTINCT user_id)unique non-null users. - Filter first:
WHEREreduces rows before the aggregate — cheaper and different from HAVING.
Copy-paste examples
Revenue per day with a minimum count
Date grouping functions are dialect-specific; this form is common in MySQL.
SELECT DATE(paid_at) AS day,
COUNT(*) AS orders,
SUM(total) AS revenue,
AVG(total) AS avg_order
FROM orders
WHERE paid_at IS NOT NULL
GROUP BY DATE(paid_at)
HAVING COUNT(*) >= 3
ORDER BY day DESC;Common mistakes
- Using
WHERE COUNT(*) > 1— aggregates belong inHAVING. SUMof a string column and getting 0 or a warning you ignored.- Forgetting
GROUP BYand selecting extra columns (MySQL loose mode). - Counting a left-joined child with
COUNT(*)and inflating parent rows —COUNT(child.id)is safer.
FAQ
- AVG and empty set? No rows →
AVGreturns NULL, not 0. Handle that in SQL (COALESCE) or in the app.
- Can I GROUP BY an alias? MySQL often allows
GROUP BY dayifdayis in SELECT. Strict SQL wants the expression or a subquery. Do not assume portability.
- Window functions vs GROUP BY?
SUM() OVER (PARTITION BY …)keeps row detail.GROUP BYcollapses. MySQL 8+ supports windows.
Related SQL cheat sheets
Build with this stack
When a cheat sheet is not enough — you need a production app, a student FYP, or a custom dashboard — ArpaNeuro builds custom web development and also sells ready-made source code. Request a quote and tell us the stack.
Browse software development services or the source code marketplace if you want a working codebase instead of starting from a blank file.