IMG-LOGO

How to use ROW_NUMBER in TSQL?

andy - 06 Jan, 2021 1658 Views 0 Comment

If you want to have a sequential number against a row in SQL Server record. You can use the number function called ROW_NUMBER. This function is usually used when you want to perform a page paging for a large number of records.

Let says we have a product table that we want to include the sequential number against the row.

Here is the TSQL Query to use the ROW_NUMBER in SQL Server.


SELECT	ROW_NUMBER() OVER(
			PARTITION BY CategoryId
			ORDER BY Name
		) AS Row_Index, 
		CategoryId, 
		Name, 
		Price
FROM  Products

This is the result if we run the above TSQL query.

If you want to divide the result based on the CategoryId, we can also use the PARTITION keyword. See below query example.


SELECT	ROW_NUMBER() OVER(
			PARTITION BY CategoryId
			ORDER BY Name
		) AS Row_Index, 
		CategoryId, 
		Name, 
		Price
FROM  Products

Here is the result after we apply the PARTITION keyword which will categorize the result based on the CategoryId column.

Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.

Related Articles

How to restore database using SQL query in TSQL?

If you have a database backup bak file extension and want to restore it using SQL query You can use the built in RESTORE DATABASE function Remember in order to be able to restore a database successfully You need to ...

How to get all table sizes in TSQL?

To get the information about how much space or size used by tables You can retrieve the size information by linking multiple tables in sys tables There are two tables that hold this information The first one is the sys ...