In a real-world enterprise database (like Amazon or Netflix), millions of transactions are executing simultaneously. If the DBMS executed these transactions serially (one after another), performance would be unacceptably slow. The DBMS must interleave the operations of multiple transactions—this is called Concurrency.
However, unmanaged concurrency leads to severe data anomalies. Concurrency Control is the mechanism the DBMS uses to ensure that concurrent transactions produce the same results as if they were executed sequentially.
If concurrency is not controlled, three major problems can occur:
Occurs when two transactions read the same data, then both update it. The second update permanently overwrites the first one.
T1 and T2 both read balance = 100. T1 adds $50 and writes 150. A millisecond later, T2 subtracts $20 from its original read and writes 80. T1's deposit is completely lost.Occurs when a transaction reads data that has been updated by another uncommitted transaction. If the other transaction rolls back, the first transaction has read data that "never officially existed".
Occurs when a transaction reads the same row twice during its execution, and gets different data each time because another transaction updated the row in between the reads.
To solve these problems, the DBMS uses Locks. A transaction must acquire a lock on a data item before it can access it.
The use of locks introduces a new problem: Deadlock.
Suppose transaction T1 holds an Exclusive Lock on row A and requests a lock on row B.
Simultaneously, transaction T2 holds an Exclusive Lock on row B and requests a lock on row A.
Neither transaction can proceed. They will wait for each other infinitely. To solve this, the DBMS runs a Deadlock Detection algorithm in the background. If it detects a cycle, it automatically aborts and rolls back one of the transactions (the "victim"), releasing its locks and allowing the other to proceed.
SQL allows developers to choose exactly how strict the concurrency control should be for a specific transaction, trading off consistency for performance.