Database Locks - Row-Level, Table-Level, Optimistic vs Pessimistic - Watch the Algorithm Execute, Step by Step
Watching this step-by-step visualization helps you understand the dynamic behavior of database locks and their interactions, which is difficult to grasp from static code or text alone.
Step 1/10
·Active fill★Answer cell
setup
leaf
Starting with an empty lock tree representing no locks held.
insertKey: 101
101
leaf
Acquired row-level lock on row 101 by inserting key 101.
insertKey: 102
101102
leaf
Acquired row-level lock on row 102 by inserting key 102.
splitKey: 103↑ promoted: 102
102
101
leaf
103
leaf
Leaf node split after inserting key 103; promoted key 102 to root.
insertKey: TABLE_LOCK
TABLE_LOCK
leaf
Escalated locks to table-level by inserting 'TABLE_LOCK' key.
compareKey: 104
TABLE_LOCK
leaf
Checked for optimistic lock on row 104; no conflict found.
compareKey: 105
TABLE_LOCK
leaf
Optimistic lock on row 105 failed due to existing table-level lock.
insertKey: 105
TABLE_LOCK105
leaf
Acquired pessimistic lock on row 105 by inserting key 105.
deleteKey: 101
TABLE_LOCK105
leaf
Released row-level lock on row 101 by deleting key 101.
traverse
TABLE_LOCK105
leaf
Final lock tree state showing table-level lock and pessimistic lock on row 105.
Key Takeaways
✓ Lock escalation from row-level to table-level reduces overhead by consolidating many locks into one.
This is hard to see from code alone because the dynamic restructuring of locks is abstracted away.
✓ Optimistic locking attempts to avoid blocking by checking conflicts before acquiring locks.
Visualizing the conflict detection step clarifies why optimistic locking can fail and fallback is needed.
✓ Pessimistic locking guarantees exclusive access by blocking conflicting transactions, represented as keys in the tree.
Seeing the lock keys inserted and removed helps understand how locks control concurrency.
Practice
(1/5)
1. You have a large table frequently queried by range conditions on a date column and occasionally updated. Which indexing strategy is most appropriate to optimize query performance?
easy
A. Use a clustered index on the date column to store rows physically sorted by date.
B. Use a non-clustered index on the date column to avoid physical reordering on updates.
C. Use no index and rely on full table scans since updates are frequent.
D. Use a clustered index on a unique ID column and a non-clustered index on the date column.
Solution
Step 1: Understand query pattern for range scans on date
Range queries on the date column benefit from data physically sorted by date, enabling efficient range scans.
Step 2: Consider clustered index effect on physical ordering
A clustered index stores rows physically ordered by the indexed column, making range queries faster.
Step 3: Evaluate update impact tradeoff
Although updates cause some overhead due to physical reordering, occasional updates are an acceptable tradeoff for query speed.
Step 4: Analyze other options
Non-clustered index avoids physical reordering but range queries require extra lookups; no index leads to slow scans; clustered on unique ID doesn't optimize date range queries.
Final Answer:
Option A -> Option A
Quick Check:
Range queries -> clustered index on date column [OK]
Hint: Range queries -> clustered index on that column [OK]
Common Mistakes:
Assuming non-clustered index always better for updates
Ignoring physical data order benefits for range queries
Believing no index is better if updates exist
2. Given the following Python code simulating a JOIN to find customers with orders, what is the output of the print statement?
easy
A. ['Alice', 'Bob', 'Charlie']
B. ['Bob', 'Charlie']
C. ['Alice']
D. ['Alice', 'Bob']
Solution
Step 1: Trace order_customer_ids set
Extract customer IDs from orders: {1, 2}.
Step 2: Filter customers by IDs in order_customer_ids
Customers with id 1 and 2 are Alice and Bob; Charlie (id 3) is excluded.
Final Answer:
Option D -> Option D
Quick Check:
Only Alice and Bob have orders, matching output [OK]
Hint: Set membership filters customers with orders correctly [OK]
Common Mistakes:
Including customers without orders
Off-by-one errors in filtering
Confusing customer IDs with order IDs
3. Which of the following statements about the trade-offs of clustered indexes is TRUE?
medium
A. Clustered indexes always improve insert performance because data is stored sequentially.
B. Clustered indexes can degrade update performance if the indexed column changes frequently due to physical row movement.
C. Clustered indexes reduce storage space because they eliminate the need for separate index structures.
D. Clustered indexes are ideal for columns with high cardinality and random access patterns.
Solution
Step 1: Analyze insert performance claim
Clustered indexes may slow inserts if rows must be inserted in the middle, causing page splits.
Step 2: Evaluate storage space claim
Clustered indexes do not eliminate index structures; non-clustered indexes still exist and clustered index is part of data storage.
Step 3: Understand update impact
Updating clustered index key causes physical row movement, which can degrade performance.
Step 4: Assess suitability for high cardinality random access
Clustered indexes are less beneficial for random access on high cardinality columns; non-clustered indexes often better.
Final Answer:
Option B -> Option B
Quick Check:
Frequent updates on clustered key -> performance hit due to physical row moves [OK]
Hint: Clustered index updates on key -> physical row moves -> slower updates [OK]
Common Mistakes:
Assuming clustered indexes always speed inserts
Believing clustered indexes save storage by removing indexes
Thinking clustered indexes are best for random access on high cardinality columns
4. What is the time complexity of using a correlated subquery with EXISTS to find all customers who have orders, assuming n customers and m orders?
medium
A. O(n * m) because for each customer the orders table is scanned
B. O(n + m) because each table is scanned once
C. O(m) because only orders are scanned
D. O(n log m) because of index lookups on orders
Solution
Step 1: Understand correlated subquery execution
For each of the n customers, the subquery scans orders (m rows) to check existence.
Step 2: Calculate total complexity
This leads to O(n * m) time complexity, as the orders table is scanned repeatedly.
Final Answer:
Option A -> Option A
Quick Check:
Repeated scans cause multiplicative complexity [OK]
Hint: Correlated subqueries scan inner table per outer row [OK]
Common Mistakes:
Assuming single scan of orders
Confusing correlated with non-correlated subqueries
Ignoring repeated scans in correlated subqueries
5. What is a common trade-off or limitation of using strict Two-Phase Locking (2PL) in high-concurrency database systems?
medium
A. Strict 2PL can cause increased waiting and deadlocks, reducing concurrency
B. Strict 2PL eliminates deadlocks entirely, improving throughput
C. Strict 2PL allows transactions to release locks early, improving performance
D. Strict 2PL requires no lock compatibility checks, simplifying implementation
Solution
Step 1: Understand strict 2PL behavior
Strict 2PL holds exclusive locks until commit, which can increase waiting times.
Step 2: Analyze deadlock potential
Because locks are held longer, deadlocks can occur more frequently, reducing concurrency.
Step 3: Evaluate options
B is incorrect; strict 2PL does not eliminate deadlocks. C is incorrect; locks are not released early. D is wrong; lock compatibility checks are essential. A correctly identifies the trade-off.
Final Answer:
Option A -> Option A
Quick Check:
Strict 2PL trades off concurrency for serializability, increasing deadlock risk.
Hint: Strict 2PL trades concurrency for serializability, risking deadlocks [OK]
Common Mistakes:
Believing strict 2PL prevents deadlocks
Thinking locks can be released early in strict 2PL
Ignoring lock compatibility checks
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.