Specifying isolation levels in SQL statements

You can override the isolation level that an application plan or package is bound with for specific SQL statements.

Procedure

Begin program-specific programming interface information.To override the isolation level for a specific SQL statement:

  • Issue the SQL statements, and include a WITH isolation level clause.
    The WITH isolation level clause:
    • Can be used on these statements:
      • SELECT
      • SELECT INTO
      • Searched DELETE
      • INSERT from fullselect
      • Searched UPDATE
    • Cannot be used on subqueries.
    • Can specify the isolation levels that specifically apply to its statement. (For example, because WITH UR applies only to read-only operations, you cannot use it on an INSERT statement.)
    • Overrides the isolation level for the plan or package only for the statement in which it appears.
    The following statement finds the maximum, minimum, and average bonus in the sample employee table.
    SELECT MAX(BONUS), MIN(BONUS), AVG(BONUS)
      INTO :MAX, :MIN, :AVG
      FROM DSN8C10.EMP
         WITH UR;
    The statement is executed with uncommitted read isolation, regardless of the value of ISOLATION with which the plan or package containing the statement is bound.
  • If you use the WITH RR or WITH RS clause, you can issue SELECT and SELECT INTO statements, and specify the following options:
    • USE AND KEEP EXCLUSIVE LOCKS
    • USE AND KEEP UPDATE LOCKS
    • USE AND KEEP SHARE LOCKS
    To use these options, specify them as shown in the following example:
    SELECT ...
     WITH RS USE AND KEEP UPDATE LOCKS;

Results

By using one of these options, you tell Db2 to acquire and hold a specific mode of lock on all the qualified pages or rows. The following table shows which mode of lock is held on rows or pages when you specify the SELECT using the WITH RS or WITH RR isolation clause.
Table 1. Which mode of lock is held on rows or pages when you specify the SELECT using the WITH RS or WITH RR isolation clause
Option Value Lock Mode
USE AND KEEP EXCLUSIVE LOCKS X
USE AND KEEP UPDATE LOCKS U
USE AND KEEP SHARE LOCKS S

With read stability (RS) isolation, a row or page that is rejected during stage 2 processing might still have a lock held on it, even though it is not returned to the application.

With repeatable read (RR) isolation, Db2 acquires locks on all pages or rows that fall within the range of the selection expression.

All locks are held until the application commits. Although this option can reduce concurrency, it can prevent some types of deadlocks and can better serialize access to data.End program-specific programming interface information.