Data Cleaning Reps

← All guides

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):

shapen
(missing)1
(no comma)216
has comma2411
3 rows

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):

placen
south of the Fiji Islands36
Reykjanes Ridge20
South Sandwich Islands region14
northern Mid-Atlantic Ridge12
Fiji region11
central Mid-Atlantic Ridge9
6 rows

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
1 row
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
3 rows

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
1 row

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_resultequals_resultlower_equals_result
101
1 row

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:

  1. instr(place, ', ') returns the position of the first comma-space, or 0 if it isn't there.
  2. Adding 2 skips the comma and the space.
  3. 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):

placefirst_commaafter_first_comma
236 km W of Ferndale, California21California
52 km W of Petrolia, CA20CA
Rat Islands, Aleutian Islands, Alaska12Aleutian Islands, Alaska
Reykjanes Ridge0eykjanes Ridge
4 rows

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:

  1. 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.
  2. 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,.
  3. replace(place, that prefix, '') removes that prefix from the original string and leaves the tail: Alaska.
  4. TRIM(...) removes the leading space and leaves Alaska.
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_labeln
Alaska653
Vanuatu293
Panama161
Indonesia145
Russia98
Japan68
China65
Papua New Guinea63
Philippines62
CA56
Puerto Rico45
New Mexico42
12 rows

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:

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_labeln
CA56
MX5
NV1
3 rows

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_labeln
Alaska653
Vanuatu293
Panama161
Indonesia145
Russia98
Japan68
China65
Papua New Guinea63
8 rows

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
1 row

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

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.

Check your understanding

Six questions on messy text labels, using the quakes place column and short examples from this guide. Pick an answer to get instant feedback.

0 of 6 answered

  • Correct 0
  • Incorrect 0
  • Accuracy —
1. The place column has 2,411 values with a comma, 216 with no comma, and 1 NULL. What does SELECT COUNT(*) FROM quakes WHERE place NOT LIKE '%,%' return?
2. WHERE place LIKE '%, CA' returns 56 rows, and WHERE place LIKE '%, California' returns 3. If you only search for LIKE '%, CA', what do you miss?
3. What does instr('Reykjanes Ridge', ', ') return?
4. What does substr(place, instr(place, ', ') + 2) return for Rat Islands, Aleutian Islands, Alaska?
5. You map CA to California, NV to Nevada, and MX to Mexico, then group the comma rows. What is the California total, and does a LIMIT 8 show it?
6. You run substr(place, instr(place, ', ') + 2) on the no-comma place Reykjanes Ridge. What comes back, and why?

Standardize before reporting

A manager wants a California count from the quakes table, but the place names aren't spelled consistently. Write one query that returns four values: the standardized label California, how many places end in the short code , CA, how many end in the full word , California, and the combined total.

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

Open in the playground