Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would this SELECT statement lock up on SQL Server?

I have a simple query like this

SELECT * FROM MY_TABLE;

When I run it, SQL Server Management Studio hangs.

Other tables and views are working fine.

What can cause this? I've had locks while running UPDATE statements before, and I know how to approach those. But what could cause a SELECT to lock?

I have run the "All Blocking Transactions" report, and it says there are none.

like image 853
JosephStyons Avatar asked Nov 18 '09 13:11

JosephStyons


People also ask

Does SQL Server lock on SELECT?

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 .

Does SELECT query lock?

SELECT statements get a shared lock on the entire table. Other statements get exclusive locks on the entire table, which are released when the transaction commits. SELECT statements get shared locks on a range of rows. UPDATE and DELETE statements get exclusive locks on a range of rows.

What causes SQL locks?

Transaction locks are the most common cause of blocked processes. The stronger (least concurrent) the isolation level, the more likely it is to cause a blocked process. Try to use less granular lock for your queries, as the less granular the lock, the more likely a blocked process or deadlock will not occur.


1 Answers

It is probably not the select that is locking up, but some other process that is editing (udpate/delete/insert) the table that is causing the locks.

You can view which process is blocking by runing exec sp_who2 on your SQL Server.

Alternatively, if you are OK with dirty reads, you can do one of two things

SELECT * FROM Table WITH (NOLOCK)

OR

SET Transaction Isolation Level Read Uncommitted
SELECT * FROM Table 
like image 110
Raj More Avatar answered Oct 28 '22 15:10

Raj More