← Back to SQL, page 23

sql-0446 · Easy fresher

Building a full name with 'first' + ' ' + 'last' returns 0 in SQLite. What went wrong?

In SQLite (and standard SQL), + is numeric addition, so the strings are converted to numbers, which are 0 for non-numeric text. Use the || operator, or concat() in PostgreSQL and SQLite 3.44+, which also treats NULL as an empty string.

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_pipeswith_concatsafe
Asha RaoAsha RaoAsha Rao
NULLBenBen

|| 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