BBampaa

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 →
About 5–10 minutes · no sign-up needed

Example

Look at the row above or below

SELECT order_date,
       revenue,
       LAG(revenue) OVER (ORDER BY order_date) AS prev_revenue
FROM orders

Result:

order_daterevenueprev_revenue
2024-03-01120.5
2024-03-0285.0120.5
2024-03-03200.7585.0
2024-03-0455.25200.75
2024-03-05310.055.25

Step by step

  1. 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
  2. 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

Try each one in your head first, then open the answer.

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 orders
2. 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_sales
3. 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_sales

Learn 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 →
About 5–10 minutes · no sign-up needed