🎓 A1Learner
🔍
0 of 51 lessons completed

SQL Lag and Lead

LAG reads the row before the current row, and LEAD reads the row after it. The two functions let one row compare itself with its neighbours.

The previous price

Pencil is cheapest, so it has no previous price and its row shows NULL. Notebook takes 0.8 as its previous price.

SELECT name, price, LAG(price) OVER (ORDER BY price) AS previous_price
FROM products
ORDER BY price;

Change from last product

The biggest step is 20.0, from Backpack at 39.99 to Headphones at 59.99. The smallest step is 1.24, from Coffee Mug to Mouse Pad.

SELECT name, price, ROUND(price - LAG(price) OVER (ORDER BY price), 2) AS price_change
FROM products
ORDER BY price;

The next price

Headphones are dearest, so they have no next price and that row shows NULL. Pencil takes 4.5 as its next price.

SELECT name, price, LEAD(price) OVER (ORDER BY price) AS next_price
FROM products
ORDER BY price;

Example

SELECT name, price, LAG(price) OVER (ORDER BY price) AS previous_price, LEAD(price) OVER (ORDER BY price) AS next_price
FROM products
ORDER BY price;

Key points

  • LAG: a window function that reads the value from the previous row
  • LEAD: a window function that reads the value from the next row
  • The ORDER BY inside OVER sets which row counts as previous and which as next.
  • The first row has no previous row, so LAG returns NULL there.
  • The last row has no next row, so LEAD returns NULL there.
  • A row minus its LAG value shows the change from the row before.

In this example, the products run from the cheapest to the dearest. LAG brings in the price below each product, and LEAD brings in the price above it. The Pencil has no row below it, so its previous price is NULL, and the Headphones have no row above them, so their next price is NULL.

Try it Yourself

Edit the code, then press Run.

Running is simulated · DB Fiddle

Exercise

What does LAG return for the first row in the order?