DB2advanced

Locking, Isolation Levels, and Deadlocks

Understand DB2's locking model, the practical effect of each isolation level, and how deadlocks arise and get resolved.

DB2 locking is where relational database theory meets very concrete production pain — deadlocks, timeouts, and lock contention are recurring real-world incidents, and interviewers use this topic to check whether a candidate understands not just the vocabulary (isolation levels) but the actual behavioral tradeoffs each choice makes under concurrent load.

Isolation levels are how tightly you reserve a shared meeting room: Uncommitted Read is walking in without knocking and reading whatever's currently on the whiteboard, even mid-erase; Repeatable Read is locking the whole room for your entire meeting so nobody else can touch anything until you leave; Cursor Stability is holding the door only while you're actually looking at one specific note. A deadlock is two people each holding a door the other needs open, until security (DB2's lock manager) steps in and asks one of them to leave.

Key Concepts

1
DB2's isolation levels — Repeatable Read (RR), Read Stability (RS), Cursor Stability (CS), and Uncommitted Read (UR) — control how much a transaction's own locking protects it from seeing or being affected by concurrent changes from other transactions. CS, the most common default, holds a lock on a row only while positioned on it, releasing it once the cursor moves off, striking a practical balance between consistency and concurrency; UR reads without acquiring locks at all (and without being blocked by others' locks), trading consistency (you might read uncommitted, later-rolled-back data — a 'dirty read') for maximum concurrency, useful for reporting queries that can tolerate slight inaccuracy.
2
A deadlock occurs when two transactions each hold a lock the other needs, forming a circular wait — DB2's deadlock detection periodically scans for these cycles and resolves them by choosing a victim transaction to roll back (returning a specific negative SQLCODE, commonly -911 or -913), letting the other proceed. Understanding that deadlocks are a normal, expected occasional occurrence in busy concurrent systems — not a bug in DB2 itself — and that application code should be designed to detect and retry on that specific SQLCODE, is a key production-readiness insight.
3
A strong interview answer distinguishes a timeout (one transaction simply waited too long for a lock, SQLCODE -911/-913 as well but for a different underlying reason — IRLM's timeout threshold rather than a genuine cycle) from a true deadlock, and can discuss practical mitigation: consistent access ordering across transactions (always touching tables/rows in the same sequence) substantially reduces deadlock likelihood by preventing the circular-wait pattern from forming in the first place.