Row_Number function in SQL
In this blog, you will see Row_Number function without Partition By or with Partition By clause.
Creating a table in SQL Server
Now we create a table named employee.
Create table Employee
(
EmpID int,
EmpName varchar(30),
EmpSalary int
)
The following is the sample data for the employee Table.

SQL ROW_NUMBER() Function
The Row_Numaber function is an important function when you do paging in SQL Server. The Row_Number function is used to provide consecutive numbering of the rows in the result by the order selected in the OVER clause for each partition specified in the OVER clause. It will assign the value 1 for the first row and increase the number of the subsequent rows.
Syntax
ROW_NUMBER ()
OVER ([PARTITION BY value_exp, ... [ n ]] order_by_clause)
OVER - Specify the order of the rows.
ORDER BY - Provide sort order for the records.
The ROW_NUMBER function enumerates the rows in the sort order defined in the over clause.
SQL ROW_NUMBER() Function without Partition By clause
Partition by clause is an optional part of Row_Number function and if you don't use it all the records of the result-set will be considered as a part of single record group or a single partition and then ranking functions are applied.
Example
SELECT *, ROW_NUMBER() OVER(ORDER BY EmpName) AS Row_Number
FROM Employee
Output

SQL ROW_NUMBER() Function with Partition By clause
When you specify a column or set of columns with the PARTITION BY clause, then it will divide the result set into record partitions. Then, finally ranking functions are applied to each record partition separately, and the rank will restart from 1 for each record partition separately.
Example
SELECT *, ROW_NUMBER() OVER(Partition by EmpName ORDER BY EmpName) AS Row_Number from Employee
Output


zeco jakePosted Apr 3, 2024, 8:43 AM
Hi Kumar, How to Display the Data based on Field Value, for example has field value qty 5 , so the data recordset will display only 5 following the Qty Value, if has Qty value 10 then the data recordset will display 10 and so on
Tamojit SarkarPosted Aug 25, 2023, 12:29 PM
Nice explaination, very helpful. : )
ahmed salahPosted Oct 19, 2022, 11:14 PM
Can you helping me working remotely on sql server or csharp or angular im have good experience on 3 languages
Dharmendra Kumar PanditPosted Sep 24, 2019, 11:34 AM
Very nice....Most valuable....
Sunil BhadauriyaPosted Mar 6, 2019, 4:37 AM
Good One indeed. Thanks Rohatash.
Dennis ThomasPosted Feb 21, 2018, 1:06 AM
Good one Rohatash, Thanks! As per my understanding, PARTITION BY is not an optional part of ROW_NUMBER() instead OVER() clause.
Vinnarasi VinsPosted Dec 26, 2017, 2:34 AM
In this given example, If i need to display Row_Number=1 how to do it? where Row_Number=1 cant be used here
Amit Kumar SinghPosted Feb 3, 2016, 8:21 AM
Nice One
mathi vPosted Sep 25, 2014, 10:44 AM
http://www.c-sharpcorner.com/Blogs/10458/