Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 XLOCK and ordering

Author  Topic 

kensai
Posting Yak Master

172 Posts

Posted - 2012-08-03 : 08:11:14
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 MyTable
SET column1 = @value1
OUTPUT 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 MyTable
SET column1 = @value1
OUTPUT 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.

DonAtWork
Master Smack Fu Yak Hacker

2167 Posts

Posted - 2012-08-03 : 09:47:51
TOP means nothing without an order by. The first one executes instantly because the TOP does pretty much nothing. The second one is doing a TRUE TOP because it has an ORDER BY clause. It takes the server a little time to actually order the records. You can improve the time with some indexing, i would bet.








How to ask: http://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx

Go to Top of Page

kensai
Posting Yak Master

172 Posts

Posted - 2012-08-04 : 11:09:42
quote:
Originally posted by DonAtWork

TOP means nothing without an order by. The first one executes instantly because the TOP does pretty much nothing. The second one is doing a TRUE TOP because it has an ORDER BY clause. It takes the server a little time to actually order the records. You can improve the time with some indexing, i would bet.



Thanks for the info.

The TOP query itself takes only 1 second. "type" and "status" columns have indexes (although not by themselves, other columns are included to their particular indexes)..
Go to Top of Page
   

- Advertisement -