Skip to content
Back to 50 Concepts
Topic 20 of 50query-executionIntermediate

# 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.

Relational Invariant:Deterministic relational algebra contract evaluated by the Cost-Based Optimizer.

2. Explain Like I'm 5

Intuitive mental model for beginners

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 Trace
Interactive Engine Simulation

Hash Aggregation & Bucket Pipeline

Step 1 of 3
SQL>SELECT department, AVG(salary) FROM employees GROUP BY department HAVING AVG(salary) > 65000;Active Input

Step 1: Hash Key Calculation

Engine Action: Hash department column for incoming rows
Bucket #1: IT

Alice ($80k), David ($70k)

Bucket #2: HR

Bob ($50k), Eve ($55k)

Bucket #3: Sales

Charlie ($90k)

How the Database Executes This:

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.

Employees Table
namedepartmentsalary
AliceEngineering$120,000
BobEngineering$110,000
CharlieMarketing$90,000
Grouped Result
departmentheadcounttotal_payroll
Engineering2$230,000
Marketing1$90,000
Relational walkthrough: Rows are grouped by department, computing aggregates for each department bucket.

5. SQL Syntax

ANSI SQL / PostgreSQL Dialect
Step 1: Single and multi-column grouping
SELECT
  department,
  country,
  COUNT(*) AS total_staff,
  ROUND(AVG(salary), 2) AS avg_salary
FROM employees
GROUP BY department, country;
Every non-aggregated column in the SELECT list MUST appear in the GROUP BY clause.

6. Important Rules & Behaviors

RuleBehavioral Explanation
Projection InvariantAny column in SELECT that is not wrapped in an aggregate function must be listed in GROUP BY.
NULL GroupingAll NULL values in a grouping column are treated as equal and placed into a single shared NULL group.
HashAggregate vs GroupAggregateEngines group rows using in-memory hash tables (HashAggregate) or by sorting first (GroupAggregate).
Single-value ruleEvery non-aggregated column in the SELECT list must appear in the GROUP BY clause.
Hash Aggregate vs Group AggregateThe 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)"
Caution: Grouping on high-cardinality columns (like unique user IDs) consumes large amounts of memory.

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

Scenario Question:

Why does the query "SELECT dept_id, title, COUNT(*) FROM staff GROUP BY dept_id;" throw an error in standard SQL?

Select your answer: