Window functions
LAG and LEAD
Read adjacent values in a declared order without a self join.
Lesson 61 of 84
Reading: about 2 min
Lesson + practice: about 15 min
Difficulty: Advanced
On this page4 sections
This lesson uses DDI_SQL_Training dataset v1.0.0 on SQL Server 2019 or later. Read adjacent values in a declared order without a self join.
Run the example
sql
SELECT TOP (5) OrderID, OrderDate,
LAG(OrderDate) OVER (ORDER BY OrderID) AS PreviousDate,
LEAD(OrderDate) OVER (ORDER BY OrderID) AS NextDate
FROM dbo.Orders
ORDER BY OrderID;Read it step by step
- LAG reads the preceding order by OrderID; LEAD reads the following order.
- The first previous value is NULL because no earlier row exists.
- Window values are calculated before TOP limits the displayed five rows.
Check the result
| OrderID | OrderDate | PreviousDate | NextDate |
|---|---|---|---|
| 1 | 2023-01-02 | NULL | 2023-01-03 |
| 2 | 2023-01-03 | 2023-01-02 | 2023-01-04 |
| 3 | 2023-01-04 | 2023-01-03 | 2023-01-05 |
| 4 | 2023-01-05 | 2023-01-04 | 2023-01-06 |
| 5 | 2023-01-06 | 2023-01-05 | 2023-01-07 |
The fifth displayed row can still have a NextDate from the sixth order.
Practice
Show Products 1–5 with the preceding product’s ListPrice in ProductID order.
Check your answer and expected result
Reveal answer
sql
SELECT TOP (5) ProductID, ListPrice,
LAG(ListPrice) OVER (ORDER BY ProductID) AS PreviousPrice
FROM dbo.Products
ORDER BY ProductID;| ProductID | ListPrice | PreviousPrice |
|---|---|---|
| 1 | 39.00 | NULL |
| 2 | 129.00 | 39.00 |
| 3 | 79.00 | 129.00 |
| 4 | 8.50 | 79.00 |
| 5 | 12.00 | 8.50 |
Product 1 has no preceding value; each later product shows its predecessor’s price.
Your progress
Reveal the check answer or reach the end to complete this lesson.