LAG() and LEAD() functions in SQL

In SQL, LAG() and LEAD() are window functions used to access data from a preceding or succeeding row within a result set.

1. LAG() function in SQL

The LAG() function allows us to access data from a previous row in the result set.

SQL Syntax

LAG(column_name, offset, default_value) OVER (PARTITION BY column_name ORDER BY column_name)
The function has the following parameters:

Example: Create the Employees table.

SQL

CREATE TABLE Employees (
   EmployeeID INT,
    Name VARCHAR(20),
    Age int,
    Salary VARCHAR(10),
    Department VARCHAR(25),
    Gender VARCHAR(1)
);      

SQL

CREATE TABLE Employees (
   EmployeeID INT,
    Name VARCHAR(20),
    Age int,
    Salary VARCHAR(10),
    Department VARCHAR(25),
    Gender VARCHAR(1)
);      

Insert the data in the Employees table.

SQL

insert into Employees values
(1, "Ashish", 24, "25000", "Electrical", "M"), 
(2, "Kirshan", 32,"30000", "Electrical", "M"),
(3, "Anjali", 20,"25000", "Electronics", "F"),
(4, "Manjulika", 30, "15000", "Electrical", "F"),
(5, "Katrina", 37,"18000", "Computer", "F"),
(6, "Esha", 37,"20000", "Computer", "F"),
(7, "Ankita", 20,"9000", "Electronics", "M"), 
(8, "Meenakshi", 30, "15000", "Computer", "F"),
(10, "Alia", 37,"16000", "Electronics", "F")
;          

By using the Create table and insert statement we reach to the following table in our database:

Table: Employees

EmployeeIDNameAgeSalaryDepartmentGender
1Ashish2425000ElectricalM
2Kirshan3230000ElectricalM
3Anjali2025000ElectronicsF
4Manjulika3015000ElectricalF
5Katrina3718000ComputerF
6Esha3720000ComputerF
7Ankita209000ElectronicsM
8Meenakshi3015000ComputerF
10Alia3716000ElectronicsF

SQL

SELECT 
    EmployeeID, 
    salary, 
    LAG(salary, 1, 0) OVER (ORDER BY salary) AS previous_salary
FROM employees;  

This will return the salary from the previous row, ordered by salary.

EmployeeIDSalaryPrevious Salary
4150000
81500015000
101600015000
51800016000
62000018000
12500020000
32500025000
23000025000
7900030000

2. LEAD() function in SQL

The LEAD() function allows you to access data from a subsequent row in the result set.

SQL Syntax

LEAD(column_name, offset, default_value) OVER (PARTITION BY column_name ORDER BY column_name)
The function has the following parameters:

Example:

SQL

SELECT 
  EmployeeID, 
  salary, 
  LAG(salary, 1, 0) OVER (ORDER BY salary) AS previous_salary
FROM employees;  

This will return the salary from the next row, ordered by salary.

EmployeeIDSalaryNext Salary
41500015000
81500016000
101600018000
51800020000
62000025000
12500025000
32500030000
2300009000
790000