I was doing paging in SQL Server 2000 using Temp Table or Derived Tables. I decided to checkout new function ROW_NUMBER() in SQL Server 2005. ROW_NUMBER() returns the sequential number of a row within a partition of a result set, starting at 1 for the first row in each partition. I have compared both the following query on SQL Server 2005.
SQL 2005 Paging Method
USE AdventureWorks GO DECLARE @StartRow INT DECLARE @EndRow INT SET @StartRow = 120 SET @EndRow = 140SELECT FirstName, LastName, EmailAddress FROM ( SELECT PC.FirstName, PC.LastName, PC.EmailAddress, ROW_NUMBER() OVER( ORDER BY PC.FirstName, PC.LastName,PC.ContactID) AS RowNumber FROM Person.Contact PC) PersonContact WHERE RowNumber > @StartRow AND RowNumber < @EndRow ORDER BY FirstName, LastName, EmailAddress GO
SQL 2000 Paging Method
USE AdventureWorks GO DECLARE @StartRow INT DECLARE @EndRow INT SET @StartRow = 120 SET @EndRow = 140CREATE TABLE #tables (RowNumber INT IDENTITY(1,1), FirstName VARCHAR(100), LastName VARCHAR(100), EmailAddress VARCHAR(100)) INSERT INTO #tables (FirstName, LastName, EmailAddress) SELECT PC.FirstName, PC.LastName, PC.EmailAddress FROM Person.Contact PC ORDER BY FirstName, LastName, EmailAddressSELECT FirstName, LastName, EmailAddress FROM #tables WHERE RowNumber > @StartRow AND RowNumber < @EndRow DROP TABLE #tables GO
While running both the query at same time in query analyzer and comparing execution plan I have discovered that SQL 2005 query method cost is 46% and SQL 2000 query method cost is 54%. Looking at client Statistics I noticed significant improvement in Time Statistics.
Update (6/11/2007) : Extention of this article is published SQL SERVER - 2005 T-SQL Paging Query Technique Comparison (OVER and ROW_NUMBER()) - CTE vs. Derived Table
Reference : Pinal Dave (http://www.SQLAuthority.com)






[...] 11th, 2007 by pinaldave I have received few emails and comments about my post SQL SERVER - T-SQL Paging Query Technique Comparison - SQL 2000 vs SQL 2005. The main question was is this can be done using CTE? Absolutely! What about Performance? It is [...]
send me the interview questions
i am pretty much interested in the interview questions and answers
You rock!
you’re freaking amazing!!! give me more of your sweet sweet sql juice!
Pinal,
You insights are great and valuable. Please remove the post(s) whoever bugging and asking you about interview questions. They need to start contribution and add value to the group and not just bug you.
Thanks,
can anybody send me some interview question
Can sombody tell me about triggers in detail with example?
send me the interview questions.
Hi Pinal Dave,
Can you Please tell me what the difference between in Sql Sever 2005 and Sql Server 2000. Means what new enhancement is done in sql Server 2005 as compared to sql server 2000.(In brief)
Thanks in Advance.