SQL Next Row Comparison
LEAD, applied the same way — compared to what's coming next instead of what came before.
What & Why
The mirror of the previous lesson: LEAD plus a comparison, when the question is about what happens next rather than what happened last.
See How It Works
BUSINESS QUESTION
Growth wants each daily active-user value compared with the next observed day.
| date_day | dau | new_users | returning_users |
|---|---|---|---|
| 2024-04-01 | 1240 | 180 | 1060 |
| 2024-04-02 | 1315 | 205 | 1110 |
| 2024-04-03 | 1288 | 164 | 1124 |
| 2024-04-04 | 1392 | 221 | 1171 |
EXAMPLE QUERY
SELECT
date_day,
dau,
LEAD(dau) OVER (ORDER BY date_day) AS next_dau,
LEAD(dau) OVER (ORDER BY date_day) - dau AS next_day_change
FROM growth.daily_active_users
ORDER BY date_day;RESULT — compare with next DAU
| date_day | dau | next_dau | next_day_change |
|---|---|---|---|
| 2024-04-01 | 1240 | 1315 | 75 |
| 2024-04-02 | 1315 | 1288 | -27 |
| 2024-04-03 | 1288 | 1392 | 104 |
| 2024-04-04 | 1392 | NULL | NULL |
LEAD supplies the immediately following day's DAU.
This lesson's practice is part of Pro.
Sign up free to try it on a real business scenario