Learn SQL/Advanced/Window Functions/SQL Previous Row Comparison

SQL Previous Row Comparison

LAG, applied to its most common real use: did this row go up or down from the last one?

What & Why

The Previous Row Comparison pattern is used to use LAG to compare the current row with its predecessor. This keeps the SQL aligned with one concrete business question and makes the result grain explicit before the query is reused.

See How It Works

BUSINESS QUESTION

Growth wants daily active users compared with the prior observed day.

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 previous_dau,
  dau - LAG(dau) OVER (ORDER BY date_day) AS dau_change
FROM growth.daily_active_users
ORDER BY date_day;
RESULT — compare with previous DAU
date_daydauprevious_daudau_change
2024-04-011240NULLNULL
2024-04-021315124075
2024-04-0312881315-27
2024-04-0413921288104

LAG supplies the immediately preceding day's DAU.

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario