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.

SqlData Integrity

Code

snippet
-- 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

FAQ

What objects does the SQL involve?
`feedback` — referenced directly, no join needed.