I have query which I use to select n number of records next in the line. My problem is, if I select the records using ORDER BY, the query takes a lot longer.This query completes instantly in milliseconds:DECLARE @tmp TABLE(Id INT NOT NULL IDENTITY(1, 1), Code CHAR(8) NOT NULL);UPDATE MyTableSET column1 = @value1OUTPUT inserted.Code INTO @tmp (Code)WHERE type = 1 AND status = 0 AND Code IN ( SELECT TOP(@count) Code FROM MyTable WITH (READPAST, XLOCK) WHERE type = 1 AND status = 0);
This one takes 6 seconds:DECLARE @tmp TABLE(Id INT NOT NULL IDENTITY(1, 1), Code CHAR(8) NOT NULL);UPDATE MyTableSET column1 = @value1OUTPUT inserted.Code INTO @tmp (Code)WHERE type = 1 AND status = 0 AND Code IN ( SELECT TOP(@count) Code FROM MyTable WITH (READPAST, XLOCK) WHERE type = 1 AND status = 0 ORDER BY PrimaryKeyColumn);
Table MyTable has 4.5 million records, type = 1 is 25K of it.I tried using UPDLOCK instead of XLOCK but result didn't change.Is there a way to improve this query? I understand the lock hint locks records it traverses but I don't know what to do here.