Lessons › SQL › Chapter 6: Window Functions
SQL lesson
LAG() and LEAD()
LAG copies a value from the row above. LEAD copies it from the row below. Every row stays, so you can put each day next to the day before. Like a running total, they need OVER (ORDER BY date), so SQL knows which row is 'above'. The first row has nothing above it, so LAG leaves it empty.
Try this lesson free →Example
Look at the row above or below
SELECT order_date,
revenue,
LAG(revenue) OVER (ORDER BY order_date) AS prev_revenue
FROM orders| order_date | revenue | prev_revenue |
|---|---|---|
| 2024-03-01 | 120.5 | |
| 2024-03-02 | 85.0 | 120.5 |
| 2024-03-03 | 200.75 | 85.0 |
| 2024-03-04 | 55.25 | 200.75 |
| 2024-03-05 | 310.0 | 55.25 |
Step by step
- LAG copies from the row above. ORDER BY the date makes the row above the day before.
SELECT order_date, revenue, LAG(revenue) OVER (ORDER BY order_date) AS prev_revenue FROM orders - LEAD copies from the row below: the next day.
SELECT order_date, revenue, LEAD(revenue) OVER (ORDER BY order_date) AS next_revenue FROM orders
Practice
1. Using orders, show order_date, revenue and the day before's revenue. Name it prev_revenue.
SELECT order_date, revenue, LAG(revenue) OVER (ORDER BY order_date) AS prev_revenue FROM orders2. Using store_sales, show sale_date, revenue and the revenue from the sale before. Name it prev_revenue.
SELECT sale_date, revenue, LAG(revenue) OVER (ORDER BY sale_date) AS prev_revenue FROM store_sales3. Using store_sales, show store_id, sale_date, revenue and the same store's sale before. Name it prev_store_revenue.
SELECT store_id, sale_date, revenue, LAG(revenue) OVER (PARTITION BY store_id ORDER BY sale_date) AS prev_store_revenue FROM store_salesLearn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.
Try this lesson free →