Why it matters
A dashboard can report the wrong total even when every row in both tables is correct.
Core concepts
Grain
Say what one row represents before you join. Orders and attached files have different grains.
Left join
A left join keeps every order. An order with two files contributes two rows. An order with no files still contributes one row with empty file fields.
Try it step by step
- Run the read-only query in a SQLite or PostgreSQL practice editor.
- Predict the three numbers before looking at the result.
- Add a second file for order 102. Predict which counts change.
Read the result left to right as joined rows, distinct orders and matched files.
Worked example
The original query returns 4, 3 and 3. Adding one file for order 102 changes those values to 5, 3 and 4.
WITH orders(id) AS (VALUES (101), (102), (103)),
files(file_id, order_id) AS (VALUES (1,101), (2,101), (3,102))
SELECT COUNT(*) AS joined_rows,
COUNT(DISTINCT o.id) AS orders,
COUNT(f.file_id) AS files
FROM orders o
LEFT JOIN files f ON f.order_id = o.id;Common mistake
Counting all joined rows as orders. An order with more files then carries more weight.
Practice exercise
Change the left join to an inner join. Which order disappears? Explain the new distinct order count.
Check your understanding
Which measure still counts an order with zero files once?
- COUNT(f.file_id)
- COUNT(DISTINCT o.id) with the left join
- COUNT(*) after an inner join
Show answer
COUNT(DISTINCT o.id) with the left join. Choose the count based on the thing the report promises to measure.
Takeaway
Choose the count based on the thing the report promises to measure.