Español Practice SQL

SQL LAG and LEAD: compare with the previous row

LAG looks one row back, LEAD one row ahead, in the order you set inside OVER.

SQL skills · Window functions

Practice this nowLearn it step by step

Free. No sign up. Your progress stays in this browser.

What you will learn

Comparing with the previous row used to need a self join. LAG does it in one line.

Subtract the previous value to get the change.

The basics

LAG takes a value from the row before, LEAD from the row after, in the order you give inside OVER.

SELECT due_date, amount,
  LAG(amount) OVER (ORDER BY due_date) AS previous_amount,
  amount - LAG(amount) OVER (ORDER BY due_date) AS change
FROM invoices

The first row has no row before it, so LAG gives NULL there. Month over month changes and days until the next event start with LAG and LEAD.

Worked examples

Example 1

Change in signups from one campaign to the next.

SELECT start_date, signups,
  signups - LAG(signups) OVER (ORDER BY start_date) AS change
FROM campaigns

The first row has nothing before it and gets NULL.

Reading helps, typing makes it stick. Every task gives you a fresh table, and your query is checked by a real database.

Try a task

Common mistakes

  • Forgetting ORDER BY inside OVER.
  • Expecting a value in the first row of LAG.
  • Mixing up LAG and LEAD.

Where you will use it at work

  • Finance: month over month revenue change.
  • Product: days between a user’s sessions.
  • Support: time until the next ticket.

Questions people ask

Can LAG look two rows back?

Yes: LAG(x, 2).

Can I set a default instead of NULL?

Yes: LAG(x, 1, 0) gives 0 for the first row.

Can I use it per group?

Yes, with PARTITION BY inside OVER.

Ready to write it yourself?

Practice LAG and LEAD

Related guides