Full answer
sql
CREATE TABLE people (first TEXT, last TEXT);
INSERT INTO people VALUES ('Asha', 'Rao'), ('Ben', NULL);The query as written:
sql
SELECT first + ' ' + last AS full_name FROM people;| full_name |
|---|
| 0 |
| NULL |
Asha's row shows 0 because each piece is converted to a number, and 'Asha', ' ' and 'Rao' all convert to 0. Ben's row is NULL, because arithmetic with his NULL last name gives NULL. The habit comes from SQL Server, where + concatenates strings.
A corrected version:
sql
SELECT first || ' ' || last AS with_pipes, concat(first, ' ', last) AS with_concat, trim(first || ' ' || COALESCE(last, '')) AS safe FROM people;| with_pipes | with_concat | safe |
|---|---|---|
| Asha Rao | Asha Rao | Asha Rao |
| NULL | Ben | Ben |
|| gives 'Asha Rao' but NULL for Ben, because concatenating NULL yields NULL. concat() skips NULL arguments, giving 'Ben ' with a trailing space, and the COALESCE plus trim version returns a clean 'Ben'. concat_ws(' ', first, last) is another option that skips NULLs and separators together.
sql
CREATE TABLE people (first TEXT, last TEXT);
INSERT INTO people VALUES ('Asha', 'Rao'), ('Ben', NULL);
SELECT first + ' ' + last AS full_name FROM people;
SELECT first || ' ' || last AS with_pipes, concat(first, ' ', last) AS with_concat, trim(first || ' ' || COALESCE(last, '')) AS safe FROM people;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- + is addition in SQLite and PostgreSQL
- Use || or concat() for strings
- || with NULL gives NULL
- concat and concat_ws skip NULLs
Common mistakes
- Carrying SQL Server habits to other engines
- Forgetting NULL parts of names
Follow-ups
- How does concat_ws handle separators?
- What does PostgreSQL do with 'a' + 'b'?
Tips
- Name the operator for each engine