concat_ws Skips NULLs When Concatenating
concat_ws skips NULL arguments and places separators only between non-empty values, while || collapses the entire expression to NULL.
Code
WITH people AS (
SELECT * FROM (VALUES
(1, 'Ada', NULL, 'Lovelace'),
(2, 'Grace', 'B', 'Hopper'),
(3, NULL, NULL, 'Turing')
) AS t(id, first_name, middle_name, last_name)
)
SELECT
id,
-- concat_ws skips NULL arguments: separators appear only between non-empty values
concat_ws(' - ', first_name, middle_name, last_name) AS full_name,
-- || collapses the whole expression to NULL on any NULL operand
first_name || ' - ' || middle_name || ' - ' || last_name AS naive_concat
FROM people
ORDER BY id;What the demo joins
Three people with different null patterns run through both concatenations. concat_ws with the dash separator skips the NULL middle names entirely: Ada prints Ada - Lovelace, Grace keeps all three parts, and the all-but-last-name row prints just Turing.
The || chain is the contrast: any single NULL poisons the whole expression, so the naive_concat columns for Ada and Turing come back NULL. No coalesce ladder is needed; concat_ws alone handles the skip-and-separate behavior.
Points worth noting
- concat_ws treats NULL args as absent, but empty strings still get joined.
- The separator never leads or trails; it only sits between surviving values.
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Why does the || version return NULL?
- SQL concatenation propagates NULL: one NULL operand makes the entire || chain NULL, while concat_ws filters NULL arguments before joining.
Report a problem with this exampleOpens a pre-filled issue on GitHub.