← Back to SQL, page 16

sql-0311 · Easy fresher

What does SELECT 'A' || NULL || 'B' return, and what does CONCAT('A', NULL, 'B') return?

The || version returns NULL, because any NULL operand makes the whole concatenation NULL. CONCAT treats NULL as an empty string and returns 'AB'. SQLite 3.44+ and PostgreSQL both support CONCAT.

Full answer
sql
SELECT 'A' || NULL || 'B' AS pipes, CONCAT('A', NULL, 'B') AS concat_fn;
pipesconcat_fn
NULLAB

This is the string version of NULL propagation: NULL + 1 is NULL, and so is a concatenation with NULL.

Oracle is the well-known exception, because it treats the empty string as NULL and lets || skip NULLs (not run here). For portable code, wrap nullable parts in COALESCE or use CONCAT where it exists.

sql
SELECT 'A' || NULL || 'B' AS pipes, CONCAT('A', NULL, 'B') AS concat_fn;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • || with a NULL operand returns NULL
  • CONCAT skips NULLs
  • Oracle treats '' as NULL, unlike most engines
  • COALESCE nullable parts for portability

Common mistakes

  • Building labels with || on nullable columns
  • Assuming Oracle behaviour elsewhere

Follow-ups

  • What does CONCAT_WS do?
  • How does NULL propagate in arithmetic?

Tips

  • State both results