Unnecessary sort with TOP PERCENT?
17
votes
2
answers
1627
views
### Setup
### Execution plan
---
## Question
Why does SQL Server sort the column when the clustered index provides exactly that order?
---
### More rows
If I increase the number of rows in the table, I get an Eager Spool instead of a Sort and the index is scanned in order:
-- Create a heap table of numbers from 1 to 100
SELECT TOP (100)
i = IDENTITY(int, 1, 1)
INTO #T
FROM master.dbo.spt_values;
-- Add a clustered primary key
ALTER TABLE #T
ADD PRIMARY KEY CLUSTERED (i);
### Test query
Display 9% of the rows in primary key order:
SELECT TOP (9e) PERCENT
i
FROM #T
ORDER BY
i ASC;
DROP TABLE #T;
dbfiddle demo
### Results


-- Create a heap table of numbers from 1 to 1,000
SELECT TOP (1000)
i = IDENTITY(int, 1, 1)
INTO #T
FROM master.dbo.spt_values;
-- Add a clustered primary key
ALTER TABLE #T
ADD PRIMARY KEY CLUSTERED (i);
-- 0.9% now
SELECT TOP (9e-1) PERCENT
i
FROM #T
ORDER BY
i ASC;
DROP TABLE #T;

Asked by Paul White
(95060 rep)
Feb 18, 2025, 08:34 AM
Last activity: Feb 20, 2025, 08:52 AM
Last activity: Feb 20, 2025, 08:52 AM