Learn SQL/Advanced/Interview Patterns/SQL Compare Consecutive Rows

SQL Compare Consecutive Rows

SQL Compare Consecutive Rows helps analysts compare neighboring ordered rows with LAG.

What & Why

Interviewers often phrase this as "find rows where the value changed from the previous row" — that's just LAG plus a comparison, already covered in the Window Functions series, worth recognizing under this framing too.

See How It Works

BUSINESS QUESTION

Growth wants the change in daily active users between consecutive observations.

date_daydaunew_usersreturning_users
2024-04-0112401801060
2024-04-0213152051110
2024-04-0312881641124
2024-04-0413922211171
EXAMPLE QUERY
SELECT
  date_day,
  dau,
  LAG(dau) OVER (ORDER BY date_day) AS prior_dau,
  dau - LAG(dau) OVER (ORDER BY date_day) AS absolute_change
FROM growth.daily_active_users
ORDER BY date_day;
RESULT — consecutive DAU comparison
date_daydauprior_dauabsolute_change
2024-04-011240NULLNULL
2024-04-021315124075
2024-04-0312881315-27
2024-04-0413921288104

LAG aligns every day with the previous representative row.

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario