Full answer
A trailing space is a real character, but some types and engines choose to ignore it when comparing.
SQLite compares strings exactly:
SELECT 'abc' = 'abc ' AS equal_with_space,
'abc' = TRIM('abc ') AS equal_after_trim,
LENGTH('abc ') AS len;| equal_with_space | equal_after_trim | len |
|---|---|---|
| 0 | 1 | 4 |
PostgreSQL does too for text and varchar, but its fixed-width char(n) type pads values with spaces and treats trailing spaces as insignificant:
SELECT 'abc'::text = 'abc '::text AS text_equal,
'abc'::char(5) = 'abc '::char(5) AS char_equal,
length('abc '::text) AS text_len;| text_equal | char_equal | text_len |
|---|---|---|
| false | true | 4 |
MySQL and SQL Server use "pad space" comparison rules for most collations, so 'abc' = 'abc ' is true there. That comes from their documentation and was not run here.
Where this bites in practice: data imported from a spreadsheet carries trailing spaces, a lookup by name works in one database and fails in another, or a unique constraint allows 'Pune' and 'Pune ' as two different cities. The usual fix is to clean the data on the way in with TRIM, and to add a CHECK constraint such as CHECK (city = TRIM(city)) so dirty values cannot come back.
SELECT 'abc' = 'abc ' AS equal_with_space,
'abc' = TRIM('abc ') AS equal_after_trim,
LENGTH('abc ') AS len;Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
- SQLite and PostgreSQL text: trailing spaces matter
- PostgreSQL char(n): trailing spaces are ignored
- MySQL and SQL Server usually ignore trailing spaces in =
- Clean with TRIM on input and guard with a CHECK constraint
Common mistakes
- Assuming string equality rules are the same on every engine
- Using char(n) for variable-length text
Follow-ups
- How would you find rows whose value has leading or trailing spaces?
- Why is char(n) rarely a good choice?
Tips
- Mention a real symptom, such as duplicate-looking city names