← Back to SQL, page 2

sql-0027 · Medium mid

Does 'abc' equal 'abc ' (with a trailing space) in SQL?

It depends on the type and engine. In SQLite and in PostgreSQL text or varchar, trailing spaces are significant, so 'abc' = 'abc ' is false. PostgreSQL's char(n) type pads and ignores trailing spaces, so the comparison is true there. MySQL and SQL Server ignore trailing spaces in = comparisons for most collations.

Full answer

A trailing space is a real character, but some types and engines choose to ignore it when comparing.

SQLite compares strings exactly:

sql
SELECT 'abc' = 'abc ' AS equal_with_space,
       'abc' = TRIM('abc ') AS equal_after_trim,
       LENGTH('abc ') AS len;
equal_with_spaceequal_after_trimlen
014

PostgreSQL does too for text and varchar, but its fixed-width char(n) type pads values with spaces and treats trailing spaces as insignificant:

sql
SELECT 'abc'::text = 'abc '::text           AS text_equal,
       'abc'::char(5) = 'abc '::char(5)     AS char_equal,
       length('abc '::text)                 AS text_len;
text_equalchar_equaltext_len
falsetrue4

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.

sql
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