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.

SqlData Fetching

Code

snippet
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

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.