Window COUNT NULL Semantics
Window aggregates keep NULL semantics: COUNT(*) over a partition counts every row while COUNT(col) skips NULLs frame by frame.
Code
-- 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-levelWHEREwill 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
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
- What relations does the SQL touch?
- `readings`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.