Data Cleaning Reps

← All guides

NULL, blank or -1? Three ways real data says "unknown"

When you learn SQL, "missing" means NULL. When you work with real data, missing can mean NULL, an empty string, a zero, a -1, the text N/A, or a date like 1900-01-01. Each one needs different handling, and each one quietly breaks a different kind of query if you miss it.

This guide uses the vehicles table on this site. It's a subset of the U.S. government's FuelEconomy.gov download covering model years 2010 to 2027. The data is excellent and well documented, and it still has all three kinds of "unknown" in it. That makes it a good place to practice.

Kind 1: real NULLs

The cylinders column is NULL for some rows. The first question is which rows, and why:

SELECT atv_type, COUNT(*) AS n
FROM vehicles
WHERE cylinders IS NULL
GROUP BY atv_type
ORDER BY n DESC;

Output (real run against the practice database):

atv_typen
EV1670
FCV43
eFCV2
3 rows

Every vehicle without a cylinder count is electric or fuel-cell powered. These NULLs aren't errors. They mean "not applicable." An electric motor doesn't have cylinders. That's a useful thing to know before you write AVG(cylinders): the average describes only the vehicles with a reported cylinder count — here, combustion engines — and you should say so.

Kind 2: empty strings that look like NULLs

The atv_type column says what kind of technology a vehicle uses (EV, Hybrid, Diesel and so on). For an ordinary gasoline car, the field is left blank. Here's the catch: in this table, like many tables loaded from CSV files, "blank" was stored as an empty string, not as NULL.

SELECT COUNT(*) AS null_count
FROM vehicles
WHERE atv_type IS NULL;

Output (real run against the practice database):

null_count
0
1 row

Zero. If you stopped there, you'd conclude every vehicle has a technology type. Now check for the empty string:

SELECT COUNT(*) AS blank_count
FROM vehicles
WHERE atv_type = '';

Output (real run against the practice database):

blank_count
16565
1 row

Most of the table. An empty string is a real value. It has a length of zero, but it's not unknown, so IS NULL never matches it, and COUNT(atv_type) counts it. Many CSV import tools turn empty cells into empty strings by default, so expect this whenever data arrived as a spreadsheet or CSV export.

Cleaning blanks with NULLIF and COALESCE

Two small functions fix this. NULLIF(x, '') turns an empty string into a real NULL. COALESCE(x, 'label') replaces a NULL with a label. Together they turn the blank into something readable.

NULLIF returns NULL when its two arguments are equal, and otherwise returns the first argument. COALESCE returns the first non-NULL value among its arguments. So COALESCE(NULLIF(atv_type, ''), 'Conventional') takes three steps: an empty string becomes NULL, a NULL becomes 'Conventional', and a real type like 'EV' passes through unchanged.

SELECT COALESCE(NULLIF(atv_type, ''), 'Conventional') AS tech,
       COUNT(*) AS n
FROM vehicles
GROUP BY tech
ORDER BY n DESC;

Output (real run against the practice database):

techn
Conventional16565
Hybrid1837
EV1670
FFV1114
Plug-in Hybrid464
Diesel405
FCV43
CNG9
eFCV2
Bifuel (CNG)2
10 rows

The six most common types are Conventional (16,565), Hybrid (1,837), EV (1,670), FFV (1,114), Plug-in Hybrid (464) and Diesel (405). The remaining 56 rows are smaller groups: 43 FCV, 9 CNG, 2 eFCV and 2 Bifuel (CNG). The table now reads like a report instead of a puzzle. Choose the label carefully, though. "Conventional" is an interpretation: it assumes a blank means an ordinary combustion vehicle. That's true here according to the data documentation, but it's worth writing that assumption down next to the result.

Kind 3: placeholder numbers

This is the most dangerous kind, because nothing looks wrong. The co2 column holds tailpipe CO2 in grams per mile. The documentation says -1 means "not available," and it's common in older model years:

SELECT year, COUNT(*) AS placeholder_rows
FROM vehicles
WHERE co2 = -1
GROUP BY year
ORDER BY year;

Output (real run against the practice database):

yearplaceholder_rows
20101097
20111112
20121126
3 rows

For 2010 through 2012, almost every record uses the placeholder. Now see what happens if you average the column without thinking about it:

SELECT ROUND(AVG(co2), 1)              AS naive_average,
       ROUND(AVG(NULLIF(co2, -1)), 1)  AS cleaned_average,
       SUM(co2 = -1)                   AS placeholder_rows,
       COUNT(*)                        AS total_rows
FROM vehicles
WHERE year = 2011;

Output (real run against the practice database):

naive_averagecleaned_averageplaceholder_rowstotal_rows
1.9233.811121126
1 row

The naive average says a 2011 vehicle emits about 2 grams of CO2 per mile. That's obviously wrong. It comes from averaging over a thousand -1 values with a handful of real ones. The cleaned average, which turns -1 into NULL first, uses only the rows that actually have a measurement. Notice that SUM(co2 = -1) works as a quick counter, because in SQLite a true comparison equals 1 and a false one equals 0.

Even the cleaned average needs a warning label here. It's based on only a few vehicles out of more than a thousand, so it may not represent the 2011 model year at all. Cleaning the placeholder made the number honest about what it measures. It didn't make it representative.

Zero can be a placeholder too

The range_miles column holds the EPA range figure. For electric vehicles it's the distance on a full charge. For vehicles where it doesn't apply, it's simply 0:

SELECT COALESCE(NULLIF(atv_type, ''), 'Conventional') AS tech,
       ROUND(AVG(range_miles), 1) AS avg_range,
       COUNT(*) AS n
FROM vehicles
WHERE year = 2024
GROUP BY tech
ORDER BY avg_range DESC;

Output (real run against the practice database):

techavg_rangen
Plug-in Hybrid444.823
FCV373.34
EV286.8266
Hybrid0205
FFV07
Diesel020
Conventional0752
7 rows

Two lessons are in that output. First, averaging range across all vehicles would mix "not applicable" zeros with real ranges and produce a meaningless number. Filter to the vehicle types where the column applies, or turn the zeros into NULLs with NULLIF(range_miles, 0) first.

Second, look at plug-in hybrids. Their average is higher than the electric vehicles'. No 2024 plug-in hybrid drives several hundred miles on battery alone, so for these rows the column is almost certainly holding a different kind of range figure than it holds for EVs. The column name is the same, but the meaning changes by row. This is the kind of thing that only turns up when you group by category and ask whether each number makes sense. When it happens, read the documentation, and if it doesn't settle the question, leave those rows out and say so.

A compact way to remember the four kinds of "unknown" in this table:

Stored value Meaning in this dataset SQL condition
NULL Unknown or not applicable, such as cylinders on an EV col IS NULL
'' (empty string) A blank from a CSV import; in atv_type, a conventional vehicle col = ''
-1 "Not available," as documented for co2 col = -1
0 In range_miles, the column doesn't apply (conventional, hybrid, diesel, FFV) col = 0

0 and negative numbers aren't automatically invalid. It depends on the column and its documentation. A 0 in range_miles is a placeholder; a 0 somewhere else might be a real measurement.

A checklist for any new column

Before you aggregate a column you haven't used before, run three checks:

  1. COUNT(*) - COUNT(col) tells you how many real NULLs there are.
  2. In SQLite, SUM(col = '') tells you how many empty strings a text column has. The portable form is SUM(CASE WHEN col = '' THEN 1 ELSE 0 END).
  3. SELECT col, COUNT(*) ... GROUP BY col ORDER BY COUNT(*) DESC shows the most common values. Placeholders like -1, 0, N/A and 9999 usually show up near the top of that list, because one placeholder value repeats across many rows.

Then read the documentation, if there is any. FuelEconomy.gov documents the -1 convention. Many internal company tables don't, and the only way to find their placeholders is the frequency check above.

Practice it

Try -1 means "not available", Average CO2 the right way, Blank is not NULL, Give blanks a real label and Who has no cylinders? in the practice section. Each one is built around one of the traps in this guide.

Check your understanding

Six questions on NULLs, blanks and placeholder values, mostly using the vehicles table. Pick an answer to get instant feedback.

0 of 6 answered

  • Correct 0
  • Incorrect 0
  • Accuracy —
1. What does SELECT COUNT(*) FROM vehicles WHERE atv_type IS NULL return?
2. For a row whose atv_type is the empty string '', what does NULLIF(atv_type, '') return?
3. An EV row has atv_type = 'EV'. What does COALESCE(NULLIF(atv_type, ''), 'Conventional') return for that row?
4. To average 2011 co2 without treating "not available" as a real measurement, which expression is honest?
5. In the 2024 range_miles column, a conventional vehicle (blank atv_type) has a stored value of 0. What does that 0 mean here?
6. A report says "the average 2011 vehicle emitted 233.8 grams of CO2 per mile." What's the problem?

Clean before you report

A manager wants a 2011 CO2 report from the vehicles table. Write one query that returns five numbers for model year 2011: the total number of records, how many have an available CO2 measurement, how many have an unavailable (-1) measurement, the average CO2 excluding placeholders, and the percent of records with an available measurement. Round the average to one decimal place and the coverage percentage to two decimal places.

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

Open in the playground