Learn SQL Lesson
Looking Back with LAG
`LAG` lets you reach into an earlier row in the same partition.
For example, you can show each salesperson's previous sale amount beside the current one:
~~~sql SELECT salesperson, sale_date, amount, LAG(amount) OVER ( PARTITION BY salesperson ORDER BY sale_date ) AS previous_amount FROM sales_2 ~~~
The first row in each salesperson's partition has no earlier row, so `LAG` returns `NULL` there.
The companion function is `LEAD`, which looks forward instead of backward. For example, `LEAD(amount) OVER (...)` can show the next sale amount beside the current sale.
This is useful for change-over-time questions like month-over-month growth, previous status, or the gap from the last event.
Practice challenge
Show each sale together with the salesperson's previous sale amount. Return salesperson, sale_date, amount, and previous_amount, ordered by salesperson and sale_date.