Write SQL to detect when a value changed compared with the previous event for the same entity.
Answer
Use LAG to expose the previous value inside a partition ordered by event time and a stable tie-breaker, then compare the current value with that previous value in an outer query. Handle the first row and NULL as explicit business cases because a missing previous row and a genuine NULL can otherwise look identical.
Strong answer includes
- uses LAG with the correct partition and order
- filters the computed previous value outside the window expression
- handles first-row and NULL semantics deliberately
Practical example
Dialect · Portable SQLRuntime · SQLite sample DB
Runs against the resettable SQLite sample database used by the playground.
SQL
Result
Run the query to see the result.
LAG exposes the previous status, while ROW_NUMBER distinguishes the first event from a real previous NULL. The explicit NULL branches make NULL-to-value and value-to-NULL transitions visible without relying on a DBMS-specific null-safe comparison operator.
Expected result: Only rows where the tracked value changed from the immediately preceding row.