Counting Rows and Counting Present Values

Counting rows and counting values of a particular expression can give different totals because null values are excluded by a value count.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Compute a small example
  2. Choose a denominator intentionally
  3. Compute coverage and submitted average together
  4. Test an all-null group and an empty source

Compute a small example

For ratings 0, null, and 7, COUNT(*) counts three observations. COUNT(rating) counts two present ratings. Zero is a present value under SQL null rules.

Choose a denominator intentionally

A mean of submitted ratings should use the count of present ratings. The count of all rows can separately show submission coverage. Combining group rates illustrates why both measures matter.[1]

Compute coverage and submitted average together

Of readings zero, null and nine, all three rows were recorded but only two have numeric values. Counting the expression yields two and the arithmetic mean of present readings is 4.5. See null and zero.

WITH readings(value) AS (VALUES (0), (NULL), (9))
SELECT COUNT(*), COUNT(value), AVG(value) FROM readings;
-- Expected: 3 rows, 2 present values, average 4.5.

Test an all-null group and an empty source

One has recorded rows while the other has none. Averaging present values produces a null result in both cases under ordinary SQL behavior. Carry a separate count if the distinction matters.

References

  1. PostgreSQL Global Development Group, Aggregate Functions ↩