Checking my execution plan it shows a warning in a Top N Sort step
Operator used tempdb to spill data during execution with spill level 1 and 4 spilled thread(s), Sort wrote 4609 pages to and read 4609 pages from tempdb with granted memory 107360KB and used memory 107360KB
Is this a bad thing and how should I tackle it?
The original query was
select a.* from TableA a where id in (
select a.id from TableA a join TableAB ab on a.id = ab.aid join TableB b on ab.bid = b.id
order by a.datetime desc offset 1000000 rows fetch next 10 rows only
)
In case you wonder, the above was meant to be a faster version of
select a.* from TableA a join TableAB ab on a.id = ab.aid join TableB b on ab.bid = b.id
order by a.datetime desc offset 1000000 rows fetch next 10 rows only
but although it ran faster, it gave that warning message above.
As a rule, it's preferable using
EXISTSoverINclause, this is assuming that you don't want duplicates from TableA as @seanb. a possible rewriting to the query using nestedEXISTSwould look likeThe SORT is inevitable, but it should happen on fewer columns than using the ORDER inside the
INclause. Even if you see the spill warning, you can check the number of pages is reduced, IMO, 4609 pages (~36MB) spill shouldn't make much difference, unless you are running this every few seconds.