Azure SQL Database.
I have a table from which I need to get the first and most recent rows for Col1
and Col2
based on CreateDate
.
CREATE TABLE dbo.table1 (
Id INT IDENTITY(1,1) PRIMARY KEY ,
Col1 VARCHAR(255) COLLATE SQL_Latin1_General_CP1_CS_AS NOT NULL ,
Col2 VARCHAR(255) COLLATE SQL_Latin1_General_CP1_CS_AS NOT NULL ,
CreateDate DATETIME NOT NULL
) ;
I have an index like so:
CREATE INDEX IX__table1_ASC
ON dbo.table1 (Col1, Col2, CreateDate );
My query to get the first row is (plan here):
--Get the first row
SELECT TOP (1) WITH TIES
*
FROM table1
ORDER BY ROW_NUMBER()
OVER (PARTITION BY Col1, Col2
ORDER BY CreateDate );
The index scan is using the index (IX__table1_ASC
) I created, but why am I getting a sort?
My query to get the most recent row (plan here):
--get latest row
SELECT TOP (1) WITH TIES
*
FROM table1
ORDER BY ROW_NUMBER()
OVER (PARTITION BY Col1, Col2
ORDER BY CreateDate DESC); --desc here
Again, the index scan is using the index (IX__table1_ASC
), but this time I'm getting two sorts.
The first one straight after the index scan.
Isn't the optimiser clever enough to read the index in reverse order?
Again, what's the second sort for?
The actual table is quite large, so you can imagine the sorts are costly. How can I best optimise here?