Concatenation NULL Poisoning And Coalesce

String concatenation with || returns NULL when any operand is NULL, so display strings built from optional columns need COALESCE per operand.

SqlData Integrity

Code

snippet
SELECT
    first_name,
    nickname,
    -- nickname 为 NULL 的行整个表达式塌缩成 NULL:
    -- 'Ada' || NULL || 'Lovelace' 不等于 'AdaLovelace'
    first_name || nickname || 'Lovelace' AS poisoned,
    -- 每个可空操作数单独兜底,拼接才完整
    first_name || COALESCE(' "' || nickname || '" ', '') || 'Lovelace' AS display_name,
    -- 数值拼接前要显式转型,int 到 text 没有隐式转换
    'order #' || order_id::text AS labeled_id
FROM people;

-- concat() 函数行为不同:它把 NULL 当空串处理
SELECT concat('a', NULL, 'b') AS concat_skips_nulls;
-- 而 || 只要有任何一个 NULL 就整体塌缩,哪怕其余操作数都非空
SELECT 'a' || NULL || 'b' AS operator_poisoned;

Inside the snippet

Several statements share this file — SELECT, with people among the objects involved.

Putting it to use

Run it in the people database context.

Core lines

SELECT
first_name,
nickname,
first_name || nickname || 'Lovelace' AS poisoned,
first_name || COALESCE(' "' || nickname || '" ', '') || 'Lovelace' AS display_name,
'order #' || order_id::text AS labeled_id
FROM people;
SELECT concat('a', NULL, 'b') AS concat_skips_nulls;
SELECT 'a' || NULL || 'b' AS operator_poisoned;

Interactive Tools for This Topic

FAQ

Name the tables involved in this file.
`people` — referenced directly, no join needed.