Advanced · Lesson 4 of 18

LAG and LEAD

LAG and LEAD access values from other rows.

LAG(column) - previous row's value LEAD(column) - next row's value

Compare to previous:

SELECT first_name, salary,
       LAG(salary) OVER (ORDER BY salary DESC) as prev_salary
FROM employees;

Perfect for:

  • Year-over-year comparisons
  • Day-over-day changes
  • Finding gaps in data
Check your understanding

Show each employee's salary and the next lower salary.

Examples run on the employees sample database. Open any of them in the playground to experiment.

Practice it on a real question

All Window functions questions

Practice on your iPhone

Query Dojo for iPhone has 85 interview questions, timed mock interviews and a tile builder, so you can write queries without a keyboard.

Get the app