Full answer
sql
CREATE TABLE leads (id INTEGER PRIMARY KEY, city TEXT);
INSERT INTO leads VALUES (1, 'Pune'), (2, ''), (3, NULL), (4, ' '), (5, 'Leeds');The query as written:
sql
SELECT COUNT(*) AS total, COUNT(city) AS with_city FROM leads;| total | with_city |
|---|---|
| 5 | 4 |
The report claims 4 of 5 leads have a city. Two of those are an empty string and a string of spaces, which forms often submit when a field is left blank.
A corrected version:
sql
SELECT COUNT(*) AS total, COUNT(NULLIF(trim(city), '')) AS with_city FROM leads;| total | with_city |
|---|---|
| 5 | 2 |
Trimming and then turning '' into NULL leaves 2 real cities. For the data itself, convert blanks once with UPDATE leads SET city = NULL WHERE trim(city) = '' and add CHECK (city IS NULL OR trim(city) <> ''). Oracle treats '' as NULL, which is one more reason not to rely on blanks meaning anything.
sql
CREATE TABLE leads (id INTEGER PRIMARY KEY, city TEXT);
INSERT INTO leads VALUES (1, 'Pune'), (2, ''), (3, NULL), (4, ' '), (5, 'Leeds');
SELECT COUNT(*) AS total, COUNT(city) AS with_city FROM leads;
SELECT COUNT(*) AS total, COUNT(NULLIF(trim(city), '')) AS with_city FROM leads;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- Empty strings are not NULL
- NULLIF(trim(x), '') normalises blanks
- Prefer storing NULL for unknown
- A CHECK can reject blank strings
Common mistakes
- Checking only for NULL
- Forgetting whitespace-only values
Follow-ups
- How would you clean the existing data safely?
- How do engines differ on empty strings?
Tips
- Show the normalising expression