SQL GROUP BY statement
Here is a clear, practical, and complete guide to the SQL GROUP BY statement, with examples, rules, and common pitfalls.
β
What GROUP BY Does
GROUP BY groups rows that share the same values so you can apply aggregate functions such as:
-
COUNT() -
SUM() -
AVG() -
MIN() -
MAX()
It turns many rows into summary rows.
πΉ Basic Syntax
π Basic Examples
1. Count employees per department
2. Total sales per customer
3. Average score per class
π₯ GROUP BY with Multiple Columns
This groups first by country, then city.
π₯ GROUP BY + HAVING (Filter Aggregated Results)
HAVING is used after aggregation.WHERE filters rows before grouping.
Example: Departments with more than 10 employees
π§ GROUP BY with ORDER BY
Sort aggregated results:
π₯ Real-World Examples
Monthly revenue
(PostgreSQL example using DATE_TRUNC)
Count logins per user
Maximum order per customer
π§ Important Rules & Pitfalls
β 1. Every non-aggregated column MUST be in GROUP BY
β Invalid:
β Valid:
β 2. Aggregate functions ignore NULLs
COUNT(column) ignores NULLSUM, AVG, MIN, MAX ignore NULL
β 3. Use HAVING for aggregated filters
WHERE β before groupingHAVING β after grouping
β 4. GROUP BY with DISTINCT isnβt usually needed
This:
Is equal to:
π Performance Tips
β Index columns used in GROUP BY
β Use GROUP BY on low-cardinality columns carefully
β Avoid grouping on expressions unless necessary
β In large datasets, consider materialized views

