COALESCE NULL Safe Defaults

Guard nullable columns with COALESCE and NULLIF so blanks render as explicit defaults and divide-by-zero collapses to NULL instead of failing.

SqlData Integrity

Code

snippet
SELECT
    account_id,
    -- NULL 串联成显式占位,而不是静默消失
    COALESCE(nickname, '(unset)') AS display_name,
    -- NULLIF:把 0 变 NULL,从而除零整体塌缩为 NULL
    ROUND(
        refunds::numeric / NULLIF(charges, 0),
        4
    ) AS refund_rate,
    -- 再用 COALESCE 给塌缩值兜底
    COALESCE(
        ROUND(refunds::numeric / NULLIF(charges, 0), 4),
        0
    ) AS refund_rate_safe
FROM accounts
-- WHERE 里注意:NULL 参与比较结果仍是 NULL,必须用 IS NULL
WHERE nickname IS NULL OR charges IS NULL OR charges = 0;

What the code does

At its core this is a single SELECT statement against accounts.

In terms of clauses, the statements use: a WHERE clause narrowing which rows one statement affects.

Applying it

The accounts table is the working surface here.

Statements that matter

SELECT
account_id,
COALESCE(nickname, '(unset)') AS display_name,
ROUND(
refunds::numeric / NULLIF(charges, 0),
4
) AS refund_rate,
COALESCE(
ROUND(refunds::numeric / NULLIF(charges, 0), 4),
0
) AS refund_rate_safe
FROM accounts
WHERE nickname IS NULL OR charges IS NULL OR charges = 0;

Interactive Tools for This Topic

FAQ

Which tables does this file reference?
`accounts`.