Window COUNT NULL Semantics

Window aggregates keep NULL semantics: COUNT(*) over a partition counts every row while COUNT(col) skips NULLs frame by frame.

SqlData Integrity

Code

snippet
-- NULL semantics of window aggregates: COUNT(*) counts every row, COUNT(celsius) counts only non-null values
CREATE TABLE readings (
    sensor   text NOT NULL,
    taken_at int NOT NULL,
    celsius  numeric
);

INSERT INTO readings (sensor, taken_at, celsius) VALUES
    ('a', 1, 21.5), ('a', 2, NULL), ('a', 3, 22.0),
    ('b', 1, 19.0), ('b', 2, 20.5), ('b', 3, NULL);

SELECT sensor,
       taken_at,
       celsius,
       COUNT(*)       OVER (PARTITION BY sensor) AS rows_in_partition,
       COUNT(celsius) OVER (PARTITION BY sensor) AS non_null_in_partition,
       COUNT(celsius) OVER (PARTITION BY sensor ORDER BY taken_at
                            ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS non_null_so_far
FROM readings
ORDER BY sensor, taken_at;

What the code does

The file runs SELECT / INSERT / CREATE statements, touching readings.

Clause by clause, expect: COUNT aggregation; a window function (OVER (…)) evaluating per row against the partition with no rows folded away; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns.

What to watch for

  • Window functions evaluate after WHERE/GROUP BY, so filtering on their output in the same-level WHERE will not work — use an outer query or a CTE.

Applying it

The readings table is the working surface here.

Statements that matter

INSERT INTO readings (sensor, taken_at, celsius) VALUES
    ('a', 1, 21.5), ('a', 2, NULL), ('a', 3, 22.0),
    ('b', 1, 19.0), ('b', 2, 20.5), ('b', 3, NULL);
CREATE TABLE readings (
    sensor   text NOT NULL,
    taken_at int NOT NULL,
    celsius  numeric
);

Interactive Tools for This Topic

FAQ

What relations does the SQL touch?
`readings`.