LAG is a window function that accesses a value from a previous row within an ordered window. It can be used on data produced by a JOIN.
Comparing current and previous values is important for trend, performance, and change analysis.
Compare each customer's current order amount with their previous order amount.
SELECT
c.CustomerName,
o.OrderDate,
o.OrderAmount,
LAG(o.OrderAmount) OVER (
PARTITION BY o.CustomerID
ORDER BY o.OrderDate
) AS PreviousOrderAmount
FROM Customers c
INNER JOIN Orders o
ON c.CustomerID = o.CustomerID;
Used in sales trends, transaction analysis, financial monitoring, and time-series reporting.
- LAG accesses a previous row.
- ORDER BY defines the sequence.
- PARTITION BY separates entities.
- JOIN can provide descriptive information.
- LAG is useful for change analysis.
What does LAG do?
LAG returns a value from a previous row within an ordered window.
How can LAG help after a JOIN?
It can compare sequential records while the JOIN provides related descriptive information.