I have the following definition:
CREATE TABLE [dbo].[JobItems] (
[ItemId] UNIQUEIDENTIFIER NOT NULL,
[ItemState] INT NOT NULL,
[ItemCreationTime] DATETIME NULL DEFAULT GETUTCDATE(),
[ItemPriority] TINYINT NOT NULL DEFAULT(0),
[ItemRefreshTime] DATETIME NULL,
-- lots of other columns
CONSTRAINT [PrimaryKey_GUID_HERE] PRIMARY KEY NONCLUSTERED ([ItemId] ASC)
);
CREATE UNIQUE CLUSTERED INDEX [JobItemsIndex]
ON [dbo].[JobItems]([ItemId] ASC);
CREATE INDEX [GetTaskToProcessIndex]
ON [dbo].[JobItems]([ItemState], [ItemPriority], [ItemCreationTime])
and the following query:
SELECT TOP(1) ItemId FROM JobItems
WHERE ItemState = 5 OR
( ( ItemState = 11 ) AND ( DATEDIFF( SECOND, ItemRefreshTime, GETUTCDATE() ) > 14 ) )
ORDER BY ItemPriority ASC, ItemCreationTime ASC
I run this query and inspect the actual execution plan and here's what's going on:
- Index seek is done to retrieve items with
ItemState=5
. - Index seek is done to retrieve items with
ItemState=11
and then for each row a separate seek is done to retrieveItemRefreshTime
and the results of two seeks are filtered using nested loops. - Sets from 1 and 2 containing
ItemId
,ItemCreationTime
andItemPriority
are concatenated and then... - Magical
DistinctSort
happens withORDER BY ItemId ASC
and finally TopNSort
happens withORDER BY ItemPriority ASC, ItemCreationTime ASC
TopNSort
and DistinctSort
take something like 32 percent each so I'd be happy to get rid of DistinctSort
- I don't even understand its purpose.
What's this magical TopNSort
which useful DistinctSort
and why is it there?