×

sql · level 3 · unit 3 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

looks at the row before. looks at the row after.

To spot change, compare each row with its neighbour. LAG(amount) OVER (ORDER BY day) fetches the amount from the row before, and LEAD(amount) fetches it from the row after. So amount - LAG(amount) OVER (...) is the change since last time.

The first row has nothing before it, so LAG gives NULL. A third argument sets a default: LAG(amount, 1, 0) means one row back, or 0 if there is none.

Careful: the row before is not always the day before. The café has no row for 4 June.

SELECT day, amount,
  LAG(amount) OVER (ORDER BY day) AS previous,
  amount - LAG(amount) OVER (ORDER BY day) AS change
FROM takings
ORDER BY day;

With 4 June missing, 5 June is compared with 3 June.