SQL · Level 3 Window functions

SQL LAG() and Day-over-Day Change

Show how revenue changed from one day to the next with LAG(), and handle the first day, which has no previous value.

  • LAG(x) OVER (ORDER BY ...)
  • The first row gets NULL
  • COALESCE() for a default

LAG(x) OVER (ORDER BY day) reads the previous row's value, so each day can be compared with the one before. Trap: the first row has no previous one, so LAG returns NULL, and any maths with NULL is NULL. COALESCE gives a default.

SELECT day, visitors,
       visitors - LAG(visitors) OVER (ORDER BY day) AS change
FROM traffic;   -- the first day's change is NULL

Return each day, its revenue and the change from the previous day, with 0 for the first day, ordered by day. In the database below, revenue went up by 30 on March 2.

Sample data from the first test. The other tests use different rows, so write a query, not a list of answers.

daily 3 rows
dayTEXTrevenueINTEGER
2024-03-01100
2024-03-02130
2024-03-0390
solution.sql
Test Suites Pending
Output