ROW_NUMBER SQL Function Overview (2023)

In this article, we will discuss the SQL ROW_NUMBER function. This is a continuation of the SQL Fundamentals series. In this guide, I'll explain what window functions are and see sample examples to help you understand the concepts behind the SQL ROW_NUMBER function.

show

The most commonly used function in SQL Server is the SQL ROW_NUMBER function. The SQL ROW_NUMBER function is available in SQL Server 2005 and later versions.

ROW_NUMBER adds unique increment numbers to the result grid. The order in which row numbers are applied is determined by the ORDER BY expression. In most cases, one or more columns are specified in the ORDER BY expression, but more complex expressions or even subqueries can also be used. So it creates an ever-increasing integer value, always starting at 1, and subsequent rows get the next higher value.

You can also use it with a PARTITION BY clause. But when it crosses a partition limit or a limit, it resets the counter and starts at 1. So one partition can have values ​​1, 2, 3, etc., and the second partition starts the counter again from 1, 2 , 3.... etc., etc.

Basic:

  1. The SQL ROW_NUMBER function is a non-permanent creation of a temporary sequence of values ​​and is calculated dynamically when the query is executed.
  2. There is no guarantee that the rows returned by an SQL query that uses the SQL ROW_NUMBER function will be sorted in exactly the same order each time it is executed.
  3. The ROW_NUMBER and RANK functions are similar. The output of ROW_NUMBER is a sequence of values ​​starting at 1 and incrementing by 1, and the value of the RANK function is also incremented by 1, but for a tie, the values ​​will be repeated.
  4. If you have experience with Oracle, you will be more familiar with ROWNUM. It is a false pillar. It starts at 1 and increments by 1 until the end of the table.
  5. The SQL ROW_NUMBER function is dynamic in nature and we can return the value using the PARTITION BY clause
  6. The ORDER BY clause of the query and the ORDER BY clause of the OVER clause have nothing to do with each other.

pension

1

2

ROW_NUMBER( )

Exceed ( [ Division pass through value_expression1 , ... [ n ] ] order by clause column 1,column 2..)

ROW_NUMBER

ROW_NUMBER followed by the OVER function and then an ORDER BY clause in parentheses. The ORDER BY clause is required to sort the result set.

Exceed

The OVER term defines the window or set of rows that the window function operates on, so it's important to understand this. Possible elements of the OVER clause are ORDER BY and PARTITION BY.

ORDER BY expressions with OVER clauses are supported when the rows must be ordered in a specific way for the function to work correctly.

1

Division pass through value_expression1

Partition base

The Partition By clause is optional. When you specify a value, it will be divided byfromThe clause inserts the partition with the SQL ROW_NUMBER function applied. The values ​​specified in the PARTITION clause define the boundaries of the result set. If no PARTITION BY clause is specified, the OVER clause acts on all rows in the result set as a single data set. The clause can consist of one or more columns, more complex expressions, or even subqueries.

order by clause

Order by clause is a mandatory clause. Specifies the order and association of temporary values ​​with the rows of the specified partition. The ORDER BY clause is an expression of the OVER clause, which specifies how the function should order the rows in a specific way.

demonstration

In this section, we will learn about the SQL ROW_NUMBER function. Throughout the demo, I used the AdventureWorks2016 database.

How to use ROW_NUMBER in SQL queries

In the following example, we will see the use of the OVER clause.

Let's get a list of all customers by displaying columns like SalesOrderID, OrderDate, SalesOrderNumber, SubTotal, TotalDue, and RowNum. The Row_Number function is applied to the order of the CustomerID column. Temporary values ​​start at 1 assigned in the row of CustomerID and continue to the last row of the array. Since we did not specify an ORDER BY clause in the query, the order of CustomerID is not guaranteed.

1

2

3

4

5

6

7

8

9

10

11

use Adventure Factory 2016;

I am going

choose ROW_NUMBER() Exceed(

Series pass through Customer's code) as Row number,

Customer's code,

sales order id,

date of order,

sales order number,

Subtotal,

Total payable

from sales volume.sales order title;


ROW_NUMBER SQL Function Overview (1)

How to use the Order by clause

The following example uses the ORDER BY clause in the query. The ORDER BY clause in the query is applied to the SalesOrderID column. We can see that the rows in the output are still sorted and returned. Row_Number still applies to CustomerID. The output shows that the ORDER BY of the query and the ORDER BY of the OVER clause are unrelated to the output.

1

2

3

4

5

6

7

8

9

10

11

12

use Adventure Factory 2016;

I am going

choose ROW_NUMBER() Exceed(

Series pass through Customer's code) as Row number,

Customer's code,

sales order id,

date of order,

sales order number,

Subtotal,

Total payable

from sales volume.sales order title

Series pass through sales order id;


ROW_NUMBER SQL Function Overview (2)

How to use multiple columns with OVER clause

In the example below, you can see that we list the customer ID and order date in the ORDER BY clause. This provides the customer with the latest order details and the sequence of numbers assigned to the entire result set.

1

2

3

4

5

6

7

8

9

10

use Adventure Factory 2016;

I am going

choose ROW_NUMBER() Exceed(Series pass through Customer's code, date of order DESC) as Row number,

Customer's code,

sales order id,

date of order,

sales order number,

Subtotal,

Total payable

from sales volume.sales order title


ROW_NUMBER SQL Function Overview (3)

How to use SQL ROW_NUMBER function with PARTITION

The following example uses the PARTITION BY clause on the CustomerID and OrderDate fields. At the exit you can see the customer11019There were three orders in June 2014. In this case the partitioning is done on multiple columns.

The partition is a combination of OrderDate and CustomerID. Row_Number will start over for each unique combination of OrderDate and CustomerID. This way, it is easy to find customers who have placed multiple orders on the same day.

1

2

3

4

5

6

7

8

9

10

11

12

use Adventure Factory 2016;

I am going

choose ROW_NUMBER() Exceed(Division pass through Customer's code,

Date added(moon, date difference(moon, 0, date of order), 0)

Series pass through Subtotal DESC) as Orders per month,

Customer's code,

sales order id,

date of order,

sales order number,

Subtotal,

Total payable

from sales volume.sales order title;


ROW_NUMBER SQL Function Overview (4)

How to return a subset of rows using CTE and ROW_NUMBER

In the following example, we will parse the SalesOrderHeader to display the top five largest orders placed by each customer per month. Using the Month function, you can manipulate the orderDate column to get the month part. In this way, sales corresponding to a specific month (OrderDate) and customer (CustomerID) are shared.

To list the top five orders per month for each customer, a CTE is required. Create a window on the partitioned data, assign values ​​to it, and call the CTE to get the maximum order.

1

2

3

4

5

6

7

8

9

10

11

12

and CTE

as ( chooseROW_NUMBER Exceed ( Division pass through Customer's code,moon(date of order) Series pass through Subtotal DESC, Total payable DESC ) as ROW_NUM,

Customer's code,

moon(date of order) moon,

Subtotal ,

Total payable ,

date of order

from sales volume.sales order title

)

choose*

fromCTE

Where ROW_NUM <= 5


ROW_NUMBER SQL Function Overview (5)

sum up

So far, we have looked at the SQL ROW_NUMBER function in detail. We have discussed many examples ranging from simple to complex. We also discussed how to use SQL ROW_NUMBER function with CTE (Common Table Expressions). In most cases, you will always see an over clause in every window function.

The over clause defines the window that each row views. In the over clause, there is a from partition supported by each window function, followed by a row by clause. That's all for now... We hope you enjoyed reading this article.


  • author
  • Recent Posts

ROW_NUMBER SQL Function Overview (6)

I am a database technologist with over 11 years of solid hands-on experience in database technology. I am a Microsoft Certified Professional and have a Masters in Computer Applications.

My expertise lies in the design and implementation of high availability and cross-platform database migration solutions. Technologies currently working are SQL Server, PowerShell, Oracle and MongoDB.

View all posts by Prashanth Jayaram

ROW_NUMBER SQL Function Overview (7)

Latest Posts by Prashanth Jayaram(view all)

  • Ladder of SQL Fundamentals- April 7, 2021
  • A quick overview of database control in SQL- January 28, 2021
  • How to set up Azure Data Sync between Azure SQL Database and on-premises SQL Server- January 20, 2021

Relevant Articles:

  1. ROW_NUMBER SQL Function Overview
  2. Overview of SQL COUNT and COUNT_BIG in SQL Server
  3. Overview of static and dynamic SQL Pivot and Unpivot Relational Operators
  4. SQL Server Header Operation Overview and Examples
  5. Overview of SQL date formats, SQL DateDiff function, SQL DateAdd function, and more

References

Top Articles
Latest Posts
Article information

Author: Patricia Veum II

Last Updated: 01/09/2023

Views: 6166

Rating: 4.3 / 5 (44 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Patricia Veum II

Birthday: 1994-12-16

Address: 2064 Little Summit, Goldieton, MS 97651-0862

Phone: +6873952696715

Job: Principal Officer

Hobby: Rafting, Cabaret, Candle making, Jigsaw puzzles, Inline skating, Magic, Graffiti

Introduction: My name is Patricia Veum II, I am a vast, combative, smiling, famous, inexpensive, zealous, sparkling person who loves writing and wants to share my knowledge and understanding with you.