Rolling Z-Score With STDDEV Window
Compare each reading against a trailing frame mean and stddev_samp that exclude the current row, flagging |z| beyond 3 with NULL-safe division.
Code
-- rolling Z-score: judge whether the current value is anomalous using the "before" window statistics
-- the frame takes the 6 preceding rows and excludes the current one: the baseline is not polluted by the sample under test
CREATE TEMP TABLE sensor_reads (
device text NOT NULL,
taken_at timestamptz NOT NULL,
value numeric NOT NULL
);
INSERT INTO sensor_reads (device, taken_at, value) VALUES
('s1', '2026-11-13 09:00', 20), ('s1', '2026-11-13 09:05', 21),
('s1', '2026-11-13 09:10', 19), ('s1', '2026-11-13 09:15', 22),
('s1', '2026-11-13 09:20', 20), ('s1', '2026-11-13 09:25', 21),
('s1', '2026-11-13 09:30', 95), -- spike
('s1', '2026-11-13 09:35', 20);
SELECT
taken_at,
value,
ROUND(avg(value) OVER w, 2) AS rolling_mean,
ROUND(stddev_samp(value) OVER w, 2) AS rolling_sd,
-- z = (current value - frame mean) / frame stddev; stddev is NULL while the sample is insufficient
ROUND((value - avg(value) OVER w)
/ NULLIF(stddev_samp(value) OVER w, 0), 2) AS z,
abs((value - avg(value) OVER w)
/ NULLIF(stddev_samp(value) OVER w, 0)) > 3 AS outlier
FROM sensor_reads
WINDOW w AS (
ORDER BY taken_at
ROWS BETWEEN 6 PRECEDING AND 1 PRECEDING
)
ORDER BY taken_at;Inside the snippet
The file runs SELECT / INSERT / CREATE statements, touching sensor_reads.
sensor_reads is created in this same file as session-local temp tables — nothing needs to exist beforehand, and it goes away at session end.
Breaking the statements into their working parts: AVG aggregation; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns.
Putting it to use
Nothing outside the file is needed: the session-local tables it touches (sensor_reads) are created by the file itself — point it at a scratch database and run the whole thing.
Core lines
CREATE TEMP TABLE sensor_reads (
device text NOT NULL,
taken_at timestamptz NOT NULL,
value numeric NOT NULL
);
Interactive Tools for This Topic
FAQ
- What are the relations in play here?
- `sensor_reads`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.