Lag Lead Compare Adjacent Rows
Compare adjacent rows using LAG and LEAD window functions to detect anomalies between consecutive measurements.
Code
SELECT
timestamp,
reading,
LAG(reading, 1) OVER (ORDER BY timestamp) AS prev_reading,
LEAD(reading, 1) OVER (ORDER BY timestamp) AS next_reading,
reading - LAG(reading, 1) OVER (ORDER BY timestamp) AS delta_prev,
reading - LEAD(reading, 1) OVER (ORDER BY timestamp) AS delta_next
FROM sensor_readings
ORDER BY timestamp;How the snippet works
At its core this is a single SELECT statement against sensor_readings.
What the statements actually assemble: a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order.
Caveats
- 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
Run the statement against the sensor_readings table.
Statements that matter
SELECT
timestamp,
reading,
LAG(reading, 1) OVER (ORDER BY timestamp) AS prev_reading,
LEAD(reading, 1) OVER (ORDER BY timestamp) AS next_reading,
reading - LAG(reading, 1) OVER (ORDER BY timestamp) AS delta_prev,
reading - LEAD(reading, 1) OVER (ORDER BY timestamp) AS delta_next
FROM sensor_readings
ORDER BY timestamp;
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
- Which tables does the SQL touch?
- `sensor_readings` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.