Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the differences between the older row_number() and the newer OFFSET + FETCH based pagination in SQL Server?

Tags:

I have few questions in context of the older row_number (SQL Server 2008) and the newer OFFSET + FETCH (SQL Server 2012) paging mechanism provided by SQL Server 2012.

  1. What are the limitations with row_number()?
  2. Is OFFSET + FETCH an improved replacement for row_number()?
  3. Are there any use-cases which could only be sufficed using one and not the other?
  4. Are there any performance differences between the two? If yes, which one is recommended?

Thanks.

like image 680
Anand Patel Avatar asked May 05 '13 05:05

Anand Patel


People also ask

What is ROW_NUMBER () function then what is the use of over () clause?

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. OVER - Specify the order of the rows.

What is ROW_NUMBER () function in SQL?

ROW_NUMBER function is a SQL ranking function that assigns a sequential rank number to each new record in a partition. When the SQL Server ROW NUMBER function detects two identical values in the same partition, it assigns different rank numbers to both.

Is ROW_NUMBER faster than group by?

According to the optimizer, in my case the ROW_NUMBER is about 60% more efficient according to the subtree cost. And according to statistics IO, about 20% less CPU time. However, in real elapsed time, the ROW_NUMBER solution takes about 80% more real time. So the GROUP BY wins in my case.

What is ROW_NUMBER () and partition by in SQL Server?

The PARTITION BY clause divides the result set into partitions (another term for groups of rows). The ROW_NUMBER() function is applied to each partition separately and reinitialized the row number for each partition. The PARTITION BY clause is optional.


1 Answers

Using ROW_NUMBER() works fine - it's just more work than necessary; you need to write a "skeleton" CTE around your actual query, add the ROW_NUMBER() column to your output set, and then filter on that.

Using the new OFFSET / FETCH is simpler - and yes, it's also better for performance, as these two links can show you:

  • New T-SQL features in SQL Server 2012
  • Comparing performance for different SQL Server paging

So overall: if you're using SQL Server 2012 - then you should definitely use OFFSET/FETCH rather than ROW_NUMBER() for paging

like image 192
marc_s Avatar answered Sep 22 '22 18:09

marc_s