← Back to SQL, page 7

sql-0140 · Easy fresher

What does first || ' ' || last return when last is NULL, and how is CONCAT different?

The || operator returns NULL if any operand is NULL, so the whole name disappears. CONCAT, available in PostgreSQL and in SQLite 3.44+, treats NULL as an empty string. Use COALESCE around nullable parts, or CONCAT_WS to join with a separator and skip NULLs.

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,
       first || ' ' || last        AS pipes,
       CONCAT(first, ' ', last)    AS concat_fn,
       CONCAT_WS(' ', first, last) AS concat_ws
FROM contacts WHERE id IN (1, 2) ORDER BY id;
idpipesconcat_fnconcat_ws
1Asha RaoAsha RaoAsha Rao
2NULLbenben

Ben's last is NULL, so || gives NULL for him. CONCAT drops the NULL but keeps the space, leaving a trailing blank. CONCAT_WS adds the separator only between non-NULL values, which is usually what a "full name" column wants.

PostgreSQL gives the same three results:

sql
SELECT id, first || ' ' || last AS pipes, CONCAT(first, ' ', last) AS concat_fn,
       CONCAT_WS(' ', first, last) AS concat_ws
FROM contacts WHERE id IN (1, 2) ORDER BY id;
idpipesconcat_fnconcat_ws
1Asha RaoAsha RaoAsha Rao
2NULLbenben

SQL Server's + on strings also yields NULL with a NULL operand by default; MySQL uses CONCAT because || means OR there unless a mode is set (neither was run here).

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,
       first || ' ' || last        AS pipes,
       CONCAT(first, ' ', last)    AS concat_fn,
       CONCAT_WS(' ', first, last) AS concat_ws
FROM contacts WHERE id IN (1, 2) ORDER BY id;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • || returns NULL when any part is NULL
  • CONCAT treats NULL as an empty string
  • CONCAT_WS skips NULLs and their separators
  • Operator meaning varies by engine

Common mistakes

  • Building display names with || on nullable columns
  • Leaving double or trailing spaces after CONCAT

Follow-ups

  • How would you build 'Last, First' only when both exist?
  • Which engines use + for string concatenation?

Tips

  • Show the three variants on one NULL row