I have a fairly complex query in SQL Server running against a view, in the form:
SELECT *
FROM myview, foo, bar
WHERE shared=1 AND [joins and other stuff]
ORDER BY sortcode;
The query plan as shown above shows a Sort
operation just before the final SELECT
, which is what I would expect. There are only 35 matching records, and the query takes well under 2 seconds.
But if I add TOP 30
, the query takes almost 3 minutes! Using SET ROWCOUNT
is just as slow.
Looking at the query plan, it now appears to sort all 2+ million records in myview
before the joins and filters.
This "sorting" is shown on the query plan as an Index Scan on the sortcode
index, a Clustered Index Seek on the main table, and a Nested Loop between them, all before the joins and filters.
How can I force SQL Server to SORT
just before TOP
, like it does when TOP
isn't specified?
I don't think the construction of myview
is the issue, but just in case, it is something like this:
CREATE VIEW myview AS
SELECT columns..., sortcode, 0 as shared FROM mytable
UNION ALL
SELECT columns..., sortcode, 1 as shared FROM [anotherdb].dbo.mytable
The local mytable
has a few thousand records, and mytable
in the other database in the same MSSQL instance has a few million records. Both tables do have indexes on their respective sortcode
column.
WHERE shared=1
in your query actually cancels the first part of theUNION
view? – Wehrmacht[joins and other stuff]
part of the query. Perhaps some other index missing is what causes the optimizer to take the slow path. – Wehrmacht