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;| id | pipes | concat_fn | concat_ws |
|---|---|---|---|
| 1 | Asha Rao | Asha Rao | Asha Rao |
| 2 | NULL | ben | ben |
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;| id | pipes | concat_fn | concat_ws |
|---|---|---|---|
| 1 | Asha Rao | Asha Rao | Asha Rao |
| 2 | NULL | ben | ben |
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