GROUP BY & Aggregates in SQL

From the SQL cheat sheet ยท Aggregation ยท verified Jul 2026

GROUP BY & Aggregates

Summarize data with aggregate functions and grouping.

sql
-- Aggregate functions
SELECT COUNT(*) FROM users;
SELECT SUM(amount) FROM orders;
SELECT AVG(age) FROM users;
SELECT MIN(price), MAX(price) FROM products;

-- GROUP BY
SELECT city, COUNT(*) AS user_count
FROM users
GROUP BY city;

-- HAVING โ€” filter groups
SELECT city, COUNT(*) AS cnt
FROM users
GROUP BY city
HAVING COUNT(*) > 10;
๐Ÿ’ก WHERE filters rows before grouping; HAVING filters groups after aggregation
โšก COUNT(*) counts all rows; COUNT(column) counts only non-NULL values
๐Ÿ“Œ Every non-aggregated column in SELECT must appear in GROUP BY
๐ŸŸข Execution order: WHERE โ†’ GROUP BY โ†’ HAVING โ†’ SELECT โ†’ ORDER BY โ†’ LIMIT
aggregategroup-byhavingcountsum
Back to the full SQL cheat sheet