And Or Evaluation Order Is Not Guaranteed
SQL does not guarantee left-to-right evaluation of AND terms, so a guard like y <> 0 AND y/x > 1 can still divide by zero; CASE does evaluate in order.
Code
-- SQL 不保证 AND/OR 两侧表达式从左到右求值:PG 可以为走索引而重排条件
-- 经典翻车:y <> 0 AND y / x > 1 想用第一个条件保护除法,但除法可能先被求值
-- SELECT * FROM t WHERE y <> 0 AND y / x > 1; -- 仍可能抛 division by zero
-- OR 同理:两个操作数之间也没有先来后到
-- 守卫必须用 CASE:CASE 的 WHEN 分支严格按顺序求值,不用的子表达式不求值
-- 任何顺序敏感的逻辑都要显式写进 CASE 的 WHEN 里
CREATE TEMP TABLE metrics (id int, calls int, errors int);
INSERT INTO metrics VALUES (1, 100, 5), (2, 0, 0);
SELECT id,
CASE WHEN calls = 0 THEN 0.0
ELSE errors::numeric / calls END AS error_rate
FROM metrics
ORDER BY id;How the snippet works
SELECT / INSERT / CREATE statements share the script, touching metrics.
metrics is spun up by this very file as a session-local temp table — no setup has to come before it, and the end of the session takes it back.
What the statements actually assemble: an ORDER BY that fixes the output order.
Applying it
Nothing outside the file is needed: the session-local tables it touches (metrics) are created by the file itself — point it at a scratch database and run the whole thing.
Statements that matter
SELECT id,
CASE WHEN calls = 0 THEN 0.0
ELSE errors::numeric / calls END AS error_rate
FROM metrics
ORDER BY id;
CREATE TEMP TABLE metrics (id int, calls int, errors int);
INSERT INTO metrics VALUES (1, 100, 5), (2, 0, 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.Case ConverterConvert text between lowercase, uppercase, title, sentence, camelCase, snake_case, and kebab-case while preserving Unicode letters and numbers.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.
FAQ
- What relations does the SQL touch?
- The references are `metrics`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.