Empty Set Aggregates Return Null Not Zero
SUM, AVG, and MIN over an empty set return NULL rather than zero while COUNT returns 0, so wrap sums in COALESCE when downstream expects a number.
Code
-- 空集 (empty set) 上的聚合返回 NULL 而不是 0:SUM/AVG/MIN/MAX 一致,COUNT 是唯一返回 0 的
-- "没有数据"与"值为 0"是两种口径,下游把 NULL 当 0 会算错
WITH tickets(id, status, hours) AS (
VALUES
(1, 'open', 3),
(2, 'open', 5),
(3, 'resolved', 8)
),
empty_set AS (
SELECT hours FROM tickets WHERE status = 'done' -- 零行
)
SELECT
SUM(hours) AS sum_hours, -- NULL:空输入
AVG(hours) AS avg_hours, -- NULL
MIN(hours) AS min_hours, -- NULL
COUNT(*) AS ticket_count, -- 0
COALESCE(SUM(hours), 0) AS sum_hours_safe -- 显式兜底成 0
FROM empty_set;How the snippet works
At its core this is a single SELECT statement against tickets and empty_set.
Mechanically, the statements are built from: a CTE (WITH … AS) that names an intermediate result before the main query; a WHERE clause constraining which rows the statement operates on; COUNT, SUM, AVG, MIN aggregation.
Applying it
The tickets table is the working surface here.
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
- Name the tables involved in this file.
- `tickets`, `empty_set`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.