Cleaning messy text labels in SQL with LIKE, instr and substr
Numbers break in obvious ways: a -1 here, a NULL there. Text breaks in subtle ways. The same thing gets spelled two ways, abbreviated sometimes, buried inside a longer string, or left out. Before you can group, filter or join on a text column, you usually have to clean it, and the first step is admitting that it needs cleaning.
The place column in this site's quakes table is a great example. USGS writes a human-readable description for every event, like 52 km W of Petrolia, CA or 197 km NW of Port-Olry, Vanuatu. It's written for people, not for databases.
Look before you clean
Start by sorting the rows into rough shapes. Does the place have a comma? Is it missing?
SELECT CASE
WHEN place IS NULL THEN '(missing)'
WHEN place NOT LIKE '%,%' THEN '(no comma)'
ELSE 'has comma'
END AS shape,
COUNT(*) AS n
FROM quakes
GROUP BY shape;Output (real run against the practice database):
| shape | n |
|---|---|
| (missing) | 1 |
| (no comma) | 216 |
| has comma | 2411 |
Most rows follow the "distance, direction, town, region" pattern. Of the 2,628 rows, 2,411 have a comma, 216 have no comma, and 1 is missing:
| Shape | Rows | Share |
|---|---|---|
| Has a comma | 2,411 | 91.7% |
| No comma | 216 | 8.2% |
| Missing | 1 | 0.04% |
SELECT place, COUNT(*) AS n
FROM quakes
WHERE place NOT LIKE '%,%'
GROUP BY place
ORDER BY n DESC
LIMIT 6;Output (real run against the practice database):
| place | n |
|---|---|
| south of the Fiji Islands | 36 |
| Reykjanes Ridge | 20 |
| South Sandwich Islands region | 14 |
| northern Mid-Atlantic Ridge | 12 |
| Fiji region | 11 |
| central Mid-Atlantic Ridge | 9 |
Most of these no-comma rows are offshore regions: ocean ridges and island groups, with no nearby town to measure from. A few are not. western Xizang (3 rows) is inland. Any rule you write for "the region after the comma" has to handle the no-comma rows separately, or they'll quietly turn into garbage.
The same place, spelled two ways
Search for California and you hit the first real inconsistency:
SELECT COUNT(*) AS short_code
FROM quakes
WHERE place LIKE '%, CA';Output (real run against the practice database):
| short_code |
|---|
| 56 |
SELECT place
FROM quakes
WHERE place LIKE '%, California';Output (real run against the practice database):
| place |
|---|
| 236 km W of Ferndale, California |
| 238 km W of Ferndale, California |
| 235 km W of Ferndale, California |
Most California events end in the two-letter code CA (56 of them), but a few offshore events end in the full word (3, all west of Ferndale). If you only searched for one form, your count would be wrong, and nothing would warn you. The fix is to check for both forms:
SELECT COUNT(*) AS california_events
FROM quakes
WHERE place LIKE '%, CA'
OR place LIKE '%, California';Output (real run against the practice database):
| california_events |
|---|
| 59 |
That combined count is 59.
A note on LIKE and letter case
By default, SQLite's LIKE is case-insensitive for ASCII letters, and = is case-sensitive unless a different collation is used:
SELECT 'CA' LIKE 'ca' AS like_result,
'CA' = 'ca' AS equals_result,
LOWER('CA') = 'ca' AS lower_equals_result;Output (real run against the practice database):
| like_result | equals_result | lower_equals_result |
|---|---|---|
| 1 | 0 | 1 |
That behavior differs between databases. PostgreSQL's LIKE is case-sensitive, for example. LOWER() or UPPER() on both sides helps you write a comparison that works the same way everywhere, though Unicode handling varies: they are reliable for plain English letters, but not every database folds accented or non-Latin characters the same way.
Pulling out the part you need
To count events by location label, you need the text after the comma. A common first attempt uses instr (the position of a substring) and substr (cut from a position). In SQLite that looks like substr(place, instr(place, ', ') + 2). Step by step:
instr(place, ', ')returns the position of the first comma-space, or0if it isn't there.- Adding
2skips the comma and the space. substr(place, that number)returns everything from there to the end of the string.
In standard SQL, the close equivalents are POSITION(', ' IN place) and SUBSTRING(place FROM ... ). SQL Server uses CHARINDEX and SUBSTRING. The idea is the same; only the function names change.
It works for many rows, and it breaks on others.
Where the first-comma extraction works and breaks
These four strings are all in the quakes table:
| Place | substr(place, instr(place, ', ') + 2) |
What happened |
|---|---|---|
52 km W of Petrolia, CA |
CA |
Works |
236 km W of Ferndale, California |
California |
Works, but it's a different spelling from CA |
Rat Islands, Aleutian Islands, Alaska |
Aleutian Islands, Alaska |
Breaks: instr finds the first comma, not the last |
Reykjanes Ridge |
eykjanes Ridge |
Breaks: no comma, so instr returns 0, and substr(place, 2) drops the first letter |
SELECT place,
instr(place, ', ') AS first_comma,
substr(place, instr(place, ', ') + 2) AS after_first_comma
FROM quakes
WHERE place IN (
'52 km W of Petrolia, CA',
'236 km W of Ferndale, California',
'Rat Islands, Aleutian Islands, Alaska',
'Reykjanes Ridge'
)
GROUP BY place
ORDER BY first_comma DESC;Output (real run against the practice database):
| place | first_comma | after_first_comma |
|---|---|---|
| 236 km W of Ferndale, California | 21 | California |
| 52 km W of Petrolia, CA | 20 | CA |
| Rat Islands, Aleutian Islands, Alaska | 12 | Aleutian Islands, Alaska |
| Reykjanes Ridge | 0 | eykjanes Ridge |
The first-comma approach is the wrong tool once a string can contain more than one comma, or none.
An intermediate trick for the last comma
SQLite doesn't have a "find the last comma" function. A well-known intermediate technique uses replace and rtrim. It's the SQLite form of the problem; it isn't the only way, and it isn't the first function you should reach for in every database.
Two things to know before the expression makes sense. First, rtrim(x, chars) treats chars as a set of characters, not as a suffix. rtrim('Mississippi', 'ippi') returns Mississ, not Miss, because every trailing i or p gets stripped, not the letters ippi as a block. Second, the trick uses that set behavior on purpose.
For Rat Islands, Aleutian Islands, Alaska, the steps are:
replace(place, ',', '')removes the commas. The result is used only as the character set for the next step: every letter and space in the string, but not the comma.rtrim(place, that set)strips characters from the right of the original string until it hits one that isn't in the set. The only character not in the set is the comma, so it stops there. What's left is everything up to and including the last comma:Rat Islands, Aleutian Islands,.replace(place, that prefix, '')removes that prefix from the original string and leaves the tail:Alaska.TRIM(...)removes the leading space and leavesAlaska.
SELECT TRIM(replace(place, rtrim(place, replace(place, ',', '')), '')) AS location_label,
COUNT(*) AS n
FROM quakes
WHERE place LIKE '%,%'
GROUP BY location_label
ORDER BY n DESC
LIMIT 12;Output (real run against the practice database):
| location_label | n |
|---|---|
| Alaska | 653 |
| Vanuatu | 293 |
| Panama | 161 |
| Indonesia | 145 |
| Russia | 98 |
| Japan | 68 |
| China | 65 |
| Papua New Guinea | 63 |
| Philippines | 62 |
| CA | 56 |
| Puerto Rico | 45 |
| New Mexico | 42 |
That's ugly but effective. In databases that have REVERSE, a more readable version is to reverse the string, cut at the first comma, and reverse the tail back. Standard SQL's POSITION and SUBSTRING handle a first delimiter cleanly; the last one usually needs REVERSE, a regular expression, or a split function.
This table has no trailing commas, and the query above also filters to rows that contain a comma, which keeps the trick out of trouble here. It's still worth knowing the edges, because rtrim does not mean "remove this suffix." Against test strings:
- A
NULLplace staysNULL. - Multiple commas correctly return the last label (
Alaska, orMXfromB.C., MX). - A string with no comma, like
Reykjanes Ridgeorwestern Xizang, comes back unchanged — the whole place is treated as the label. That's why theWHERE place LIKE '%,%'filter matters. - A trailing comma yields a blank label. There are no such rows in this table, but a typo could create one.
Repeated letters in the tail don't break the extraction, because the set-of-characters behavior is what makes the trick work.
The top of the result is Alaska 653, Vanuatu 293, Panama 161, Indonesia 145, Russia 98, Japan 68, China 65, Papua New Guinea 63, Philippines 62, CA 56, Puerto Rico 45, and New Mexico 42. The remaining 660 of the 2,411 comma rows are in smaller groups not shown in this top 12. These are location labels, not one kind of place. Alaska is a state; Vanuatu and Panama are countries. Standardized spelling doesn't mean standardized meaning.
Now look at that list with fresh eyes. CA sits in it as if it were a separate location from California, and other short codes are hiding further down:
SELECT TRIM(replace(place, rtrim(place, replace(place, ',', '')), '')) AS location_label,
COUNT(*) AS n
FROM quakes
WHERE place LIKE '%,%'
AND length(TRIM(replace(place, rtrim(place, replace(place, ',', '')), ''))) <= 3
GROUP BY location_label;Output (real run against the practice database):
| location_label | n |
|---|---|
| CA | 56 |
| MX | 5 |
| NV | 1 |
Three short codes show up: CA (56) and NV (1) for two US states, and MX (5) for Mexico. Everything else in this short list is a full name. Filtering on short labels like this is a quick way to find abbreviations in any text column.
From extraction to a clean label
Once you know the variants, map them to one standard label with CASE:
SELECT CASE TRIM(replace(place, rtrim(place, replace(place, ',', '')), ''))
WHEN 'CA' THEN 'California'
WHEN 'NV' THEN 'Nevada'
WHEN 'MX' THEN 'Mexico'
ELSE TRIM(replace(place, rtrim(place, replace(place, ',', '')), ''))
END AS location_label,
COUNT(*) AS n
FROM quakes
WHERE place LIKE '%,%'
GROUP BY location_label
ORDER BY n DESC
LIMIT 8;Output (real run against the practice database):
| location_label | n |
|---|---|
| Alaska | 653 |
| Vanuatu | 293 |
| Panama | 161 |
| Indonesia | 145 |
| Russia | 98 |
| Japan | 68 |
| China | 65 |
| Papua New Guinea | 63 |
After that mapping, California is 59 and ranks 10th — just below the Philippines at 62 — so a LIMIT 8 still hides it. Mexico is 35 and Nevada is 17. The top of the list is unchanged at the high end: Alaska 653 through Papua New Guinea 63.
On a bigger project, you wouldn't hard-code that list in a CASE. You'd keep a small mapping table and join to it, which is exactly what the guide on joining messy keys covers. But for a one-off analysis, a CASE you can read top to bottom is fine. It also documents your cleaning decisions in the query itself. And a clean spelling is still just a spelling: California is a US state in this column, and Mexico is a country. Standardized spelling doesn't mean standardized meaning.
Check for invisible differences
Two labels can look identical on screen and still fail an = comparison because one has a trailing space, a tab or a non-breaking space copied from a web page. It's worth one quick query to confirm that a text column doesn't have stray whitespace at either end:
SELECT COUNT(*) AS rows_with_extra_spaces
FROM quakes
WHERE place <> TRIM(place);Output (real run against the practice database):
| rows_with_extra_spaces |
|---|
| 0 |
That check returns 0: no non-NULL rows have leading or trailing ordinary spaces detectable by place <> TRIM(place). This column comes back clean of ordinary spaces, which is good news, but you only know that because you checked. On data typed in by people, or exported from spreadsheets, this count is often far from zero. The fix is the same TRIM() you used above, applied before grouping or joining. TRIM only removes ordinary spaces by default. Tabs and non-breaking spaces need TRIM(col, char(9)) or replace(). If a count still looks wrong after trimming, compare length(col) with what you see. A label that's one character longer than it looks is hiding something.
What to take away
- Profile the shapes first. Group rows by pattern (has a comma, no comma, missing) before writing an extraction rule.
- Search for every spelling. Codes and full names often live side by side in the same column.
- Know your database's LIKE. By default it's case-insensitive for ASCII letters in SQLite, and case-sensitive in PostgreSQL.
LOWER()orUPPER()helps, though Unicode handling varies. - Test extraction on the weird rows, not just the typical ones. Multiple commas and missing delimiters are where rules break — including the first-letter drop when
instrreturns0. - Make cleaning decisions visible in a
CASEor a mapping table so others can check them. And remember that a standardized spelling is not the same thing as a standardized meaning.
Practice it
Try California, spelled two ways, Events per day (which extracts the date from a text timestamp) and Match earthquakes to US states in the practice section.