Full answer
NULL spreads through expressions. If one input is unknown, the result is unknown:
CREATE TABLE people (first TEXT, middle TEXT, last TEXT);
INSERT INTO people VALUES ('Ana', NULL, 'Lopez'), ('Ravi', 'K', 'Iyer'), ('Mei', NULL, 'Lin');SELECT NULL + 1 AS plus, NULL * 0 AS times_zero, 'tea' || NULL AS joined;| plus | times_zero | joined |
|---|---|---|
| NULL | NULL | NULL |
That catches people building display names. A middle name column is often empty:
SELECT first || ' ' || middle || ' ' || last AS full_name FROM people ORDER BY first;| full_name |
|---|
| NULL |
| NULL |
| Ravi K Iyer |
Two rows lost their whole name because of one missing piece. Fix it by turning the NULL into something harmless before joining:
SELECT first || COALESCE(' ' || middle, '') || ' ' || last AS full_name FROM people ORDER BY first;| full_name |
|---|
| Ana Lopez |
| Mei Lin |
| Ravi K Iyer |
This also tidies the spacing: the space is only added when a middle name exists. SQLite (3.44 and later), PostgreSQL and MySQL 8 have CONCAT_WS(separator, ...), which skips NULLs and puts the separator only between real values:
SELECT CONCAT_WS(' ', first, middle, last) AS full_name FROM people ORDER BY first;| full_name |
|---|
| Ana Lopez |
| Mei Lin |
| Ravi K Iyer |
PostgreSQL gives the same result for the CONCAT_WS query:
SELECT CONCAT_WS(' ', first, middle, last) AS full_name FROM people ORDER BY first;| full_name |
|---|
| Ana Lopez |
| Mei Lin |
| Ravi K Iyer |
Plain CONCAT() treats NULL as an empty string in SQLite and PostgreSQL, but MySQL's CONCAT() returns NULL if any argument is NULL (from the MySQL documentation, not run here).
CREATE TABLE people (first TEXT, middle TEXT, last TEXT);
INSERT INTO people VALUES ('Ana', NULL, 'Lopez'), ('Ravi', 'K', 'Iyer'), ('Mei', NULL, 'Lin');
SELECT NULL + 1 AS plus, NULL * 0 AS times_zero, 'tea' || NULL AS joined;
SELECT first || ' ' || middle || ' ' || last AS full_name FROM people ORDER BY first;
SELECT first || COALESCE(' ' || middle, '') || ' ' || last AS full_name FROM people ORDER BY first;
SELECT CONCAT_WS(' ', first, middle, last) AS full_name FROM people ORDER BY first;Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
- Operators return NULL if any operand is NULL
- || with a NULL part makes the whole string NULL
- COALESCE replaces NULL with a default
- CONCAT_WS skips NULLs and handles separators
Common mistakes
- Building full names with || on nullable columns
- Assuming CONCAT ignores NULLs on every engine
Follow-ups
- How do aggregate functions treat NULL compared with operators?
- How would you show 'N/A' for a missing phone number?
Tips
- Use the name example; it is the version you will meet in real code