An Empty Input and SQL SUM

In PostgreSQL, SUM returns null when there are no non-null input values. A consumer can convert that result if its own domain treats absence as zero.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace two inputs
  2. Add counts if the difference matters
  3. Distinguish a vanishing total from a missing observation
  4. Constrain where a default is meaningful

Trace two inputs

A sum over rows holding 2 and minus 2 yields zero. A filter finding no rows yields null. These represent different observations. Missing and zero values explain the distinction.

Add counts if the difference matters

Report the matching row count and present-value count alongside sum where appropriate. This shows whether rows existed but every value was missing. See counting rows and values.[1]

Distinguish a vanishing total from a missing observation

Values seven and minus seven sum to zero. A filter matching no rows instead produces null for SUM in PostgreSQL. A source of rows whose values are all null also gives a null sum but still has a nonzero row count. See row counts versus value counts.

WITH readings(value) AS (VALUES (7), (-7))
SELECT SUM(value) AS observed_total, SUM(value) FILTER (WHERE value > 10) AS no_match
FROM readings;
-- Expected: 0, null.

Constrain where a default is meaningful

A ledger report may define an empty day's total as zero. An instrument report may need the absence to stay visible. Test an exact cancellation and empty selection together.

References

  1. PostgreSQL Global Development Group, Aggregate Functions ↩