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.
Code
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
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
- Which tables does this file reference?
- `accounts`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.