Stage 5. GROUP BY and HAVING for Business Metrics

When business asks “What is total revenue?” or “How many orders per customer?”, plain row-level SELECT is not enough. You need aggregation: convert many rows into compact summaries. GROUP BY and HAVING are made for this.

Aggregation pipeline

What GROUP BY does

GROUP BY splits rows into groups by one or more keys. Then aggregates like COUNT, SUM, AVG, MIN, MAX are calculated per group.

Example:

SELECT user_id,
       COUNT(*) AS orders_count,
       SUM(amount) AS total_amount
FROM orders
WHERE status = 'PAID'
GROUP BY user_id;

Execution logic:

  1. Keep only rows from WHERE.
  2. Group remaining rows by user_id.
  3. Compute count and sum for each group.

What HAVING does

HAVING filters already-built groups after GROUP BY.

SELECT user_id,
       SUM(amount) AS total_amount
FROM orders
WHERE status = 'PAID'
GROUP BY user_id
HAVING SUM(amount) >= 1000;

Meaning: keep only users with total paid amount at least 1000.

Key difference:

  • WHERE filters rows before grouping;
  • HAVING filters groups after grouping.

Terms and keywords in one table

Keyword Role Example
GROUP BY Groups rows by key GROUP BY user_id
COUNT(*) Counts rows per group Number of orders
SUM(amount) Sums values per group Revenue
HAVING Filters groups by condition HAVING SUM(amount) > 1000

Example with output

SELECT user_id,
       COUNT(*) AS orders_count,
       SUM(amount) AS total_amount
FROM orders
WHERE status = 'PAID'
GROUP BY user_id
ORDER BY total_amount DESC;
user_id orders_count total_amount
1 5 4700.00
2 2 1400.00
3 1 300.00

Common beginner mistakes

  1. Using HAVING when WHERE should be used.
  2. Selecting a non-aggregated field not listed in GROUP BY.
  3. Grouping by too granular keys (for example full timestamp) and getting tiny fragmented groups.

Practical scenario: top customers by month

SELECT user_id,
       SUM(amount) AS revenue
FROM orders
WHERE status = 'PAID'
  AND created_at >= DATE '2026-05-01'
  AND created_at <  DATE '2026-06-01'
GROUP BY user_id
HAVING SUM(amount) >= 1000
ORDER BY revenue DESC;

This is a ready baseline for monthly top-customer reporting.

Glossary
table
A database structure that stores data in rows and columns.
row
One record inside a database table.
column
A named field in a database table that stores one kind of value.
schema
The structure that defines database objects such as tables, columns, relationships, and constraints.
primary key
A column or group of columns that uniquely identifies each row in a table.
foreign key
A column or group of columns that points to a primary key in another table.
relationship
A connection between data entities, usually represented through keys or object references.
entity
A domain object or persistent class that represents something with identity.
attribute
A property of an entity, usually mapped to a column or field.
aggregate function
A SQL function that calculates one value from many rows, such as count, sum, or average.
index
A data structure that helps a database find rows faster without scanning the whole table.
selectivity
A measure of how well a column or condition narrows data to a smaller result set.
normalization
The process of organizing relational data to reduce duplication and protect consistency.
transaction
A group of operations treated as one unit that should complete fully or not apply at all.
ACID
The database transaction guarantees of atomicity, consistency, isolation, and durability.
isolation level
A database setting that controls how concurrent transactions see each other's changes.
lock
A database or concurrency mechanism that restricts access to shared data while work is in progress.
deadlock
A situation where operations wait on each other in a cycle and cannot continue without intervention.
query plan
The database engine's chosen strategy for executing a query.
EXPLAIN
A SQL command that shows the query plan selected by the database.
sequential scan
A query operation that reads table rows one by one instead of using a targeted index lookup.