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.

SqlData Integrity

Code

snippet
-- 空集 (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

FAQ

Name the tables involved in this file.
`tickets`, `empty_set`.