adsense

Saturday, December 20, 2025

SQL Server LAG() Function

 The SQL LAG() function is a window function used to access a column’s value from a previous row within a defined partition and order. Unlike aggregate functions, it does not reduce the number of rows; instead, it returns a corresponding value for each row. By specifying a partition (e.g., by organisation) and an order (e.g., by year), LAG() enables row-by-row comparisons, such as comparing current values with prior-period values


E.g

SELECT 

    Department,

    Employee,

    SalaryMonth,

    Salary,

    LAG(Salary, 1, 0) 

        OVER (PARTITION BY Department ORDER BY SalaryMonth) AS PrevMonthSalary

FROM EmployeeSalary

ORDER BY Department, SalaryMonth

Result

DepartmentEmployeeSalaryMonthSalaryPrevMonthSalary
ITJohn2024-011200000
ITJohn2024-02125000120000
ITJohn2024-03130000125000
HRMary2024-01900000
HRMary2024-029200090000
HRMary2024-039500092000