Skip to content

Free guide

Write SQL that counts the right thing

Before writing SELECT, finish this sentence: “One row represents one ____.” The answer determines your joins, exclusions and denominator.

Why it matters

If an order has three status events, a join returns three rows for that order. A revenue total can triple even when every input value is correct.

Core concepts

Read a query in layers

FROM and JOIN identify the inputs. WHERE filters rows, GROUP BY defines groups and aggregates summarize them. A LEFT JOIN keeps rows from the left that lack a match. A WHERE condition on a right-side field can silently remove those unmatched rows.

Reduce before joining

Choose an event grain, order grain or person grain. Aggregate item totals to order grain before joining to a fact at that grain. COUNT(DISTINCT order_id) may repair a count while leaving a SUM overstated. Draw an example with two matching events to catch this.

Window functions

ROW_NUMBER labels rows within a partition while keeping the original rows visible. Order by the business timestamp and a stable tie breaker. Use a CTE or subquery to filter to rank 1. Decide separately whether the business wants the latest state or any state that happened in a period.

Try it step by step

  1. Write the expected output for a tiny input by hand. Include an order with no event and an order with two events.
  2. Run the SQL. Compare row count, distinct order count, and totals before and after each join.
  3. Change a tie, a null and a missing match. Predict each result before running the query again.

Use a grain statement, key uniqueness check and a hand-counted fixture before reviewing performance.

Worked example

Hypothetical example. Orders A and B have values 10 and 20. A has two events, B has none. A direct inner join returns two event rows worth 20 in total and drops B. A left join with only the most recent event keeps both orders and the correct total of 30.

SQL
WITH orders(id, amount) AS (
  VALUES ('A',10), ('B',20)
), events(order_id, seq, state) AS (
  VALUES ('A',1,'created'), ('A',2,'sent')
), ranked AS (
  SELECT order_id, state, ROW_NUMBER() OVER (
    PARTITION BY order_id ORDER BY seq DESC
  ) AS rn FROM events
)
SELECT o.id, o.amount, e.state
FROM orders o LEFT JOIN ranked e
  ON e.order_id = o.id AND e.rn = 1
ORDER BY o.id;

Common mistake

Using DISTINCT across the entire result to hide unexpected duplicates. It can also hide two valid transactions with the same fields.

Practice exercise

Run the read-only example in a SQL scratch database. Expect A, 10, sent and B, 20, null. Change the final LEFT JOIN to JOIN and explain why B disappears.

Check your understanding

One order has two status rows. How should order revenue be protected?

  1. Use SELECT DISTINCT on amounts
  2. Sum order values once at order grain
  3. Round amounts before joining
Show answer

Sum order values once at order grain. Unique amounts are not unique orders. Model or aggregate at the unit of revenue.

Takeaway

Prove the grain before trusting the sum.

Further reading

Browse more lessons