SQL Aggregation and Join Grain
A practical lesson on grouping and conditional summaries in SQL, followed by techniques for preserving metric accuracy when joins change row counts.
Build summaries and filter at the right stage
Build summaries and filter at the right stage
A query’s grain is what one row in its result represents. GROUP BY sets that grain by putting input rows with the same grouping values into a group. Aggregate functions then calculate one value per group: for example, COUNT counts rows, SUM adds values, AVG calculates an average, and MIN and MAX find the smallest and largest values.
Suppose orders has one row per order. Grouping by region produces one result row per region, with summaries calculated from that region’s orders:
SELECT
region,
COUNT(*) AS order_count,
SUM(amount) AS revenue,
AVG(amount) AS average_order_amount
FROM orders
GROUP BY region
ORDER BY region;
Here, region identifies each group, while the aggregates summarize its rows. A selected column that is not inside an aggregate should identify the group—usually by appearing in GROUP BY. Otherwise, a group could contain several values for that column, leaving the query without a single value to report. If a query uses aggregates but no GROUP BY, its input is treated as one group and it produces an overall summary.
Filtering can happen at two different stages. WHERE removes input rows before the groups and their aggregates are calculated. HAVING filters the completed groups, so it can test aggregate results. For example, this query excludes cancelled orders first, then keeps regions with at least 100 remaining orders and revenue above $10,000:
SELECT
region,
COUNT(*) AS order_count,
SUM(amount) AS revenue
FROM orders
WHERE status <> 'cancelled'
GROUP BY region
HAVING COUNT(*) >= 100
AND SUM(amount) > 10000;
Use WHERE for row-level conditions such as a status or date range; use HAVING for group-level conditions such as a minimum order count or revenue. The order matters conceptually: HAVING evaluates summaries after the input rows have been filtered and grouped.
Calculate segment metrics in one query
Calculate segment metrics in one query
Conditional aggregation calculates multiple segment-specific measures within one grouped result. Put a condition inside an aggregate so that each expression counts or sums only the rows that meet its condition. For example, this query returns one row per region, with totals for all orders, paid orders, refunded orders, and paid revenue:
SELECT
region,
COUNT(*) AS all_orders,
SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END) AS paid_orders,
SUM(CASE WHEN status = 'refunded' THEN 1 ELSE 0 END) AS refunded_orders,
SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END) AS paid_revenue
FROM orders
GROUP BY region;
For each order, the CASE expression contributes 1 to the paid-order sum only when its status is paid, and 1 to the refunded-order sum only when its status is refunded. The paid-revenue expression contributes the order’s amount only for paid orders. The grouping still determines the output grain: there is one result row per region, not one row per status.
Some database systems support aggregate FILTER, which expresses a condition directly on an aggregate:
SELECT
region,
COUNT(*) AS all_orders,
COUNT(*) FILTER (WHERE status = 'paid') AS paid_orders,
SUM(amount) FILTER (WHERE status = 'paid') AS paid_revenue
FROM orders
GROUP BY region;
CASE inside an aggregate is a portable pattern; use FILTER only where the database supports it. Be deliberate about NULL: SUM ignores null inputs, and a CASE without ELSE returns NULL when its condition is false. Use ELSE 0 when a nonmatching row should contribute zero to a sum, including when no rows match a segment.
Protect metrics when joins multiply rows
Protect metrics when joins multiply rows
Before combining tables and aggregating, check the grain: what entity does each row represent, and at what level should the metric be calculated? A join returns a row for each matching pair. If one order matches several rows in order_items, the joined result contains several rows for that order. This is normal when an order has multiple items—but summing an order-level amount after the join repeats that amount once per item. Joining two separate one-to-many tables can multiply rows further.
For example, this query can overstate revenue when an order has multiple matching items:
SELECT
o.region,
SUM(o.amount) AS revenue
FROM orders AS o
JOIN order_items AS i
ON i.order_id = o.order_id
GROUP BY o.region;
The issue is not automatically bad or duplicated source data. The question is whether the join’s multiplicity matches the grain of the metric. To inspect how many joined rows each order produces, count them per order:
SELECT
o.order_id,
COUNT(*) AS joined_rows
FROM orders AS o
JOIN order_items AS i
ON i.order_id = o.order_id
GROUP BY o.order_id
HAVING COUNT(*) > 1;
A count above one may simply mean that an order has multiple items. To investigate suspected duplicate source records, group by the columns expected to uniquely identify a record and check for counts greater than one. Also verify that the join uses the complete intended key: joining on a non-unique attribute or omitting part of a composite key can create unexpected matches. Comparing row counts and sums before and after a join can help reveal where multiplicity changes a measure.
One way to avoid repeating an order-level amount is to summarize items to one row per order before joining that summary to orders:
WITH items_per_order AS (
SELECT
order_id,
COUNT(*) AS item_count
FROM order_items
GROUP BY order_id
)
SELECT
o.region,
COUNT(*) AS order_count,
SUM(o.amount) AS revenue,
SUM(COALESCE(i.item_count, 0)) AS item_count
FROM orders AS o
LEFT JOIN items_per_order AS i
ON i.order_id = o.order_id
GROUP BY o.region;
items_per_order has at most one row per order_id, so joining it cannot multiply an order row. The LEFT JOIN retains orders with no matching item summary; COALESCE(i.item_count, 0) represents a missing summary as zero. This preserves the order-level grain for COUNT(*) and SUM(o.amount) while including the item counts.
COUNT(DISTINCT o.order_id) can be appropriate when the intended metric is a count of distinct orders. It does not repair a multiplied sum. Nor is SUM(DISTINCT o.amount) a general fix: different orders can legitimately have the same amount, and the distinct sum would count that amount only once.