views:

839

answers:

3

I have a stored procedure that does a lot more reads when the NOLOCK hint is added to the query. I'm baffled - does anyone know why, please?

Details: The query is:

SELECT * FROM dbo.<table-name> WITH (NOLOCK).

It was doing 40,000 reads and there are less than 2,000 rows. I established that most of these reads are caused by 3 TEXT columns. (If I omit those it goes down to 59 reads!) But when I delete the WITH (NOLOCK) it goes from 40,000 reads to 13,000. I repeated this a few times because I thought I must have screwed up but it's really consistent both ways.

A: 

Maybe the read count includes page reads to read the locks?

Charles Bretana
I'm not with you, Charles. Doesn't WITH (NOLOCK) just ignore locks?
David Wimbush
@David, I confess I'm guessing on this one, but because it is ignoring these locks, doesn't that mean it doesn't have to read the disk to find out which ones are there that might affect the query... no ?
Charles Bretana
+1  A: 

NOLOCK reads data from transactions that have not been committed.

EDIT

Demo of NOLOCK read of uncommitted data.

create table table1 (id int, val int)
go

select * from table1 with ( NoLock)
begin tran
insert into table1 values (1,1)

--Switch to new query window
select * from table1 with ( NoLock)
--switch back
rollback tran
select * from table1 with ( NoLock)
cmsjr
why would you want to read data only from transaction logs? when is there a case when you need to not see the data from the actual database but you want to see the uncommitted data? i dont get it.
djangofan
Without running to multiple comments, it might be better to think of it as reading what's available in both the db and the transaction log. If there are no uncommitted transactions against the row/table your are reading you'll see what you would see normally, but if someone started a trans, inserted data , and later rolled back the insert you might read the data that was later rolled back. Why? Sometimes performance vs granular accuracy is a reasonable trade off. Alternately, lack of awareness of the implications ;)
cmsjr
A: 

Thanks, cmsjr, that makes sense but this table is rarely updated. I can't see how this effect would account for such a difference.

David Wimbush
And this would have inconsistent effect since it would depend on whether, and how large, any existing current transactions were...
Charles Bretana