Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
QA interview question
Databases, SQL & BISQL languageMiddleCommonPractical

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

Solution · Compare with the previous row
Dialect · Portable SQLRuntime · SQLite sample DB

Runs against the resettable SQLite sample database used by the playground.

SQL
SQLite · sample DB · browser sandbox
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.

#sql#lag#window-functions#change-detection

Sources

PostgreSQL documentationPostgreSQL Global Development Group · Relational modelling, SQL, joins, constraints, transactions, concurrency, indexes, query plans and recovery