Data Cleaning Reps

← All guides

Joining tables when the keys don't match

Textbook joins are easy: the customer_id in one table matches the customer_id in the other. Real joins often look more like this: one table says 52 km W of Petrolia, CA, another says California, and a third stores population for California alongside regional totals you have to filter out. This guide walks through that kind of join on this site's data, and through the checks that tell you whether the join actually worked.

The tables are quakes (2,628 USGS seismic events from October 2026), state_abbrev (a state-level geographic lookup with 52 two-letter codes and their names: the 50 states, DC and Puerto Rico) and state_population (U.S. Census Bureau population estimates, 66 rows). As Guide 1 found, two of the quakes rows aren't earthquakes: 2,626 are earthquakes, one is a landslide and one is an explosion. The counts below include all 2,628 so they add up to the table.

Here is the whole idea on three real rows:

place What the join looks for Result
52 km W of Petrolia, CA the code CA after the last comma matches California
Rat Islands, Aleutian Islands, Alaska the name Alaska after the last comma matches Alaska
197 km NW of Port-Olry, Vanuatu neither a code nor a name no match

Step 1: understand both sides of the key

On the seismic-event side, US locations end in either a two-letter code or a full name. On the lookup side, state_abbrev has both forms in separate columns:

SELECT abbrev, name FROM state_abbrev WHERE abbrev IN ('AK', 'CA', 'NV', 'PR');

Output (real run against the practice database):

abbrevname
AKAlaska
CACalifornia
NVNevada
PRPuerto Rico
4 rows

So the join condition has to accept either form. In SQLite, || joins strings together, so '%, ' || s.abbrev builds a pattern like %, CA.

Step 2: test each half of the condition separately

Before combining conditions with OR, see how many rows each one matches on its own:

SELECT COUNT(*) AS matched_by_code
FROM quakes q
JOIN state_abbrev s ON q.place LIKE '%, ' || s.abbrev;

Output (real run against the practice database):

matched_by_code
57
1 row
SELECT COUNT(*) AS matched_by_name
FROM quakes q
JOIN state_abbrev s ON q.place LIKE '%, ' || s.name;

Output (real run against the practice database):

matched_by_name
845
1 row

Most matches come from full names: 845 of them, 653 in Alaska alone. In this table, USGS spells Alaska out every time (none end in , AK). A smaller group, 57, comes from codes: 56 end in , CA and one in , NV. If either number were zero, the pattern would be wrong, and it's much easier to spot that now than inside a bigger query.

Step 3: combine, then count per state

SELECT s.name, COUNT(*) AS n
FROM quakes q
JOIN state_abbrev s
  ON q.place LIKE '%, ' || s.abbrev
  OR q.place LIKE '%, ' || s.name
GROUP BY s.name
ORDER BY n DESC, s.name;

Output (real run against the practice database):

namen
Alaska653
California59
Puerto Rico45
New Mexico42
Texas32
Hawaii26
Nevada17
Utah6
Oregon5
Washington5
Wyoming5
Colorado2
16 rows, first 12 shown

Sixteen names match, 902 events in all: Alaska 653, California 59, Puerto Rico 45, New Mexico 42, Texas 32, Hawaii 26, Nevada 17, Utah 6, Oregon 5, Washington 5, Wyoming 5, Colorado 2, Kansas 2, and one each for Idaho, Montana and Oklahoma. Alaska dominates. California's 59 include both spellings: 56 end in , CA and 3 in , California. The 902 are 901 earthquakes plus the explosion near Granite Falls, Washington. The landslide in Nepal doesn't match.

Step 4: check for double matches, then for wrong matches

A join can go wrong in two different ways, and they need two different checks.

Double matches. A join with OR, or with LIKE, can match one event to more than one lookup row. Compare the number of joined rows with the number of distinct events that matched:

SELECT (SELECT COUNT(*)
        FROM quakes q
        JOIN state_abbrev s
          ON q.place LIKE '%, ' || s.abbrev OR q.place LIKE '%, ' || s.name) AS joined_rows,
       (SELECT COUNT(*)
        FROM quakes q
        WHERE EXISTS (SELECT 1 FROM state_abbrev s
                      WHERE q.place LIKE '%, ' || s.abbrev OR q.place LIKE '%, ' || s.name)) AS distinct_quakes;

Output (real run against the practice database):

joined_rowsdistinct_quakes
902902
1 row

Both numbers are 902, so every matched event matched exactly one lookup row. If joined_rows were bigger, some places would be matching two patterns, and the per-state counts would be inflated. This check takes ten seconds and catches one of the most common silent errors in SQL.

Wrong matches. The check above can't tell you whether the one match was the right one. A seismic event near Tbilisi in the country of Georgia would match the US state of Georgia exactly once, so joined_rows and distinct_quakes would still agree. A join can have the correct number of rows and still match the wrong records. The check for that is to look at what actually matched. Here is every distinct ending that matched:

SELECT TRIM(replace(place, rtrim(place, replace(place, ',', '')), '')) AS ending,
       COUNT(*) AS n
FROM quakes q
WHERE EXISTS (SELECT 1 FROM state_abbrev s
              WHERE q.place LIKE '%, ' || s.abbrev OR q.place LIKE '%, ' || s.name)
GROUP BY ending
ORDER BY n DESC;

Output (real run against the practice database):

endingn
Alaska653
CA56
Puerto Rico45
New Mexico42
Texas32
Hawaii26
Nevada16
Utah6
Wyoming5
Washington5
Oregon5
California3
18 rows, first 12 shown

There are 18 endings: the 16 names plus the codes CA and NV. Read down the list and every one is a US place. No place in this table ends in Georgia, so there is no clash here, but you only know that because you looked.

Step 5: check what didn't match

An inner join silently drops rows that don't match. Here, 902 of 2,628 events (34.3%) matched and 1,726 didn't: 1 has a NULL place, 216 have no comma, and 1,509 have a comma but don't end in a lookup name or code. A high match rate isn't the goal. The right rate depends on the question, and a report on US states should leave out events in Japan or Vanuatu. What matters is that you know why each group was dropped.

Some of those drops are correct (events in Japan shouldn't match a US state), but some might not be. Look at US-related places that fell through:

SELECT TRIM(replace(place, rtrim(place, replace(place, ',', '')), '')) AS region,
       COUNT(*) AS n
FROM quakes q
WHERE place LIKE '%,%'
  AND NOT EXISTS (SELECT 1 FROM state_abbrev s
                  WHERE q.place LIKE '%, ' || s.abbrev OR q.place LIKE '%, ' || s.name)
  AND (place LIKE '%U.S.%' OR place LIKE '%Guam' OR place LIKE '%Mariana Islands')
GROUP BY region
ORDER BY n DESC;

Output (real run against the practice database):

regionn
U.S. Virgin Islands32
Guam14
Northern Mariana Islands13
3 rows

The U.S. Virgin Islands (32), Guam (14) and the Northern Mariana Islands (13) aren't in state_abbrev, so they drop out. Whether that's right depends on the question. For a "US states" report it's correct. For a "US and territories" report you'd add them to the lookup table. The point is to make that decision on purpose.

That query has a blind spot of its own. It only looks at places with a comma, so it misses US-area labels without one: off the coast of Oregon (3), Gulf of Alaska (2), off the coast of Southeastern Alaska (1), south of the Aleutian Islands (1) and Mariana Islands region (7).

The other direction: lookup rows with no events

The check above looked for events that didn't find a state. It's just as useful to flip it around and ask which lookup rows didn't find any events. A LEFT JOIN keeps every row from the left table even without a match, and counting a column from the right table gives zero for those rows:

SELECT COUNT(*) AS states_with_zero_events
FROM (
  SELECT s.name
  FROM state_abbrev s
  LEFT JOIN quakes q
    ON q.place LIKE '%, ' || s.abbrev OR q.place LIKE '%, ' || s.name
  GROUP BY s.name
  HAVING COUNT(q.id) = 0
);

Output (real run against the practice database):

states_with_zero_events
36
1 row

36 of the 52 lookup rows have no events matching our current text rules. That doesn't prove there was no activity, because some offshore labels are missed (the no-comma labels above point at Oregon and Alaska, which already have matches, so they don't change the 36 this month, but the same gap could hide others in another month). It matters either way: an inner join would make those rows vanish from a chart entirely, instead of showing them as zero. Use COUNT(q.id), not COUNT(*). COUNT(*) would count the unmatched row itself and report 1 instead of 0.

Step 6: join a third table, carefully

The next step is practice with normalization: dividing a count by another measurement so groups of different sizes can be compared. It is not a measure of earthquake hazard or risk, since earthquakes are geological and don't depend on how many people live nearby. Keep one more caveat in view: the event counts come from October 2026, and the population denominator is from 2024.

The Census table mixes the nation (sumlev 010), 4 regions (020), 9 divisions (030) and 52 state-level rows (040, including DC and Puerto Rico) in one file. Join only to the state-level rows. Before you do, validate that side of the join the same way you validated the first one.

First, are there repeated names among the state-level rows?

SELECT name, COUNT(*) AS n
FROM state_population
WHERE sumlev = '040'
GROUP BY name
HAVING COUNT(*) > 1;

Output (real run against the practice database):

namen
0 rows

It returns no rows. Second, are any population values missing or zero?

SELECT COUNT(*) AS state_rows,
       COUNT(DISTINCT name) AS distinct_names,
       SUM(pop2024 IS NULL) AS missing_pop,
       SUM(pop2024 <= 0) AS zero_or_negative_pop
FROM state_population
WHERE sumlev = '040';

Output (real run against the practice database):

state_rowsdistinct_namesmissing_popzero_or_negative_pop
525200
1 row

That gives 52 rows, 52 distinct names, 0 missing and 0 zero or negative (the smallest pop2024 is 587,618). Third, does every matched name find a population row?

SELECT COUNT(*) AS matched_names,
       COUNT(p.name) AS found_in_population
FROM (SELECT DISTINCT s.name
      FROM quakes q
      JOIN state_abbrev s
        ON q.place LIKE '%, ' || s.abbrev OR q.place LIKE '%, ' || s.name) m
LEFT JOIN state_population p
  ON p.name = m.name AND p.sumlev = '040';

Output (real run against the practice database):

matched_namesfound_in_population
1616
1 row

All 16 matched names find a row (16 and 16). In this file the names are also unique across all 66 rows, so the sumlev filter doesn't change today's result. It's still the right guard, because it says which level you mean and because every check above only holds for that level.

One detail about that filter. The sumlev column is declared TEXT, and every value is stored as text with its leading zero ('010', '020', '030', '040'). SQLite compares a value with a column using the column's affinity, so sumlev = 40 is compared as the text '40', which isn't '040'. In this table it matches 0 rows, while sumlev = '040' matches 52. Had the file been imported into a whole-number column, the leading zero would already be gone. Whichever way a column is stored, keep the documented text code and its leading zero.

Now the report. It uses a CTE (common table expression), which is a named query result, introduced with WITH, that you can use later in the same statement. It breaks a long query into readable steps.

WITH per_state AS (
  SELECT s.name, COUNT(*) AS n
  FROM quakes q
  JOIN state_abbrev s
    ON q.place LIKE '%, ' || s.abbrev OR q.place LIKE '%, ' || s.name
  GROUP BY s.name
  HAVING COUNT(*) >= 5
)
SELECT p.name,
       ps.n AS events,
       ROUND(ps.n * 1000000.0 / p.pop2024, 2) AS events_per_million
FROM per_state ps
JOIN state_population p
  ON p.name = ps.name AND p.sumlev = '040'
ORDER BY events_per_million DESC;

Output (real run against the practice database):

nameeventsevents_per_million
Alaska653882.27
New Mexico4219.72
Hawaii2617.98
Puerto Rico4514.05
Wyoming58.51
Nevada175.2
Utah61.71
California591.5
Oregon51.17
Texas321.02
Washington50.63
11 rows

A few details are doing real work in that query:

Eleven names remain: Alaska 653 events (882.27 per million), New Mexico 42 (19.72), Hawaii 26 (17.98), Puerto Rico 45 (14.05), Wyoming 5 (8.51), Nevada 17 (5.20), Utah 6 (1.71), California 59 (1.50), Oregon 5 (1.17), Texas 32 (1.02) and Washington 5 (0.63). Puerto Rico is in the list because it's in the lookup table. The ranking changes the story: Alaska is still first, but a small-population state like Wyoming climbs above California, which falls to eighth of the eleven despite having the second-highest raw count. One more detail about the cutoff: Washington's 5 include the explosion near Granite Falls. Without it, Washington would have 4 events, miss the cutoff, and the list would have 10 names.

The join checklist

  1. Look at the key on both sides and list every form it takes.
  2. Test each part of a multi-part join condition separately.
  3. Compare joined rows to distinct source rows to catch double matches.
  4. Read what matched, because the right row count can still hide wrong matches.
  5. Inspect what didn't match, and decide if that's correct. A high match rate isn't the goal.
  6. Validate each lookup table you join to (unique keys, no missing values), and filter it to the right level (states, not regions).

Practice it

Try Match earthquakes to US states and Events per million residents in the practice section. Both are graded against the queries in this guide.

Check your understanding

Six questions on joining messy keys, using the quakes, state_abbrev and state_population tables. Pick an answer to get instant feedback.

0 of 6 answered

  • Correct 0
  • Incorrect 0
  • Accuracy —
1. An INNER JOIN between quakes and state_abbrev (on code or name) matches 902 of the 2,628 events. What does the join return?
2. California has 59 events: 56 end in , CA and 3 end in , California. Which join condition counts all 59?
3. In the guide, joined rows and distinct matched events are both 902. Suppose joined_rows had been 905 instead. What would that mean?
4. customers has 5 rows, and one customer has no orders. You run SELECT c.name, COUNT(*) AS n FROM customers c LEFT JOIN orders o ON o.customer_id = c.id GROUP BY c.name. What does the customer with no orders show?
5. Suppose a seismic event has the place 12 km S of Tbilisi, Georgia (the country), and the lookup has a row for the US state of Georgia. The join uses LIKE '%, ' || s.name. What happens?
6. Before joining the per-state counts to state_population to get events per million, which approach validates the join?

Complete geographic report

Build a report with one row for every row in state_abbrev, all 52 of them, zeros included. Match events to the lookup the same way as in the guide (code or name), return the lookup name and the number of matching seismic events as n, and sort by n from largest to smallest, then by name A to Z. Check your result: 16 rows should be above zero and sum to 902, and 36 should be zero. Bonus tip (not graded): join state_population on sumlev = '040' to add events per million, and remember the numerator is October 2026 while the denominator is 2024.

Tip: Ctrl+Enter (⌘+Enter on Mac) checks your answer. Everything runs in your browser.

Open in the playground