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):
| abbrev | name |
|---|---|
| AK | Alaska |
| CA | California |
| NV | Nevada |
| PR | Puerto Rico |
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 |
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 |
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):
| name | n |
|---|---|
| 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 |
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_rows | distinct_quakes |
|---|---|
| 902 | 902 |
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):
| ending | n |
|---|---|
| Alaska | 653 |
| CA | 56 |
| Puerto Rico | 45 |
| New Mexico | 42 |
| Texas | 32 |
| Hawaii | 26 |
| Nevada | 16 |
| Utah | 6 |
| Wyoming | 5 |
| Washington | 5 |
| Oregon | 5 |
| California | 3 |
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):
| region | n |
|---|---|
| U.S. Virgin Islands | 32 |
| Guam | 14 |
| Northern Mariana Islands | 13 |
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 |
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):
| name | n |
|---|
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_rows | distinct_names | missing_pop | zero_or_negative_pop |
|---|---|---|---|
| 52 | 52 | 0 | 0 |
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_names | found_in_population |
|---|---|
| 16 | 16 |
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):
| name | events | events_per_million |
|---|---|---|
| Alaska | 653 | 882.27 |
| New Mexico | 42 | 19.72 |
| Hawaii | 26 | 17.98 |
| Puerto Rico | 45 | 14.05 |
| Wyoming | 5 | 8.51 |
| Nevada | 17 | 5.2 |
| Utah | 6 | 1.71 |
| California | 59 | 1.5 |
| Oregon | 5 | 1.17 |
| Texas | 32 | 1.02 |
| Washington | 5 | 0.63 |
A few details are doing real work in that query:
- The CTE (
per_state) builds the per-state counts first, so the population join happens on one clean row per name. HAVING COUNT(*) >= 5drops the five names with fewer than 5 events (Colorado 2, Kansas 2, Idaho 1, Montana 1, Oklahoma 1), where a rate per million would be mostly noise.1000000.0, not1000000. In SQLite, dividing two whole numbers gives a whole number. The.0forces decimal math.p.sumlev = '040'is text, with a leading zero, as covered above.
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
- Look at the key on both sides and list every form it takes.
- Test each part of a multi-part join condition separately.
- Compare joined rows to distinct source rows to catch double matches.
- Read what matched, because the right row count can still hide wrong matches.
- Inspect what didn't match, and decide if that's correct. A high match rate isn't the goal.
- 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.