Timedora

Reliable SQL Joins and Aggregation

A practical lesson on choosing joins, preserving the intended result grain, validating counts, and avoiding inflated aggregates.

, Keys, and Join Behavior

Start with the meaning of one row

Before writing a join, state the you want: what should each result row represent? It might be one row per customer, one row per order, or one row per customer-order pair. This decision is the standard for judging whether repeated rows are correct or a problem.

A is the column—or set of columns—that identifies related rows. A primary key uniquely identifies a row; a foreign key commonly refers to a primary key in another table. For example, orders.customer_id can refer to customers.customer_id. If the relationship depends on a composite key, include every column in that key: leaving one out can match rows that are not actually related. A uniqueness constraint on the referenced key helps ensure each row matches at most one row on that side.

Predict what the join will do

describes how many rows can match. In a one-to-one relationship, each side has at most one match. In a one-to-many relationship, one row on one side may match several on the other, as one customer may have many orders. In a many-to-many relationship, multiple rows on each side may match, often through a bridge table.

For each left-side row, a join produces a row for every right-side row that satisfies the join condition. So a join does not automatically preserve the number of left-side rows. If the result is meant to have one row per customer, joining customers to orders repeats a customer who has several orders. That repetition is not inherently wrong: it is appropriate if the intended is one row per customer-order pair.

Consider an order with three items and two payments. Joining both child tables directly to the order can create six rows: each item is paired with each payment. Order-level measures may then be repeated. Predicting this multiplication from the intended and relationship helps catch problems before totals are calculated.

Choose which unmatched rows remain

An inner join returns only matching row pairs; use it when unmatched rows should be excluded. A left join retains every row from the left table and adds matching right-side rows. If there is no match, the right-side columns are NULL. Use it when the left table defines the population you need to keep. A full outer join retains unmatched rows from both sides.

For example, this query retains customers even when they have no orders:

SELECT
    c.customer_id,
    c.customer_name,
    o.order_id
FROM customers AS c
LEFT JOIN orders AS o
    ON o.customer_id = c.customer_id;

It has one row per customer only if each customer has at most one matching order. Customers with multiple orders appear multiple times, which is correct if the result is customer-order.

Filter placement matters when a left join must retain customers without a qualifying order. Put the order-date condition in ON:

SELECT
    c.customer_id,
    o.order_id
FROM customers AS c
LEFT JOIN orders AS o
    ON o.customer_id = c.customer_id
   AND o.order_date >= DATE '2026-01-01';

The join looks for orders meeting both conditions while preserving every customer. If the date condition is placed in WHERE instead, rows with a NULL order date generally fail that condition and customers without a qualifying order are removed. For an outer join, ON controls which right-side rows match; WHERE filters the resulting rows, including preserved rows with NULL values.

Validate Rows and Counts

Check keys before and after joining

If a key is supposed to identify one row, test that assumption rather than relying on it. Group by the key and use (*) > 1 to find duplicates:

SELECT customer_id, COUNT(*) AS rows_per_customer
FROM customers
GROUP BY customer_id
HAVING COUNT(*) > 1;

Also check the right-hand . If it occurs multiple times, one left-side row can match several right-side rows and repeat in the join result:

SELECT customer_id, COUNT(*) AS orders_per_customer
FROM orders
GROUP BY customer_id
HAVING COUNT(*) > 1;

Repeated orders per customer may be expected. The test is whether those rows fit the you chose, not whether every key must always be unique. After each join, compare row counts and repeated-key counts with the source table to see whether the result still matches that intended .

matches in a left join

For a left join, (*) counts the preserved left-side row even if there is no matching right-side row. To matches, a non-nullable identifier from the right table instead. For example:

SELECT
    c.customer_id,
    COUNT(o.order_id) AS order_count,
    COUNT(CASE WHEN o.status = 'paid' THEN 1 END) AS paid_order_count
FROM customers AS c
LEFT JOIN orders AS o
    ON o.customer_id = c.customer_id
GROUP BY c.customer_id;

Here, (o.order_id) counts matched orders. The conditional includes only rows for which o.status = 'paid'; when the condition is not met, the CASE expression has no value to . This lets the query report all customers, including those with zero matched orders, while distinguishing total matches from qualifying matches.

GROUP BY creates groups, and filters groups. Neither determines whether the chosen makes sense: that comes from the business question and the keys. Grouping also cannot reverse row multiplication that occurred earlier in the query.

Aggregate Before Combining Child Tables

Why two child joins can inflate totals

Suppose the intended result is one row per order, and an order has three item rows and two payment rows. Joining both child tables directly to orders creates six combinations for that order: each item is paired with each payment. An item total is therefore repeated across payment matches, and a payment total across item matches. Summing either measure after that multiplication can inflate the result.

Grouping after the join does not undo the repeated rows. Nor is DISTINCT a general repair: it can hide symptoms or remove legitimate rows without correcting the multiplication that affected aggregates.

Summarize each child table first

Instead, aggregate each child table to the intended —here, order_id—before combining the summaries with orders:

WITH item_totals AS (
    SELECT order_id, SUM(quantity * unit_price) AS item_total
    FROM order_items
    GROUP BY order_id
),
payment_totals AS (
    SELECT order_id, SUM(amount) AS payment_total
    FROM payments
    GROUP BY order_id
)
SELECT
    o.order_id,
    COALESCE(i.item_total, 0) AS item_total,
    COALESCE(p.payment_total, 0) AS payment_total
FROM orders AS o
LEFT JOIN item_totals AS i
    ON i.order_id = o.order_id
LEFT JOIN payment_totals AS p
    ON p.order_id = o.order_id;

The first summary computes one item total per order; the second computes one payment total per order. Each therefore has at most one row per order_id. Joining those summaries to the orders table preserves the one-row-per-order , assuming orders.order_id uniquely identifies an order. displays zero when no summary row matches; use it when zero is the value the result should show for that absence.

The general safeguard is to decide the required first, aggregate each one-to-many child table to the key for that , and then join the summaries. Check key uniqueness and inspect row counts as you build the query. Use DISTINCT only when the desired result itself calls for distinct rows, not as a substitute for understanding join .

  • : Summarizing child-table rows to one row per intended before joining that summary to other tables.