TheAnalyst / SQLAll lessons ↗
Day 20 · Advanced SQL · 10–20 minutes

LAG and LEAD

LAG and LEAD compare a row with a previous or following row in an ordered window.

01 · Learn

The idea

LAG and LEAD compare a row with a previous or following row in an ordered window. Read the query line by line and identify the input table, the transformation, and the shape of the result before running it.

SELECT order_id, order_date, amount, LAG(amount) OVER (ORDER BY order_date) AS previous_amount FROM orders ORDER BY order_date;
Read it actively

Before running the example, predict the output columns and whether the query returns one row, many rows, or possibly no rows.

02 · Recall

Explain it without looking

In your own words, explain the main SQL feature in today’s lesson and why it answers the question.

03 · Solve

Run your own query

Show each order's amount and the previous order's amount by date.

Loading browser SQL engine…
04 · Repeat

Close the loop