ROW_NUMBER() function in SQL

The ROW_NUMBER() function in SQL is used to assign a unique sequential integer to rows within a result set, based on a specified order.

SQL

ROW_NUMBER() OVER (ORDER BY column_name ASC|DESC)
Explanation:

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

Use the ROW_NUMBER() function to rank the rows according to the salary of the employees.

SQL

SELECT 
    EmployeeID, 
    Name, 
    Salary, 
    ROW_NUMBER() OVER (ORDER BY salary DESC) AS row_num
FROM Employees; 

This query assigns a row number to each employee, ordered by their salary in descending order (highest salary gets row number 1).

EmployeeIDNameSalaryrow_num
7Ankita90001
2Kirshan300002
1Ashish250003
3Anjali250004
6Esha200005
5Katrina180006
10Alia160007
4Manjulika150008
8Meenakshi150009

Explanation:

Example: Row Numbers Partitioned by Department We can also use ROW_NUMBER() to assign numbers within groups, for example, within each department.

SQL

SELECT 
    EmployeeID, 
    Name, 
    Salary, 
    ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS row_num
FROM Employees;  
EmployeeIDDepartmentNameSalaryrow_num
6ComputerEsha200001
5ComputerKatrina180002
8ComputerMeenakshi150003
2ElectricalKirshan300001
1ElectricalAshish250002
4ElectricalManjulika150003
7ElectronicsAnkita90001
3ElectronicsAnjali250002
10ElectronicsAlia160003

Explanation: