Platform - SQL Server 2008 R2 This is part of a complex stored procedure, that was taking more than 5 minutes to execute and I was asked to help troubleshoot
;WITH FilteredOrders AS
(
--CTE definition
),
PagedOrders AS
(
SELECT * FROM
(
SELECT ROW_NUMBER() OVER ( order by OrderNumber asc ) AS Row,
--Column List from FilteredOrders
FROM FilteredOrders
) AS NumberedOrders
WHERE NumberedOrders.Row BETWEEN 1 AND 500
)
SELECT * FROM PagedOrders
I eliminated the sub-query in the second CTE and recommended this
;WITH FilteredOrders AS
(
--CTE definition
)
SELECT ROW_NUMBER() OVER ( order by OrderNumber asc ) AS Row,
--Column List from FilteredOrders
INTO #PagedOrders
FROM FilteredOrders
SELECT *
FROM #PagedOrders
WHERE #PagedOrders.Row BETWEEN 1 AND 500
Now the query executes in 2 seconds. Though I hate to admit it, the fact is that I do not fully understand the massive performance gain that the second query gave. Why am I seeing so much of a difference?