InterviewPrepKit

Home / SQL / Window Functions

Day-over-Day Change with LAG and LEAD

medium
Solving tips
  • LAG pulls the previous row's value into the current row and LEAD pulls the next row's — both need an ORDER BY to define previous and next.
  • The first row has no previous (LAG is NULL) and the last has no next (LEAD is NULL); any arithmetic on them yields NULL unless you supply a default.
  • Multiply by 100.0 (not 100) before dividing so the percentage keeps its decimals instead of doing integer division.

You track daily active users (DAU). The interviewer wants the previous day’s value, the next day’s value, the day-over-day change, and the percent change, all on one row.

Schema

CREATE TABLE daily_active_users (
    day DATE,
    dau INT
);
daydau
2024-03-011000
2024-03-021100
2024-03-031050
2024-03-041300
2024-03-051290

Task

For each day return dau, prev_dau (previous day’s DAU via LAG), next_dau (next day’s DAU via LEAD), delta (dau - prev_dau), and pct_change (delta / prev_dau as a percentage, rounded to 1 decimal). Leave prev_dau, delta, and pct_change NULL on the first day and next_dau NULL on the last day. Order by day ascending.

Expected output

daydauprev_daunext_daudeltapct_change
2024-03-0110001100
2024-03-0211001000105010010.0
2024-03-03105011001300-50-4.5
2024-03-0413001050129025023.8
2024-03-0512901300-10-0.8
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.