HP

Blog · · 2 min read

The join that made twelve times too many rows

Joining yearly rent data to monthly unemployment data created a 12x fan-out. What grain means, how it happens, and how I documented the fix.

SQLData engineering

In Maple, my civic data project, I combine public Canadian datasets. Two of them were at different time resolutions: rent figures by year and unemployment figures by month. Joining them taught me what "grain" means.

What grain is

The grain of a table is what one row represents. A table with one row per city per year has a yearly grain. A table with one row per city per month has a monthly grain.

How the fan-out happens

Say I join on city and year, ignoring that unemployment has twelve rows per year:

select r.city, r.year, r.avg_rent, u.unemployment_rate
from rent_yearly r
join unemployment_monthly u
  on u.city = r.city
 and u.year = r.year;

Each yearly rent row matches twelve monthly rows. The result has twelve times as many rows as the rent table. If I now add up rent, I count each city's rent twelve times. The query runs, the numbers look plausible, and they are 12x wrong. There is no error message.

This is a silent analytical error. It was one of the reasons I started the project: public data portals publish useful datasets, but mismatched time resolutions cause join fan-out and wrong answers.

The fix

You have to decide the grain you want and bring both tables to it before you join. Two common choices:

  • Average the monthly data to the year, then join one row to one row.
  • Repeat the yearly value across the twelve months, then join month to month.

Which is right depends on the question. Comparing yearly rent with a yearly average unemployment rate fits the first. Which of the two I picked matters less than writing it down.

Writing it down

I documented the decision in an Architecture Decision Record, a short note with the problem, the options and the choice. Six months from now, that note answers "why is this table yearly?".

A test to catch it again

A row count check guards against the same mistake. After the join, assert that the number of rows equals the number of rows in the table you meant to keep, or that the join key is unique. In dbt, a unique test on the grain columns does this in one line.

The project has 69 dbt models passing, 13 automated checks, 24 Dagster assets and 6 datasets. Details are on my portfolio.