T-SQL Tutorial

T-SQL LAG


The T-SQL LAG function is an analytic function and is used in SQL Server database to return values from a previous row in the same result. First data value is null.

LAG Syntax


LAG (scalar_expression [,offset] [,default])
OVER ( [ partition_by_clause ] order_by_clause )



LAG Example


select b.*,
LAG(b.name) OVER (ORDER BY b.price) AS PrevBook
from books b;