I have a wide table, relatively large, 14,264,775 rows, running on Azure SQL database.
The following query is in need of some TLC.
IF EXISTS (
SELECT 1/0
FROM dbo.table1 src
INNER JOIN dbo.table1 tgt
ON tgt.Col1 = src.Col1
WHERE tgt.ValidFrom <= src.ValidTo
AND tgt.ValidTo >= src.ValidFrom
AND tgt.RecordId <> src.RecordId
)
BEGIN
RAISERROR('Overlap detected in dbo.table1', 11, 1);
END ;
I have this index.
CREATE NONCLUSTERED INDEX [IX__table1] ON dbo.table1
( Col1 )
INCLUDE (ValidFrom, ValidTo, RecordId)
GO
This is the io stats from the query. The logical reads are through the roof.
Here's the plan XML. I tried PasteThePlan but it wouldn't parse the plan XML. (perhaps it doesn't like Axure sql database plan xml).
As you can see there's an index scan on [src] ; reading 14,264,775 rows (the same number as all the rows in the table) . And an index seek on [tgt] ; reading 194,405,307 rows.
What do I need to change to improve the performance of the query?
There are 2.1 million unique Col1 values amongst the 14 million total rows.



