NULLIF Turns Blank Strings Into NULL
NULLIF(a, b) returns NULL when its arguments match, so empty form fields collapse to real NULLs and one COALESCE covers blank and missing alike.
Code
-- NULLIF(a, b):a = b 时返回 NULL,否则返回 a。典型用途:把空串归一成 NULL
WITH feedback(id, note) AS (
VALUES
(1, 'great'),
(2, ''), -- 表单没填
(3, ' '), -- 只有空白
(4, NULL) -- 本来就是 NULL
)
SELECT
id,
note,
NULLIF(note, '') AS blank_to_null, -- '' 变 NULL,' ' 原样
NULLIF(btrim(note), '') AS trimmed_blank_to_null, -- 空白串也归一
COALESCE(NULLIF(btrim(note), ''), '(no note)') AS display
FROM feedback
ORDER BY id;
-- NULLIF 是 COALESCE 的对偶:放在 COALESCE 之前,让"空串"与"缺失"
-- 走同一条兜底路径,下游只需判断一个 NULL 口径The code one step at a time
What runs is SELECT, with feedback as the object involved.
The pieces that do the work: a CTE (WITH … AS) that names an intermediate result before the main query; an ORDER BY that fixes the output order.
Using it
The feedback table is the working surface here.
Interactive Tools for This Topic
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.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.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
- What objects does the SQL involve?
- `feedback` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.