SET TRANSACTION ISOLATION LEVEL

This statement is used to set the isolation level for either a connection or a stored procedure. The most typical use I’ve seen is at the top of a stored procedure in order to avoid locking and deadlocks. This is a cleaner alternative to using WITH (NOLOCK) hints on tables. If you set the isolation level within a procedure, the isolation level will revert to its previous level once the procedure finishes.

The syntax is:

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;

The available options are:

  • READ UNCOMMITTED – Allows dirty reads, meaning data can be read from a transaction that is not yet complete.
  • READ COMMITTED – Only reads data from transactions that have already been committed.  Current transactions must wait for transactions referencing common resources to finish.
  • REPEATABLE READ – Data that is being read is exclusively locked until the transaction completes.
  • SNAPSHOT – The default for Oracle.  This level allows all data to be read without using locks by maintaining a snapshot of all the data being modified in “versioning” tables.  This is the only isolation level not lock based.
  • SERIALIZABLE – Data that is being read is exclusive locked and inserts are prevented within this range until the transaction completes.
Snapshot isolation is not available unless enabled at the database level. It’s recommended to know all implications prior to enabling.

Example

This statement needs to be placed before the transactions who isolation you want to modify.

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;

SELECT
  firstname
 ,salary
FROM dbo.employee e
JOIN salary s
ON s.employeeid = s.employeeid;

The comparable method using hints would be:

SELECT
  firstname
 ,salary
FROM dbo.employee e WITH (nolock)
JOIN salary s WITH (nolock)
ON s.employeeid = s.employeeid;

3 comments
Bpaul 26 Sep 2013 at 1:31 pm

Does the isolation level apply to subqueries too?

For example

select
name,
dob,
salary = (select sum(salary) + sum(allowances) from emp where emp_id = @emp_id)
from emp_base
where emp_id = @emp_id

Derek Dieter 29 Sep 2013 at 4:41 pm

Yes it does Bpaul

Pradeepa 06 May 2013 at 10:21 am

Really good explanation………..!

Featured Articles

 Site Author