Lag Lead Compare Adjacent Rows

Compare adjacent rows using LAG and LEAD window functions to detect anomalies between consecutive measurements.

SqlData Integrity

Code

sqlsnippet
9 lines
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-level WHERE will 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

FAQ

Which tables does the SQL touch?
`sensor_readings` — referenced directly, no join needed.