101

I'm wondering what is the benefit to use SELECT WITH (NOLOCK) on a table if the only other queries affecting that table are SELECT queries.

How is that handled by SQL Server? Would a SELECT query block another SELECT query?

I'm using SQL Server 2012 and a Linq-to-SQL DataContext.

(EDIT)

About performance :

  • Would a 2nd SELECT have to wait for a 1st SELECT to finish if using a locked SELECT?
  • Versus a SELECT WITH (NOLOCK)?
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Francis P
  • 13,377
  • 3
  • 27
  • 51

6 Answers6

223

A SELECT in SQL Server will place a shared lock on a table row - and a second SELECT would also require a shared lock, and those are compatible with one another.

So no - one SELECT cannot block another SELECT.

What the WITH (NOLOCK) query hint is used for is to be able to read data that's in the process of being inserted (by another connection) and that hasn't been committed yet.

Without that query hint, a SELECT might be blocked reading a table by an ongoing INSERT (or UPDATE) statement that places an exclusive lock on rows (or possibly a whole table), until that operation's transaction has been committed (or rolled back).

Problem of the WITH (NOLOCK) hint is: you might be reading data rows that aren't going to be inserted at all, in the end (if the INSERT transaction is rolled back) - so your e.g. report might show data that's never really been committed to the database.

There's another query hint that might be useful - WITH (READPAST). This instructs the SELECT command to just skip any rows that it attempts to read and that are locked exclusively. The SELECT will not block, and it will not read any "dirty" un-committed data - but it might skip some rows, e.g. not show all your rows in the table.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 1
    Nice answer, thanks a lot! Would there be an impact (on hundreds of `SELECT` queries) to use `WITH (NOLOCK)` without reason? – Francis P Sep 26 '12 at 21:28
  • 8
    We use with nolock in 99.5% of our selects, no joke. If an admin is updating a user record you don't want that to cause the report to sit there and wait for the whole distributed transaction to finish. So their old data shows up on the report. Who cares? If the report had been run a second before that's the same data that would have been there with rowlock. The only place it's a concern is data that isn't committed yet. If you're showing "orders in the last hour" that could potentially be an issue, but a tiny, tiny issue compared to speed/concurrency gains. – Brian White Sep 27 '12 at 01:57
  • 6
    Also since 'report' was thrown out as an example, reports are typically for a time period that is not the past 5 minutes. Reporting on data from last month with nolock - well it's not like the data is going to rollback a month later. – Brian White Sep 27 '12 at 02:06
  • @FrancisP: other than potentially having "dirty" data in your result set - no, I don't see any (negative) impact. And as Brian White correctly stated - if you're doing reporting etc., it's rather unlikely you'll get unwanted, non-committed data – marc_s Sep 27 '12 at 04:48
  • Oh and guys, If I got a table where each user is accessing its own rows (according to user_id), and they're doing `SELECT`,`INSERT` and `DELETE` operations, would an `INSERT` query block the entire table? (Since the other requests are `INSERT` or `SELECT` queries affecting different rows..) – Francis P Sep 27 '12 at 14:05
  • 3
    @FrancisP: not if you insert a small number of rows - in that case, it just locks the new rows being inserted. If you insert more than roughly 5000 rows at once - then a lock escalation will occur and the whole table will be exclusively locked. – marc_s Sep 27 '12 at 14:06
  • @marc_s : No, only inserting or deleting 1 row per query and mostly selecting 1 row per query on that table. But I also have some other tables accessed by all users for `SELECT` queries using same Data and was wondering if a `WITH (NOLOCK)` was realy relevant for that situation. – Francis P Sep 27 '12 at 14:09
  • we put WITH (NOLOCK) just the beginning of the query? – Furkan Gözükara Jul 18 '16 at 12:53
  • 1
    Very nice answer..It felt like an all in one tutorial for SQL locks!! glad I got in here! – digitally_inspired Nov 16 '18 at 15:47
38

On performance you keep focusing on select.
Shared does not block reads.
Shared lock blocks update.
If you have hundreds of shared locks it is going to take an update a while to get an exclusive lock as it must wait for shared locks to clear.

By default a select (read) takes a shared lock.
Shared (S) locks allow concurrent transactions to read (SELECT) a resource.
A shared lock as no effect on other selects (1 or a 1000).

The difference is how the nolock versus shared lock effects update or insert operation.

No other transactions can modify the data while shared (S) locks exist on the resource.

A shared lock blocks an update!
But nolock does not block an update.

This can have huge impacts on performance of updates. It also impact inserts.

Dirty read (nolock) just sounds dirty. You are never going to get partial data. If an update is changing John to Sally you are never going to get Jolly.

I use shared locks a lot for concurrency. Data is stale as soon as it is read. A read of John that changes to Sally the next millisecond is stale data. A read of Sally that gets rolled back John the next millisecond is stale data. That is on the millisecond level. I have a dataloader that take 20 hours to run if users are taking shared locks and 4 hours to run is users are taking no lock. Shared locks in this case cause data to be 16 hours stale.

Don't use nolocks wrong. But they do have a place. If you are going to cut a check when a byte is set to 1 and then set it to 2 when the check is cut - not a time for a nolock.

paparazzo
  • 44,497
  • 23
  • 105
  • 176
  • 2
    Thank you. We see similar performance characteristics. Our site wouldn't run if we required locks for reads, and the impact of not having it in most cases is just insignificant. – Brian White Sep 27 '12 at 02:00
  • @BrianWhite Thank you. Someone gets it. And I take a lot of table locks on update and insert. Get in, get it done, and get out is my approach. – paparazzo Sep 27 '12 at 02:21
  • 2
    Dirty read (nolock) just sounds dirty. You are never going to get partial data. If an update is changing John to Sally you are never going to get Jolly. - we read John right? – Furkan Gözükara Jul 18 '16 at 12:54
  • 2
    Updates in sql server use update lock (U) that is later converted to exclusive lock (X). (see http://www.madeiradata.com/role-update-lock-sql-server/) Update lock doesn't block shared locks, but exclusive lock blocks all other locks (see https://msdn.microsoft.com/en-us/library/ms186396(v=sql.105).aspx). – kolobok Feb 21 '18 at 15:56
  • @kolobok going to take an update a while to get an exclusive lock – paparazzo Feb 21 '18 at 16:13
18

I have to add one important comment. Everyone is mentioning that NOLOCKreads only dirty data. This is not precise. It is also possible that you'll get the same row twice or the whole row is skipped during your read. The reason is that you could ask for some data at the same time when SQL Server is re-balancing b-tree.

Check another threads

https://stackoverflow.com/a/5469238/2108874

http://www.sqlmag.com/article/sql-server/quaere-verum-clustered-index-scans-part-iii.aspx)

With the NOLOCK hint (or setting the isolation level of the session to READ UNCOMMITTED) you tell SQL Server that you don't expect consistency, so there are no guarantees. Bear in mind though that "inconsistent data" does not only mean that you might see uncommitted changes that were later rolled back, or data changes in an intermediate state of the transaction. It also means that in a simple query that scans all table/index data SQL Server may lose the scan position, or you might end up getting the same row twice.

Milan Matějka
  • 2,654
  • 1
  • 21
  • 23
11

At my work, we have a very big system that runs on many PCs at the same time, with very big tables with hundreds of thousands of rows, and sometimes many millions of rows.

When you make a SELECT on a very big table, let's say you want to know every transaction a user has made in the past 10 years, and the primary key of the table is not built in an efficient way, the query might take several minutes to run.

Then, our application might me running on many user's PCs at the same time, accessing the same database. So if someone tries to insert into the table that the other SELECT is reading (in pages that SQL is trying to read), then a LOCK can occur and the two transactions block each other.

We had to add a "NO LOCK" to our SELECT statement, because it was a huge SELECT on a table that is used a lot by a lot of users at the same time and we had LOCKS all the time.

I don't know if my example is clear enough? This is a real life example.

JonnyRaa
  • 7,559
  • 6
  • 45
  • 49
Danielle Paquette-Harvey
  • 1,691
  • 1
  • 16
  • 31
  • Thank you for the example, but I'm only wondering about SELECT queries affecting other SELECT queries (on that same table).. – Francis P Sep 26 '12 at 19:36
  • 1
    They won't, but a select statement could be part of transaction that includes an update. Update tbl set x = (select max(y) from tbl) where z = (select min(a) from tbl). If you have a concurrent select z from tbl well the other selects aren't blocking it, but the update is. – Brian White Sep 27 '12 at 02:03
  • 1
    I had exactly this issue that a long running select was blocking my inserts – nojetlag Jul 03 '13 at 14:13
  • 3
    The transactions won't block each other - the select will block the update. Here's a couple of interesting links that have just helped me understand a little more about how this stuff works: [first one](http://blog.sqlauthority.com/2012/11/15/sql-server-concurrency-basics-guest-post-by-vinod-kumar/) [second one](http://blogs.extremeexperts.com/2012/11/15/sql-server-locking-basics/) – JonnyRaa Apr 21 '15 at 09:54
  • @JonnyLeeds : Your 2nd link doesn't work anymore. Here is an archived link of [SQL Server: Locking basics](http://web.archive.org/web/20170930025858/http://blogs.extremeexperts.com:80/2012/11/15/sql-server-locking-basics) – stomy Apr 19 '18 at 15:36
3

The SELECT WITH (NOLOCK) allows reads of uncommitted data, which is equivalent to having the READ UNCOMMITTED isolation level set on your database. The NOLOCK keyword allows finer grained control than setting the isolation level on the entire database.

Wikipedia has a useful article: Wikipedia: Isolation (database systems)

It is also discussed at length in other stackoverflow articles.

rghome
  • 8,529
  • 8
  • 43
  • 62
  • Thanks rghome for the additional information you provided. – Francis P Dec 05 '14 at 16:03
  • This is why I prefer using the `READUNCOMMITTED` (an alias for `NOLOCK`) hint, *when* such is a valid use-case. Doing so makes the actual operation, which *isn't* really "without locks", less unclear. – user2864740 Dec 16 '15 at 22:43
1

select with no lock - will select records which may / may not going to be inserted. you will read a dirty data.

for example - lets say a transaction insert 1000 rows and then fails.

when you select - you will get the 1000 rows.

Royi Namir
  • 144,742
  • 138
  • 468
  • 792