I have a pivot query on a table with millions of rows. Running the query normally, it runs in 2 seconds and returns 2983 rows. If I add TOP 1000 to the query it takes 10 secon
There is a specific order in which queries are processed.
A normal SQL query will be written as follows:
SELECT [...]
FROM [table1]
JOIN [table2]
ON [condition]
WHERE [...]
GROUP BY [...]
HAVING [...]
ORDER BY [...]
But the processing order is different:
FROM [table1]
ON [condition]
JOIN [table2]
WHERE [...]
GROUP BY [...]
HAVING [...]
SELECT [...]
ORDER BY [...]
When using SELECT DISTINCT [...]
or SELECT TOP [...]
the processing order will be as follows:
FROM [table1]
ON [condition]
JOIN [table2]
WHERE [...]
GROUP BY [...]
HAVING [...]
SELECT [...] DISTINCT[...]
ORDER BY [...]
TOP [....]
Hence it's taking longer as your SELECT TOP 1000
is processed last.
Take a look at this link for further details: http://blogs.msdn.com/b/sqlqueryprocessing/