← Back to SQL, page 8

sql-0143 · Easy fresher

A search for first = 'Chen' finds nothing, though the table shows Chen. What is likely wrong, and how do you clean it?

The stored value probably has leading or trailing spaces, such as ' Chen '. Equality compares every character, so it fails. TRIM removes spaces from both ends (LTRIM and RTRIM do one side); clean the data with an UPDATE and validate input so it does not come back.

Full answer
sql
CREATE TABLE contacts (
  id    INTEGER PRIMARY KEY,
  first TEXT,
  last  TEXT,
  email TEXT,
  phone TEXT
);
INSERT INTO contacts VALUES
  (1,'Asha','Rao','asha.rao@example.com','+91 98450-12345'),
  (2,'ben',NULL,'Ben@Mail.example.org','(020) 7946 0018'),
  (3,'  Chen ','Li','chen_li@example.com','020-7946-0019'),
  (4,'Dara','Okafor',NULL,'12345');
sql
SELECT id FROM contacts WHERE first = 'Chen';
id

(0 rows)

Comparing lengths exposes the hidden characters:

sql
SELECT id, '[' || first || ']' AS shown, LENGTH(first) AS len FROM contacts WHERE id = 3;
idshownlen
3[ Chen ]7

TRIM on the comparison finds the row, but it hides the problem and blocks plain index use on first:

sql
SELECT id FROM contacts WHERE TRIM(first) = 'Chen';
id
3

Fix the data once, then guard it, for example with CHECK (first = TRIM(first)):

sql
UPDATE contacts SET first = TRIM(first) WHERE first <> TRIM(first);
SELECT id, '[' || first || ']' AS shown FROM contacts ORDER BY id;
idshown
1[Asha]
2[ben]
3[Chen]
4[Dara]

TRIM removes spaces by default. Tabs, non-breaking spaces and line breaks need an explicit character list, such as TRIM(first, ' ' || char(9)) in SQLite.

sql
CREATE TABLE contacts (
  id    INTEGER PRIMARY KEY,
  first TEXT,
  last  TEXT,
  email TEXT,
  phone TEXT
);
INSERT INTO contacts VALUES
  (1,'Asha','Rao','asha.rao@example.com','+91 98450-12345'),
  (2,'ben',NULL,'Ben@Mail.example.org','(020) 7946 0018'),
  (3,'  Chen ','Li','chen_li@example.com','020-7946-0019'),
  (4,'Dara','Okafor',NULL,'12345');

SELECT id FROM contacts WHERE first = 'Chen';

SELECT id, '[' || first || ']' AS shown, LENGTH(first) AS len FROM contacts WHERE id = 3;

SELECT id FROM contacts WHERE TRIM(first) = 'Chen';

UPDATE contacts SET first = TRIM(first) WHERE first <> TRIM(first);
SELECT id, '[' || first || ']' AS shown FROM contacts ORDER BY id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Hidden spaces break equality
  • LENGTH or quote() reveals them
  • TRIM, LTRIM and RTRIM remove spaces
  • Clean with UPDATE and prevent with a CHECK or input validation

Common mistakes

  • Wrapping every query in TRIM instead of fixing the data
  • Assuming TRIM removes tabs and non-breaking spaces

Follow-ups

  • How would you find all rows with leading or trailing whitespace?
  • How would you collapse repeated inner spaces?

Tips

  • Show the length check as a diagnostic step