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.
Code
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
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
- Name the tables involved in this file.
- `people` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.