# Topic 20: GROUP BY Grouping
Grouping rows into buckets, multi-column grouping, aggregate integrity rules, and GROUP BY execution mechanics.
1. Definition
The GROUP BY clause collapses rows that share identical values in specified columns into summary buckets, enabling aggregate functions to run per group.
2. Explain Like I'm 5
Imagine sorting a box of Lego bricks by color. You make separate piles for red, blue, and green, and then count how many bricks are in each pile.
3. Animation & Visual Simulation
Interactive Engine TraceHash Aggregation & Bucket Pipeline
SELECT department, AVG(salary) FROM employees GROUP BY department HAVING AVG(salary) > 65000;Active InputStep 1: Hash Key Calculation
Alice ($80k), David ($70k)
Bob ($50k), Eve ($55k)
Charlie ($90k)
The engine hashes the group key ("IT", "HR", "Sales") into in-memory hash buckets.
4. Real-World Example
An executive report showing total sales and headcount per department.
| name | department | salary |
|---|---|---|
| Alice | Engineering | $120,000 |
| Bob | Engineering | $110,000 |
| Charlie | Marketing | $90,000 |
| department | headcount | total_payroll |
|---|---|---|
| Engineering | 2 | $230,000 |
| Marketing | 1 | $90,000 |
5. SQL Syntax
ANSI SQL / PostgreSQL DialectSELECT department, country, COUNT(*) AS total_staff, ROUND(AVG(salary), 2) AS avg_salary FROM employees GROUP BY department, country;
6. Important Rules & Behaviors
| Rule | Behavioral Explanation |
|---|---|
| Projection Invariant | Any column in SELECT that is not wrapped in an aggregate function must be listed in GROUP BY. |
| NULL Grouping | All NULL values in a grouping column are treated as equal and placed into a single shared NULL group. |
| HashAggregate vs GroupAggregate | Engines group rows using in-memory hash tables (HashAggregate) or by sorting first (GroupAggregate). |
| Single-value rule | Every non-aggregated column in the SELECT list must appear in the GROUP BY clause. |
| Hash Aggregate vs Group Aggregate | The engine either hashes grouping keys into RAM (HashAggregate) or pre-sorts data (GroupAggregate). |
7. Deep Dive: HashAggregate vs GroupAggregate Engine Plans
The Cost-Based Optimizer chooses between HashAggregate (building a hash table in memory) and GroupAggregate (sorting input rows first, then scanning sequentially). If work_mem is too small to hold all distinct groups, the hash table spills to disk.
-- EXPLAIN output showing HashAggregate: EXPLAIN SELECT department, COUNT(*) FROM employees GROUP BY department; -- "HashAggregate (cost=15.20..17.20 rows=200 width=16)"
8. Advantages & Disadvantages
Advantages
- •Transforms granular row data into structured departmental/category analytics.
- •Enables multi-dimensional summaries in a single query.
Disadvantages & Trade-offs
- •Grouping massive datasets without indexes creates high memory pressure and disk spills.
9. Common Interview Questions
Q1.Why does "SELECT department, name, AVG(salary) FROM employees GROUP BY department;" fail with a syntax error?
This violates the Single-Value Rule of relational algebra. GROUP BY department collapses multiple employee rows into a single summary row per department. The department has one value, and AVG(salary) computes one scalar value. But "name" has multiple different values per department: the engine cannot guess which employee name to display without an aggregate function (e.g. STRING_AGG, MAX).
Q2.What is the difference between Hash Aggregate and Group Aggregate in execution plans?
In Hash Aggregate, the engine builds an in-memory hash table where keys are the GROUP BY columns and values are the running aggregate accumulators; it processes in O(N) but requires enough work_mem. In Group Aggregate, the input data must already be sorted by the grouping columns (via an index or sort); the engine streams through sorted rows and emits a group whenever the key changes, using minimal memory.
Q3.What are GROUPING SETS, ROLLUP, and CUBE in SQL?
These are multidimensional aggregation extensions that compute multiple levels of subtotals in a single query pass. ROLLUP(year, month) creates hierarchical subtotals: (year, month), (year), and grand total. CUBE(region, product) creates all possible combinations: (region, product), (region), (product), and grand total. GROUPING SETS allows defining exact custom subtotal combinations.
Q4.How do indexes optimize GROUP BY performance?
If an index exists on the grouping columns (e.g. INDEX ON employees(department)), the database can avoid the expensive in-memory hash table or sort phase entirely. It performs an Index Scan to read the rows already ordered by department, executing a streaming GroupAggregate in O(N) time with O(1) memory.
Q5.Can you GROUP BY an expression or calculation in SQL?
Yes. You can group by computed expressions, such as GROUP BY DATE_TRUNC('month', created_at) or GROUP BY CASE WHEN age >= 18 THEN 'Adult' ELSE 'Minor' END. However, in standard SQL, you must repeat the exact expression in the GROUP BY clause unless using column position numbers (e.g. GROUP BY 1).
10. Interview-Ready Answer
“GROUP BY aggregates rows with identical values into summary buckets. Every column in the SELECT list must either be declared in the GROUP BY clause or enclosed in an aggregate function.”
11. Quick Test
Why does the query "SELECT dept_id, title, COUNT(*) FROM staff GROUP BY dept_id;" throw an error in standard SQL?