February 15, 2007

SQL Server Deadlock - NOLOCK and ROWLOCK hints

Deadlock is something that will become most certainly, subject of your worries sooner or later during the lifetime of your application (or better to say database). Since MS SQL Server requires locks for SELECT, even those people who are not trying to modify database are involved in locking system. UPDATE and DELETE, obviously, requires locks. Even if you refer directly to primary key, page locks are most likely to happen in case of massive (batch) requests of same operation, because most of data will be in the same page.
Well, solution may be found in 2 little cute hints: WITH NOLOCK (for selects) and WITH ROWLOCK (for updates and deletes). With those hints you will "ask" sql server no to make any locks during selects and to lock only single row you wish to update. In short, that's it. Be careful when you are using these hints especially if your application is sensitive on data accuracy.

For further reading:
SQL Server Lock Contention Tamed: The Joys Of NOLOCK and ROWLOCK
Michael Balloni
sql-server-perfomrance.com

Do you feal dirty?
Phil Scott's blog

No comments: