Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to force row level locking in SQL Server?

I can see how to turn off row level and page level locking in SQL Server, but I cannot find a way to force SQL Server to use row level locking. Is there a way to force SQL Server to use row level locking and NOT use page level locking?

like image 846
Elan Avatar asked Jun 25 '10 00:06

Elan


People also ask

How do I restrict rows in SQL?

If you don't need to omit any rows, you can use SQL Server's TOP clause to limit the rows returned. It is placed immediately after SELECT. The TOP keyword is followed by integer indicating the number of rows to return. In our example, we ordered by price and then limited the returned rows to 3.

Is row exclusive lock mode available in SQL?

ROW EXCLUSIVE is the same as ROW SHARE , but it also prohibits locking in SHARE mode. ROW EXCLUSIVE locks are automatically obtained when updating, inserting, or deleting. See ROW SHARE . SHARE permits concurrent queries but prohibits updates to the locked table.

Why is row-level locking is better than table level locking?

Row-level locking systems can lock entire tables if the WHERE clause of a statement cannot use an index. For example, UPDATES that cannot use an index lock the entire table. Row-level locking systems can lock entire tables if a high number of single-row locks would be less efficient than a single table-level lock.


1 Answers

You can use the ROWLOCK hint, but AFAIK SQL may decide to escalate it if it runs low on resources

From the doco:

ROWLOCK Specifies that row locks are taken when page or table locks are ordinarily taken. When specified in transactions operating at the SNAPSHOT isolation level, row locks are not taken unless ROWLOCK is combined with other table hints that require locks, such as UPDLOCK and HOLDLOCK.

and

Lock hints ROWLOCK, UPDLOCK, AND XLOCK that acquire row-level locks may place locks on index keys rather than the actual data rows. For example, if a table has a nonclustered index, and a SELECT statement using a lock hint is handled by a covering index, a lock is acquired on the index key in the covering index rather than on the data row in the base table.

And finally this gives a pretty in-depth explanation about lock escalation in SQL Server 2005 which was changed in SQL Server 2008.

There is also, the very in depth: Locking in The Database Engine (in books online)

So, in general

UPDATE Employees WITH (ROWLOCK) SET Name='Mr Bean' WHERE Age>93 

Should be ok, but depending on the indexes and load on the server it may end up escalating to a page lock.

like image 92
Sam Saffron Avatar answered Sep 20 '22 02:09

Sam Saffron