Mid Detailed answer Window Functions SQL & Databases

Write a query using LEAD and LAG.

Short answer: LAG looks at the previous row; LEAD looks at the next row within an ordered partition. Great for day-over-day diffs.

Sample solution

T-SQL
SELECT OrderDate, Amount,
       LAG(Amount, 1) OVER (ORDER BY OrderDate) AS PrevAmount,
       LEAD(Amount, 1) OVER (ORDER BY OrderDate) AS NextAmount,
       Amount - LAG(Amount, 1) OVER (ORDER BY OrderDate) AS Delta
FROM DailySales;
Always specify ORDER BY in OVER — without it the result is nondeterministic.
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details