- Learn
- Computer Science & IT
- Programming
- Database Design and Advanced SQL
- SQL Transactions and Concurrency Control
SQL Transactions and Concurrency Control: ACID and Locks
IntermediateLesson 6 of 8 in Database Design and Advanced SQL Course
What you will learn
- Explain what the ACID properties guarantee and use transaction control statements so that a group of changes takes effect completely or not at all, even when a statement fails.
- Explain what a transaction is and what ACID guaranteesDefine a transaction as one logical unit of work and describe atomicity, consistency, isolation and durability with a money transfer between two accounts.
- Start, commit and roll back transactions in SQLUse START TRANSACTION or BEGIN, COMMIT and ROLLBACK, understand autocommit mode, and predict which changes a sequence of statements leaves in the database.
- Use savepoints and handle failed transactions in application codeUndo part of a transaction with savepoints, write the commit-or-rollback pattern in application code, and retry transactions that the database aborts because of concurrency.
- Explain what a transaction is and what ACID guarantees
- Analyze interleaved transactions, name the anomalies they can cause, and choose the isolation level that prevents the ones that matter for an application.
- Test schedules for serializabilityModel concurrent transactions as schedules, find conflicting operations, use a precedence graph to decide whether a schedule is conflict serializable, and check separately whether it is recoverable.
- Recognize dirty reads, phantoms and other anomaliesDescribe dirty writes, dirty reads, nonrepeatable reads, phantoms, lost updates, read skew and write skew, each with a concrete two-transaction timeline.
- Choose and set transaction isolation levelsMap the SQL standard isolation levels to the anomalies they prevent, set a level in SQL, and choose one by weighing correctness against concurrency in a real product.
- Test schedules for serializability
- Explain how shared and exclusive locks and two-phase locking produce serializable schedules, use explicit locking in SQL to keep check-then-write logic correct, and detect, prevent and recover from deadlocks.
- Explain shared and exclusive locks and two-phase lockingUse the lock compatibility rules and the two phases of two-phase locking to show how a lock-based database keeps concurrent schedules serializable.
- Lock rows explicitly and prevent lost updates and phantomsKeep read-then-write logic correct with atomic updates, SELECT … FOR UPDATE, version checks and range or parent-row locks.
- Detect, prevent and recover from deadlocksRecognize a deadlock in a wait-for graph, explain how databases detect it or prevent it, and write transactions that avoid deadlocks and survive them.
- Explain shared and exclusive locks and two-phase locking
- Explain how keeping several versions of each row lets readers and writers work without blocking each other, what snapshot isolation does and does not prevent, and how serializable alternatives close the remaining gaps.
- Explain how MVCC keeps row versions and snapshotsFollow how a multiversion database creates row versions, decides which version each transaction sees, and cleans up versions nobody needs.
- Explain snapshot isolation, write skew and serializable alternativesExplain how snapshot isolation handles write conflicts and why it still allows write skew, and how serializable snapshot isolation, optimistic validation and timestamp ordering produce serializable results.
- Explain how MVCC keeps row versions and snapshots
- Explain how a write-ahead log records every change so that a database can undo unfinished transactions and redo committed ones after a crash, and how backups and archived logs restore data after a disk failure.
- Explain failures, the log and write-ahead loggingName the kinds of failure a database must survive, read the records of a transaction log, and explain the write-ahead logging rules that make commits durable.
- Recover a database after a crash or a disk failureCarry out redo and undo from a log with a checkpoint, describe the three ARIES phases, and restore a database from a backup and archived log.
- Explain failures, the log and write-ahead logging
SQL Transactions and Concurrency Control study guide
1Group SQL statements into reliable transactions
An order, transfer or reservation often needs several SQL statements to succeed together. Transaction boundaries give those statements one outcome, while constraints and concurrency control preserve the rules around them. Follow the four ACID properties, practice commit and rollback, then use savepoints and application error handling to recover safely when part of the work fails or a reply is lost.
1.1 Transactions and the four ACID properties
A transaction groups database operations into one logical unit of work. A transfer needs a debit and a credit. If only the debit becomes permanent, the database has kept a statement but lost the meaning of the operation.
Follow a transfer
Account A starts at 500.00 and B at 300.00. Moving 200.00 produces these changes:
UPDATE accounts SET balance = balance - 200.00 WHERE id = 'A';
UPDATE accounts SET balance = balance + 200.00 WHERE id = 'B';
The starting total is 800.00. After both statements, A is 300.00 and B is 500.00, still totaling 800.00. Between the statements, the transaction's own working state has 300.00 in each account. Grouping the statements tells the database that this temporary state must never become the permanent result.
Identify the guarantee
| Property | What it guarantees | What the transfer needs |
|---|---|---|
| Atomicity | All changes take effect together, or none do. | A failure after the debit must cancel it. |
| Consistency | A correct transaction preserves the database's rules. | The total stays 800.00 and constraints hold. |
| Isolation | Full isolation gives an outcome equivalent to a serial order. | Concurrent work cannot produce an impossible combination. |
| Durability | A confirmed commit survives a later system crash. | The completed transfer remains after restart. |
Atomicity concerns failure within the unit of work. If the server crashes after subtracting 200.00, recovery must leave the original balances, unless the whole transfer committed. Undo/redo systems restore old values from recovery information. PostgreSQL handles aborted changes by keeping their row versions invisible through transaction status, then cleaning them up later.
Consistency shares responsibility with the application. A CHECK (balance >= 0) can reject a negative balance. A foreign key can reject an unknown account. Neither proves that the application credited the intended recipient or preserved the sum of balances. Those business rules need correct transaction logic, plus suitable concurrency control when several transactions can affect them.
Isolation controls the outcome of overlapping work. Serializable execution has the same effect as some order in which transactions run one at a time. The server can still interleave their operations. Weaker isolation levels permit some anomalies; at READ COMMITTED or stronger, another transaction cannot read the transfer's uncommitted debit. Depending on the implementation, it reads an older committed version or waits.
Durability depends on persistent recovery information. Before confirming a normal durable commit, the database flushes the required log records to nonvolatile storage. The changed table pages can be written later because recovery can reconstruct them.
Connect correctness to concurrency
Concurrency improves throughput: while one transaction waits for storage, another can use the processor. Short requests can finish without waiting for an entire long report. Locks and row versions control which overlapping operations can proceed.
Durability protects against a system crash with surviving storage. A destroyed storage device still needs a backup or another surviving copy. Also keep the meaning of consistency straight: the C in ACID concerns integrity rules; the consistency discussed in replicated-system models such as CAP concerns what different readers observe.
Key Takeaways
- Atomicity makes one logical unit of work all or nothing.
- Consistency depends on declared constraints and correct application logic.
- Serializability permits interleaving while preserving a serial outcome.
- Durability requires persistent recovery information before commit is confirmed.
- Concurrency raises throughput but needs control to preserve correctness.
1.2 Commit, rollback and transaction boundaries
With autocommit, each successful statement commits as its own transaction. On transactional tables, one UPDATE affecting 1,000 rows is atomic. Two separate autocommitted updates are two units of work: a crash between them can leave a transfer incomplete.
Put the boundary around the whole job
START TRANSACTION;
UPDATE accounts SET balance = balance - 200.00 WHERE id = 'A';
UPDATE accounts SET balance = balance + 200.00 WHERE id = 'B';
COMMIT;
START TRANSACTION works in PostgreSQL and MySQL. PostgreSQL, MySQL and SQLite accept BEGIN; SQL Server and SQLite accept BEGIN TRANSACTION. Oracle starts a transaction implicitly when transactional work begins. All use COMMIT and ROLLBACK to finish it. A driver can manage these boundaries too, so check its autocommit setting instead of assuming it matches an interactive SQL console.
The current session sees its own changes before commit. Another transaction at READ COMMITTED or stronger reads committed data or waits. After commit, a newly acquired snapshot includes the transfer; an older transaction-wide snapshot continues to show the earlier balances.
Handle a failed statement
Suppose stock contains 2 lamps and requires qty >= 0. An order for 3 lamps first inserts order 101, then tries to subtract 3 from stock. The second statement fails its constraint. The application must cancel the order too:
ROLLBACK;
The order disappears and stock remains 2. Merely receiving an error does not give identical behavior across products.
| Product or setting | Effect of a typical statement error inside a transaction |
|---|---|
| PostgreSQL | Leaves the transaction aborted until rollback, or recovery to an earlier savepoint. A commit in the aborted state rolls back. |
| MySQL and SQL Server default behavior | Many errors undo the failing statement while earlier work remains pending. |
SQL Server with SET XACT_ABORT ON | Runtime errors roll back the transaction; the application still needs proper error handling. |
Commit only after the whole operation succeeds. Otherwise a product that leaves the transaction open could keep order 101 without reserving its stock.
Recognize boundaries outside the obvious pair
In MySQL and Oracle, statements such as CREATE TABLE, ALTER TABLE and DROP TABLE cause implicit commits and are not ordinary rollbackable work. PostgreSQL and SQL Server can roll back most table definition changes inside a transaction. Mixing schema changes with a business transaction can therefore change its boundaries across products.
A transaction is active while statements run, partially committed after its final operation while commit is becoming durable, and committed once the commit is durable. Failure moves it toward aborted, when its changes have been rolled back. A lost connection causes the server to roll back work still uncommitted when it detects the disconnect. A connection lost during commit leaves the client unsure whether commit already happened.
ROLLBACK cannot reverse a completed commit. Reversing a committed transfer needs a new compensating transaction, such as transferring the amount back. It also cannot recall an email already sent outside the database.
Keep the transaction open only while doing its database work. Waiting for user input holds locks and can retain old versions, making unrelated requests wait and cleanup fall behind.
Key Takeaways
- Autocommit gives each successful statement its own transaction.
- Put every dependent change inside the same explicit transaction.
- Roll back after an unhandled error; error behavior differs by product.
- Implicit commits can split a transaction containing schema changes.
- A committed change needs a new compensating transaction to reverse it.
- Keep transactions short and finish them explicitly.
1.3 Savepoints and safe application retries
A savepoint marks a position inside an open transaction. It lets the application discard a deliberately handled portion while keeping earlier work pending. It does not create a separate committed transaction.
Recover a local failure
The customers table has a unique email constraint:
START TRANSACTION;
INSERT INTO customers (id, email) VALUES (1, 'ana@example.com');
SAVEPOINT before_second;
INSERT INTO customers (id, email) VALUES (2, 'ana@example.com');
-- The duplicate email fails.
ROLLBACK TO SAVEPOINT before_second;
INSERT INTO customers (id, email) VALUES (3, 'li@example.com');
COMMIT;
The first insertion remains pending when the second fails. Rolling back to before_second clears the failed portion, so customer 3 can be inserted. Commit keeps customers 1 and 3. In PostgreSQL, the savepoint is also what allows the transaction to recover from the error without abandoning all earlier work.
RELEASE SAVEPOINT before_second removes the marker while retaining the changes. A full ROLLBACK discards all changes, including those before the marker. At READ COMMITTED or stronger, other transactions still cannot read pending changes just because a savepoint exists. SQL Server uses SAVE TRANSACTION name and ROLLBACK TRANSACTION name for the corresponding marker and partial rollback.
Decide whether another attempt can help
Use a commit-or-rollback pattern around application work:
repeat up to 3 attempts:
begin transaction
try:
read current data and perform the changes
commit
return success
on serialization failure or deadlock:
roll back any remaining transaction
wait briefly before another attempt
on other error:
roll back
report the error and stop
report that the retry limit was reached
A serialization failure or deadlock can disappear when concurrent work finishes. A duplicate key caused by submitting the same invalid data will fail again unchanged. Useful signals include SQLSTATE 40001 for serialization failure and PostgreSQL 40P01 for deadlock; MySQL reports deadlock error 1213 and SQL Server error 1205.
A retry begins at the transaction's first statement and reads the data again. Retrying only a failed update can reuse a decision based on values the database has already rejected as unsafe. The new attempt is a new transaction with current information.
Make a repeated request safe
An email or payment sent during the failed attempt may already have happened. Keep external side effects until after commit, or make them idempotent with a unique request identifier so repeating a request cannot repeat its effect. Deferring an effect avoids sending it for rolled-back work; the receiving service still needs duplicate protection if delivery itself may be retried.
A disconnect during COMMIT creates a different problem: the server might have committed before the reply was lost. Store the request identifier with the business change under a UNIQUE constraint. On reconnect, check for it before repeating the operation. The identifier makes a previous success recognizable; a blind retry could otherwise create a second order.
Key Takeaways
- A savepoint supports partial rollback and commits nothing.
- Retry transient concurrency failures from the beginning with fresh reads.
- Roll back before retrying, including work a product leaves open.
- Use unique request identifiers to recognize completed work after an uncertain commit.
2Recognize concurrency problems and choose an isolation level
Concurrent transactions can each run valid SQL and still combine their decisions into an invalid result. Operation timelines make the dependencies visible: who read which value, who changed it, and who committed first. Use schedules and graphs to test serial order, distinguish the main anomalies, then match an isolation level to the rule and to the behavior of the database product running it.
2.1 Schedules, conflicts and serial orders
A schedule lists operations in execution order, preserving each transaction's own order. R1(A) means T1 reads A, W1(A) means T1 writes A, and C1 means T1 commits. A serial schedule finishes one transaction before starting the next; three transactions have six possible serial orders.
Find the dependencies
Two operations conflict if they come from different transactions, access the same item and include at least one write. Read–write, write–read and write–write pairs qualify. Two reads do not. A precedence graph records which transaction must come before another if those conflicts are to keep their order.
- Draw one node per transaction.
- For each conflicting pair, draw an edge from the transaction acting first to the one acting later.
- Look for a cycle. No cycle means the schedule is conflict serializable.
- Read a serial order that follows every edge. Several orders may work when some transactions are independent.
Swapping adjacent nonconflicting operations leaves behavior unchanged. An acyclic graph means these swaps can turn the schedule into a serial one. A cycle demands contradictory orders.
Compare two interleavings
Start with A = 100 and B = 100. T1 transfers 50 from A to B. T2 adds 10% interest to each account. Serial T1 then T2 produces A = 55 and B = 165; serial T2 then T1 produces A = 60 and B = 160. Both totals are 220.
R1(A) W1(A) R2(A) W2(A) R1(B) W1(B) R2(B) W2(B)
T1's conflicting operations precede T2's on both A and B. The graph has only T1 → T2. The schedule interleaves operations but matches serial T1 then T2, ending at 55 and 165.
Now change the order on B:
R1(A) W1(A) R2(A) W2(A) R2(B) W2(B) R1(B) W1(B)
A gives T1 → T2, while B gives T2 → T1. Computing the changes gives A = 55 and B = 160, totaling 215. This result matches neither serial order. The cycle identifies the conflicting requirements before any arithmetic is needed.
Check commit order separately
Recoverability asks about a transaction that reads another transaction's write. If T2 reads T1's value, T2 must not commit before T1 commits. Otherwise T1 could abort after T2 has permanently used data that never committed. A precedence graph alone does not answer this question.
A cascadeless schedule goes further: reads use only committed values, so an abort cannot force readers of that value to abort too. Strict two-phase locking provides this protection, as does MVCC when its readers see only committed versions. The schedule W1(A) R2(A) C1 C2 is recoverable but still permits a dirty read; it is not cascadeless.
Conflict serializability is a sufficient single-version test, not the widest definition of serializability. Some schedules with blind writes fail this test yet are view serializable; checking view serializability in general is NP-complete. Multiversion methods also reason about which version a read observes. In a precedence graph, draw edges for conflicting pairs, never simply because two operations are next to each other.
Key Takeaways
- A conflict requires different transactions, the same item and at least one write.
- An acyclic precedence graph proves conflict serializability.
- An interleaved schedule can still have a serial outcome.
- Recoverability depends on read dependencies and commit order.
- Cascadeless schedules allow reads only from committed work.
2.2 Recognize what went wrong in a timeline
A concurrency problem becomes easier to diagnose when you write down who read, who wrote and when each transaction committed. Similar-looking outcomes can need different protections.
Uncommitted work crosses a boundary
A dirty write overwrites another transaction's uncommitted write. Undoing the earlier transaction could then erase the later transaction's work. Mainstream transactional engines prevent this by holding write locks until the writing transaction ends.
A dirty read reads another transaction's uncommitted value. T2 changes item 7's price from 40.00 to 4.00. T1 invoices at 4.00 before T2 rolls back. The invoice used a value that never committed. The key detail is the missing commit before the read, not whether the number seems reasonable.
A later read sees different committed data
| Phenomenon | Timeline | What changes |
|---|---|---|
| Nonrepeatable read | T1 reads balance 500.00; T2 withdraws 100.00 and commits; T1 rereads 400.00. | An existing row's value or existence. |
| Phantom | T1 counts 29 enrollments; T2 adds a matching enrollment and commits; T1 recounts 30. | The set matching a search condition. |
| Read skew | T1 reads A = 500.00; T2 transfers 200.00 to B and commits; T1 reads B = 500.00. | Related reads come from different committed states. |
For read skew, the valid balances total 800.00 before and after the transfer. T1 reports 1,000.00 because it combines the old A with the new B. Each value was committed, so avoiding dirty reads did not prevent the error.
A phantom can come from an insert, a delete or an update that moves a row into or out of the matching set. Locking every row returned by a query may still leave space for a new matching row.
Two writers make incompatible decisions
A lost update happens when one computed replacement overwrites another. Stock starts at 10. T1 and T2 both read 10. T1 subtracts 3 and writes 7; T2 subtracts 4 from its old reading and writes 6. Both commit, so T1's reduction is lost. Applying both orders should leave 3. This pattern commonly comes from reading in the application and later writing a literal replacement value.
Write skew involves different written rows. A shift needs at least one doctor on call. Alice and Bob are both on call. T1 sees two and takes Alice off; T2 also sees two and takes Bob off. Each change is valid against its own view, but together they leave nobody available. Neither overwrites the other's row, so same-row write conflict detection misses the shared rule.
Match the name to the evidence
Ask whether a read used uncommitted work, whether a later read changed, or whether two decisions based on overlapping reads broke a rule. A lost update destroys a change on the same row; write skew preserves both writes but breaks a rule across rows. A successful single-user test proves little about either pattern because the harmful order needs overlap. Weaker isolation levels permit particular phenomena as part of their contract; the application must choose protection that matches its rule.
Key Takeaways
- A dirty read uses uncommitted data; a dirty write overwrites it.
- Nonrepeatable reads change a row observation; phantoms change a query result set.
- Read skew combines committed values from different states.
- A lost update overwrites another computed change to the same row.
- Write skew can break a shared rule while updating different rows.
- Row locks alone may leave gaps where matching rows can appear.
2.3 Choose isolation by the rule you must protect
An isolation level states what concurrent transactions may observe. Choose it from the business rule and the database's actual behavior. The level name alone can hide important differences.
Read the standard's minimum guarantees
| Level | Dirty reads | Nonrepeatable reads | Phantoms |
|---|---|---|---|
| READ UNCOMMITTED | Possible | Possible | Possible |
| READ COMMITTED | Prevented | Possible | Possible |
| REPEATABLE READ | Prevented | Prevented | Possible |
| SERIALIZABLE | Prevented | Prevented | Prevented |
SERIALIZABLE also requires equivalence to a serial execution. Preventing only the three named phenomena does not prove this: snapshot isolation can prevent all three in plain snapshot reads and still allow write skew.
The SQL standard's default is SERIALIZABLE, but PostgreSQL, Oracle and SQL Server default to READ COMMITTED. MySQL InnoDB defaults to REPEATABLE READ. SQLite serializes writes, allowing one writer at a time.
Check the implementation
| Product | Important behavior |
|---|---|
| PostgreSQL | READ UNCOMMITTED behaves as READ COMMITTED. REPEATABLE READ uses snapshot isolation and prevents snapshot-read phantoms, but permits write skew. SERIALIZABLE adds dependency checks. |
| MySQL InnoDB | REPEATABLE READ keeps a snapshot for plain reads, but read-then-write replacement code can lose updates. Locking reads use current data. |
| SQL Server | REPEATABLE READ holds read locks. SNAPSHOT uses row versions. READ_COMMITTED_SNAPSHOT enables versioned READ COMMITTED. |
| Oracle | READ COMMITTED is the default; its level named SERIALIZABLE uses snapshot isolation and can allow write skew. |
Set the level at the correct point
In PostgreSQL, choose the level before the transaction's first query:
BEGIN;
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
-- Read the rule's inputs and perform the changes.
COMMIT;
BEGIN ISOLATION LEVEL REPEATABLE READ is another PostgreSQL form. MySQL's unqualified SET TRANSACTION applies to the next transaction; SET SESSION TRANSACTION ISOLATION LEVEL ... changes its session default. SQL Server's isolation setting persists for the connection until changed. Reused connections therefore need deliberate settings.
Fit the guarantee to the job
A dashboard count that may be a little out of date usually suits READ COMMITTED. A report spanning several queries needs one stable view, such as PostgreSQL REPEATABLE READ. An on-call rule checked across rows needs a truly serializable level with retries, or coordinated locking that protects every relevant decision. A debit expressed as one conditional, relative UPDATE can be safe at READ COMMITTED without first reading a replacement value into the application.
Stronger isolation can mean longer lock waits or more serialization failures. The application must budget for retries where conflicts are rejected. READ UNCOMMITTED can expose rolled-back data and, in SQL Server, even miss or double-count rows during scans; speed is useful only when the resulting observations meet the application's needs.
Different operations can use different levels. For a rule protected by PostgreSQL SERIALIZABLE, all transactions that maintain that rule must participate at SERIALIZABLE or use other sufficient coordination. An uncoordinated weaker-level writer can defeat the intended guarantee.
Key Takeaways
- The standard table defines minimum protections, not identical product behavior.
- Only actual serializability rules out write skew as well as read anomalies.
- Choose the level before the protected reads begin.
- Stable multi-query reports need a transaction-wide view.
- Protect every transaction that participates in a shared rule.
3Control concurrency with locks and resolve deadlocks
Locks let a database delay operations that would interfere with one another. Their modes, timing and scope determine whether they protect one row, a multi-row decision or a range of possible results. Work from shared and exclusive locks to two-phase locking, apply atomic updates and explicit locking in SQL, then trace deadlocks so application code can avoid common cycles and recover from victims.
3.1 Lock compatibility and two-phase locking
A lock manager grants a claim on a row, page or table, or makes the requester wait. Shared and exclusive locks describe how transactions coordinate access to the same item.
Decide who must wait
| Requested lock | Another transaction holds S | Another transaction holds X |
|---|---|---|
| Shared (S) | Compatible | Wait |
| Exclusive (X) | Wait | Wait |
Several transactions can hold S together. X excludes both other readers taking S and other writers taking X. A transaction can request an upgrade from S to X, but it must wait for other shared holders to leave.
Protecting only the instant of each read is insufficient for a multi-read rule. A report can lock A, read it, unlock it, then read B after a transfer commits. Every individual access was locked, yet the report combines different states. Lock duration determines the protection.
Separate growing from shrinking
Two-phase locking (2PL) requires a growing phase with acquisitions and no releases, followed by a shrinking phase with releases and no new acquisitions. The final acquisition is the transaction's lock point. The order of lock points gives a serial order for the conflict-serializable schedule.
| Protocol | Extra rule beyond basic 2PL | Result |
|---|---|---|
| Strict 2PL | Hold every exclusive lock until commit or abort. | Prevent dirty reads and cascading rollback. |
| Rigorous 2PL | Hold shared and exclusive locks until the end. | Serialize transactions in commit order. |
To follow a rigorous example, start with A = 500.00 and B = 300.00. T1 takes X(A) and writes 300.00. A report T2 requests S(A) and waits. T1 takes X(B), writes 500.00 and commits, releasing its locks. T2 now reads 300.00 and 500.00 while holding its own S locks and obtains the correct total, 800.00.
Basic 2PL can release an exclusive lock before commit during its shrinking phase. It guarantees conflict serializability, but needs the stricter rule to stop readers depending on uncommitted writes.
Understand the cost and the limits
2PL can deadlock. T1 may hold X(A) and request X(B), while T2 holds X(B) and requests X(A). Both are still growing, so the protocol has not been violated. Likewise, locks on existing rows cannot alone protect a search condition from a newly inserted matching row; range or predicate protection is needed.
Granularity is the size of the locked item. Row locks permit unrelated updates but require many lock records. A table lock is cheaper to track and blocks more work. Intention locks, such as IS and IX on a table, announce locks lower in the hierarchy so the manager can judge whole-table requests without checking every row. Some systems, including SQL Server, can escalate many row locks into a table lock.
The database normally acquires locks automatically. At lock-based READ COMMITTED, ordinary shared read locks can be released as reads finish. Write locks normally last until transaction end; explicit row locks also protect the transaction's later work, with product-specific savepoint rollback rules. Long transactions therefore keep other writers waiting even when no statement is currently running.
Key Takeaways
- S is compatible with S; X conflicts with another transaction's S or X.
- 2PL allows no new acquisition after the first release.
- Strict 2PL holds X locks to the end; rigorous 2PL holds all locks.
- 2PL can deadlock and needs range protection for phantoms.
- Row locks favor concurrency; table locks reduce lock-management cost.
- Intention locks advertise lower-level locks in a hierarchy.
3.2 Make check-then-write decisions safe
A read followed by a write is not automatically one safe decision. Another transaction can change the inputs between those statements. Choose a method that protects the decision from its first relevant read through its write.
Compute inside one update
UPDATE stock
SET qty = qty - 3
WHERE item_id = 42 AND qty >= 3;
Check the affected-row count. For an existing item, 1 means the reservation succeeded; 0 means the condition no longer permits it. If stock starts at 10, concurrent relative updates subtracting 3 and 4 leave 3. PostgreSQL READ COMMITTED makes the second updater wait and then recheck the condition against the committed row.
Lock before reading a replacement value
START TRANSACTION;
SELECT qty FROM stock WHERE item_id = 42 FOR UPDATE;
-- If the returned quantity is 10, the application computes 7.
UPDATE stock SET qty = 7 WHERE item_id = 42;
COMMIT;
FOR UPDATE locks the returned row through transaction end. A second transaction using the same method waits, then reads 7 before calculating its own replacement. Taking a lock only after an ordinary read would leave the original decision stale.
In PostgreSQL, InnoDB and Oracle, an ordinary snapshot SELECT usually reads an older committed version without waiting for that row lock. Every read-then-write path must therefore use the chosen protection. PostgreSQL and MySQL offer FOR SHARE for shared locking; SQL Server uses hints such as WITH (UPDLOCK) for update-oriented reads.
Detect a stale edit with a version
For a user editing a form, hold no database transaction open during the editing time. Read the row with version 5, then submit a short conditional write:
UPDATE products
SET price = 19.90, version = 6
WHERE id = 7 AND version = 5;
Zero affected rows means the submitted version is stale or the row is gone. Reload before retrying. Every writer must maintain the version convention. This is optimistic control: check for a conflict at write time. It still takes a normal write lock while the update runs. Pessimistic control instead acquires protection before the read and makes conflicts wait.
Protect the rows that could appear
A course has 30 seats and 29 enrollments. Two transactions can both count 29 and insert, leaving 31. Locking only the 29 enrollment rows does not lock the missing seat. InnoDB next-key/gap locks and SQL Server serializable key-range locks protect relevant index gaps; general predicate protection describes the search condition itself.
At READ COMMITTED, another solution is a parent-row protocol: every enrollment transaction first locks the course row with FOR UPDATE, then counts enrollments in a later statement. The waiting transaction obtains a fresh statement snapshot after the first commits, counts 30 and refuses. A transaction-wide snapshot can retain the earlier count even after that wait.
A shared enrolled counter with CHECK (enrolled <= capacity) turns the decision into a same-row write conflict. Increment it and insert the enrollment in the same transaction. If the increment would reach 31, the constraint rejects it and the application rolls back. True SERIALIZABLE with whole-transaction retries is another way to protect the cross-row decision.
Key Takeaways
- Use conditional relative updates when one statement can express the rule.
- Acquire a read lock before using the value to compute a replacement.
- Version checks detect stale writes without holding locks during user editing.
- Protect a search condition or coordinate on a shared row to stop capacity races.
- A parent-row lock followed by a count needs a fresh view after waiting.
3.3 Find and handle deadlocks
Waiting is normal when another transaction holds an incompatible lock. A deadlock is different: a cycle of transactions waits on one another, so none can release the locks by finishing normally.
Trace the waiting edges
T1 updates account 1 and holds X(1). T2 updates account 2 and holds X(2). T1 then requests account 2; T2 requests account 1. Draw a wait-for graph with an arrow from the waiting transaction to the holder. Here T1 → T2 and T2 → T1 form a cycle.
A single edge does not establish deadlock. If T2 is still running freely, it can commit and release the lock T1 needs. The cycle is what makes the wait self-sustaining.
Databases check wait-for graphs when waits arise or persist. PostgreSQL's deadlock_timeout defaults to 1 second before a deadlock check; this is not a limit that cancels every lock wait after 1 second.
Release a victim and retry
The database chooses a victim so the remaining transactions can progress. PostgreSQL, InnoDB and SQL Server roll back the victim transaction. Oracle reports ORA-00060 and rolls back the blocked statement, so the application should explicitly roll back the remaining transaction before retrying.
PostgreSQL uses SQLSTATE 40P01, MySQL deadlock error 1213, and SQL Server error 1205. Victim selection can consider work or locks; SQL Server also supports SET DEADLOCK_PRIORITY. Application code must retry the whole logical transaction with fresh reads, not just resubmit the statement that happened to wait.
Prevent cycles by choosing one order
For transfers between accounts 1 and 2, always acquire account 1 before account 2, even when money moves in the opposite direction. If every transaction follows one global order, the circular dependency cannot form. Acquire the strongest needed lock from the start when feasible: two shared holders both trying to upgrade to X can otherwise deadlock.
Keep transactions short and use suitable indexes to limit rows scanned and locked. These reduce conflicts, while a consistent resource order directly prevents ordering cycles.
Compare age-based prevention
Assign each transaction a timestamp; a smaller timestamp is older.
| Protocol | Older requester meets younger holder | Younger requester meets older holder |
|---|---|---|
| Wait-die | Wait | Requester rolls back |
| Wound-wait | Holder rolls back | Wait |
Waits follow one age direction, so no cycle can form. A restarted transaction keeps its original timestamp in these prevention schemes, helping it eventually stop losing. This differs from basic timestamp ordering of data operations, which restarts with a new timestamp.
A lock timeout rejects a wait after a limit without proving a cycle. InnoDB's innodb_lock_wait_timeout defaults to 50 seconds. A timeout can reject ordinary blocking, and waiting for it can delay resolution of a real deadlock when detection is not available. Deadlock and starvation also differ: starvation means one transaction keeps losing while others do finish. MVCC does not remove deadlocks because writers still acquire locks.
Key Takeaways
- A wait-for edge points from the waiter to the lock holder.
- A cycle identifies deadlock; an isolated wait can be ordinary blocking.
- Rollback and retry must cover the whole logical transaction.
- A consistent global lock order prevents cyclic lock requests.
- Wait-die and wound-wait direct waits by transaction age.
- Timeouts can reject waits without establishing deadlock.
- MVCC writers can still deadlock.
4Explain multiversion concurrency control and snapshot isolation
A report can keep a consistent view while other users update rows if the database retains older row versions. The snapshot determines which versions the report sees, and its lifetime determines how stable those reads remain. Follow that visibility rule, account for version cleanup, and examine the different-row conflicts that snapshot isolation misses before comparing serializable alternatives.
4.1 Read the right row version
Multiversion concurrency control (MVCC) keeps enough history for a reader to see a consistent view while writers change current data. A snapshot records which committed changes are visible. It is a visibility boundary, not a separate physical copy of the entire database.
Choose the visible version
A row version records its creating transaction and information about its replacement or deletion. A snapshot reader selects a version whose creator had committed by the snapshot boundary and whose replacement had not. The transaction also sees its own changes.
Account A begins with committed version v1 = 500.00. T20 takes a snapshot at 10:00:00. At 10:00:01, T21 writes v2 = 300.00 but has not committed. T20 reads v1 because v2 is uncommitted. T21 commits at 10:00:02.
| T20's next read | Result | Reason |
|---|---|---|
| Under the original transaction-wide snapshot | 500.00 | T21 committed after that snapshot. |
| Under a new READ COMMITTED statement snapshot | 300.00 | T21 committed before the new statement. |
A new reader taking its snapshot at 10:00:03 sees 300.00. The older result is correct for the older snapshot; it is not a failed update.
Separate snapshot reads from current writes
Plain snapshot reads usually avoid row-lock waits by reading an older version. A writer can proceed while those readers continue. Two writers of the same row still conflict and can wait on a row lock. Their transactions can therefore deadlock even though ordinary readers do not block them.
Snapshot timing matters. PostgreSQL READ COMMITTED takes a new snapshot for each statement. PostgreSQL REPEATABLE READ takes its transaction-wide snapshot at the first query; InnoDB establishes its ordinary REPEATABLE READ view at the first consistent read. Starting a transaction is not always the instant that fixes its view.
Locking reads need separate attention. InnoDB SELECT ... FOR UPDATE, UPDATE and DELETE operate on current versions. One REPEATABLE READ transaction can therefore see an old value in a plain SELECT and a newer value in a locking read. PostgreSQL REPEATABLE READ instead raises a serialization failure when it tries to lock or update a row changed and committed since its snapshot.
Keep history only as long as it is needed
PostgreSQL stores row versions in the table and uses VACUUM, usually autovacuum, to remove versions no live snapshot needs. Long-held snapshots delay cleanup and can grow tables. InnoDB reconstructs older rows from undo records and retains history needed by active read views.
Oracle also reconstructs older data from undo, but retention and available space limit how far it can go. If a long query needs overwritten undo, it fails with ORA-01555, "snapshot too old." Its history is not an unlimited promise to every old reader.
MVCC improves the overlap of reporting and updates, but version storage and cleanup have costs. End transactions and long-held snapshots promptly when their work is done. A snapshot makes reads internally stable within its lifetime; protecting decisions across different written rows still needs an isolation method that addresses those dependencies.
Key Takeaways
- A snapshot selects committed versions according to its visibility boundary.
- A transaction sees its own writes as well as its snapshot.
- Fresh statement snapshots and transaction-wide snapshots give different reread results.
- Writers still take locks and can wait or deadlock.
- Long-held snapshots retain history; missing Oracle undo can cause ORA-01555.
4.2 Close the gaps left by snapshot isolation
Snapshot isolation (SI) gives each transaction a stable committed view plus its own writes. Concurrent transactions that write the same row cannot both commit. That rule prevents lost updates, but it does not detect every unsafe dependency.
Follow a write conflict
In PostgreSQL REPEATABLE READ, T1 and T2 both read stock 10. T1 writes 7 for an order of 3. T2 tries to write 6 for an order of 4 and waits. If T1 commits, T2 fails with SQLSTATE 40001; it cannot replace the committed 7 using its old reading of 10. Retrying from the beginning reads 7 and subtracts 4, leaving 3. If T1 rolls back instead, T2 can continue.
Find the conflict that uses different rows
For an on-call shift, both Alice and Bob start available. Each transaction reads the two rows, sees two people and removes a different person. SI finds no same-row write conflict, so both can commit. In either serial order, the second transaction would see only one available person and refuse. This is write skew, showing why stable snapshots are weaker than serializability.
Protect the rule with a truly serializable level, sufficient locks on all rows used by the decision, an enforceable database constraint, or a shared counter that every transaction updates. Updating the same counter materializes the conflict: the database can now detect a collision on one row. Locking existing rows does not by itself protect every possible insertion into a predicate.
Compare serializable methods
| Method | How it handles a dangerous dependency | Main cost |
|---|---|---|
| Two-phase locking | Makes incompatible requests wait. | Lock waits and possible deadlocks. |
| SSI | Tracks snapshot read–write dependencies and rejects a dangerous pattern. | Serialization retries, including some harmless cases rejected conservatively. |
| Optimistic validation | Checks whether intervening writes invalidate a transaction's reads. | Discarded work when validation fails. |
| Basic timestamp ordering | Rejects operations inconsistent with timestamp order. | Repeated restarts under contention. |
PostgreSQL SERIALIZABLE uses serializable snapshot isolation (SSI). Its nonblocking predicate locks track reads; they do not stop writers in the way blocking range locks do. Dependency checking adds no lock wait, although the underlying writes still acquire locks.
Validation-based control reads and computes in a private workspace, validates at commit, then writes. In a simple serial validator, validation and writing must run as one indivisible commit step. Otherwise two conflicting transactions could both validate before either writes. Parallel variants must also account for overlapping write phases.
Basic timestamp ordering assigns a unique timestamp and tracks each item's latest read and write timestamps. A read fails if a younger transaction already wrote the item. A write fails if a younger transaction already read or wrote it. A rejected transaction restarts with a new timestamp. This protocol does not wait, so it cannot create lock deadlocks.
Snapshot isolation prevents many read anomalies, but a product label is not a proof of a serial outcome. Oracle SERIALIZABLE and SQL Server SNAPSHOT can allow write skew. Serialization errors are the database rejecting unsafe work; handle them with complete retries.
Key Takeaways
- Snapshot isolation rejects concurrent same-row writers but permits write skew.
- A shared row can turn a cross-row rule into a detectable write conflict.
- SSI tracks read–write dependencies with nonblocking read markers.
- Optimistic validation must coordinate the validation and write phases.
- Basic timestamp ordering enforces timestamp order by rejecting operations.
5Explain how logging lets a database recover from failures
An acknowledged commit can survive a crash even when its updated table pages have not reached disk. The recovery log bridges that gap, while rollback must also remove work that never committed. Read the write-ahead rules, follow redo and undo through a checkpointed log, and distinguish restarting after a system crash from rebuilding lost storage with backups and archived records.
5.1 Write the log before the page
The database changes pages in a memory buffer pool before writing them to storage. A crash can therefore leave some committed changes missing from data files and some uncommitted changes already present. Recovery information makes this state repairable.
Separate the failure types
| Failure | What is lost or interrupted | Required response |
|---|---|---|
| Transaction failure | One logical operation cannot finish. | Roll back its pending work. |
| System crash | Volatile memory is lost; stored files survive. | Recover from persistent records. |
| Media failure | Stored data is destroyed. | Restore surviving copies and archived logs. |
Memory is volatile. Disks and SSDs are nonvolatile, but they can still fail. Stable storage is the ideal of data that survives failures, approximated with independent redundant copies.
Read an undo/redo log
In the classic undo/redo design used in several database engines, a log is an append-only sequence with a log sequence number (LSN) identifying each record:
<T1 start>
<T1, A, 500.00, 300.00>
<T1, B, 300.00, 500.00>
<T1 commit>
An update record names the transaction, item, old value and new value. The old before image supports undo; the new after image supports redo. This notation is a teaching model, while products organize their physical logs differently.
Apply both WAL rules
Write-ahead logging (WAL) requires the change's log record to reach durable storage before its changed data page is written. Before the database confirms commit, it must also flush all of that transaction's log records, including the commit record.
If the transfer's commit record is durable but its table pages are not, recovery redoes A = 300.00 and B = 500.00. If the commit record never became durable, recovery removes unfinished effects, restoring the starting balances in an undo/redo engine.
Two buffer policies explain the need for both images:
| Policy | Permission | Recovery consequence |
|---|---|---|
| Steal | Write a page containing uncommitted work to disk. | Need undo for unfinished changes. |
| No-force | Confirm commit without flushing every changed data page. | Need redo for committed changes still missing. |
Sequential log appends make committing cheaper than flushing many scattered pages. Group commit flushes several transactions' commit records together; each can be acknowledged after the shared durable flush.
Preserve rollback during later recovery
Normal rollback reads the transaction's updates backward and restores before images. Each restoration is logged in a redo-only compensation log record (CLR), followed eventually by an abort record. Replaying those compensation records prevents crash recovery from resurrecting an already rolled-back change. Savepoint rollback stops at the saved position.
PostgreSQL's WAL is redo-oriented: aborted row versions remain invisible through commit status and are later removed by vacuum. InnoDB combines redo and undo logs; Oracle uses redo and undo; SQL Server uses its transaction log. SQLite supports rollback journaling or WAL mode.
Settings that skip the normal durable commit flush trade durability for speed. Examples include PostgreSQL synchronous_commit = off and InnoDB innodb_flush_log_at_trx_commit values 0 or 2. The newest acknowledged commits can then be lost in a relevant crash.
Key Takeaways
- A crash can leave committed data absent and uncommitted data present in files.
- WAL flushes a change record before its page and the transaction log before commit acknowledgment.
- Steal needs undo; no-force needs redo in an undo/redo design.
- Compensation records preserve rollback when history is replayed.
- PostgreSQL uses visibility rules for aborted row versions and WAL for redo.
- Skipping commit flushes can lose recently acknowledged work.
5.2 Recover committed work and remove unfinished work
Crash recovery restores committed changes and removes unfinished effects. In the classic undo/redo design, redo repeats logged changes forward; undo works backward through unfinished transactions. The order matters because data files may contain only part of the history.
Start from a flushing checkpoint
A simple checkpoint first flushes every modified page and records its active transactions. For this log, record 5 is such a checkpoint:
1 <T1 start>
2 <T1, A, 500, 300>
3 <T2 start>
4 <T2, C, 70, 90>
5 <checkpoint {T1, T2}>
6 <T1, B, 300, 500>
7 <T1 commit>
8 <T3 start>
9 <T3, A, 300, 250>
The crash occurs after record 9. At the checkpoint, disk already contains the effects through record 4, including unfinished T2's change to C.
- Initialize the undo list with T1 and T2 from the checkpoint.
- Redo forward after it. Record 6 sets B to 500; record 7 removes committed T1 from the undo list. Record 8 adds T3; record 9 sets A to 250.
- The undo list is now T2 and T3. Undo backward: restore A to 300 from record 9, then restore C to 70 from record 4. Undo must reach before the checkpoint for a transaction active there.
- Log each restoration as a compensation record and record each completed abort. The final state is A = 300, B = 500 and C = 70.
Redo included unfinished T3's change. This is repeating history; undo then removes it. An already aborted transaction has its rollback preserved by replaying its compensation records and needs no new undo.
Make recovery survive another crash
Value-setting records can be applied repeatedly without adding the change twice. Setting A to 300 again still leaves 300. ARIES also records a page's latest applied LSN and skips redo already reflected in that page. Compensation records preserve completed undo and identify where remaining rollback must continue.
ARIES has three passes. Analysis reconstructs active transactions and dirty pages. Redo repeats history from the oldest change that might still be missing. Undo rolls back unfinished transactions, writing compensation records as it goes.
An ARIES fuzzy checkpoint records recovery state without forcing all dirty pages to disk. Analysis may therefore choose a redo start before the checkpoint. Do not apply the simple checkpoint's start rule to this different design. Checkpoints reduce recovery scanning; the flushing design also creates extra page-write work during normal operation.
Restore after storage is lost
Media recovery restores a full backup and rolls forward a continuous archived log. Point-in-time recovery stops at a selected boundary: stopping at 14:04 avoids an accidental delete committed at 14:05, but also excludes later valid work that must be re-entered separately. The backup needs a continuous usable log chain through the target time. A suitable replica can reduce takeover time.
Ordinary crash recovery preserves committed mistakes because they are committed work. Reverse them with a compensating transaction, or choose a restore boundary when the broader loss of later changes is acceptable.
Key Takeaways
- Redo repeats history; undo then removes unfinished transactions.
- An active transaction can need undo records from before a flushing checkpoint.
- ARIES runs analysis, redo and undo, with logged compensation for rollback.
- A fuzzy checkpoint may require redo from an earlier position.
- Restore a backup and continuous archived logs after media loss.
- Point-in-time recovery excludes valid changes after the selected boundary too.
SQL Transactions and Concurrency Control examples
1Keep a reservation complete through failure
14 steps
- 1IntroductionGive the job one outcome
A parts reservation must reduce stock and create a reservation record. Either both changes belong to the committed database, or neither does. Follow a request for 4 units from stock of 12, then add an optional label and an application retry. The transaction boundary is the link between the SQL statements and the single business outcome.
- 2ExampleIdentify the temporary state
Start with 12 units and no reservation. The first update reduces available stock to 8. Until the reservation row is inserted, the transaction has only completed part of its work. Atomicity requires a failure here to cancel the reduction. The temporary state can exist inside the transaction, but it cannot become the permanent result of a failed reservation.
- 3ExplanationAssign responsibility for the rules
A nonnegative-stock constraint can reject an impossible subtraction, but it cannot invent a missing reservation record. Consistency also needs application logic that performs both changes. Full isolation gives concurrent requests a serial outcome. Durability preserves a successful commit after a system crash, using recovery information already on persistent storage.
- 4ChallengeWhat must survive the crash?
The server crashes after reducing stock to 8 but before inserting the reservation or committing. What should the committed state contain after recovery?
---reveal---
Stock must be 12 and no reservation must exist. The unfinished operation has no permanent effect. Keeping stock at 8 would preserve only one half of the logical job, violating atomicity.
- 5ExampleStart the shared transaction
Use PostgreSQL syntax to put both statements inside one boundary:
BEGIN; UPDATE stock SET qty = qty - 4 WHERE item_id = 63; INSERT INTO reservations (id, item_id, qty) VALUES (720, 63, 4);The current session sees its own stock change immediately. Another transaction at READ COMMITTED cannot read it while it is uncommitted; its read uses committed data or waits, depending on the engine.
- 6ExampleCommit after both changes succeed
After both statements succeed, run
COMMIT;. The server makes the required log records durable before acknowledging the normal commit. The stock reduction and reservation now have one permanent outcome. A laterROLLBACK;cannot cancel them. If the reservation must be canceled later, a new transaction must restore availability and remove or reverse the booking according to the application's rules. - 7ChallengeHandle the failed insertion
Suppose the stock update succeeds but the reservation identifier violates a unique constraint. What should ordinary unhandled-error code do?
---reveal---
Issue
ROLLBACK;, so the stock reduction does not remain pending or become committed. Do not assume every database has already rolled back every earlier statement: many MySQL and SQL Server errors leave earlier work open, while PostgreSQL leaves an aborted transaction to clear. - 8ExplanationIsolate an optional operation
Suppose the required stock and reservation work succeeds, but an optional label can be replaced if its code is already taken. Set
SAVEPOINT before_label;before inserting it. On the expected duplicate error,ROLLBACK TO SAVEPOINT before_label;removes that attempt while preserving the required work. The earlier changes remain pending; the savepoint has committed nothing. - 9ChallengeRead the savepoint boundary
The transaction creates its reservation, sets
before_label, fails to insert label K, rolls back to the marker, inserts label L and commits. What remains?---reveal---
The reservation and label L remain. The failed K attempt does not. A full rollback would cancel the reservation too, but rollback to the marker deliberately retains the work before it. The final commit makes the retained work permanent together.
- 10TipRestart the decision, not one statement
If a serialization failure or deadlock cancels the request, roll back any remaining transaction and retry from the first read with a short bounded delay. Availability may have changed while the other request completed. Reusing the old quantity or retrying only the final write can recreate the decision the database rejected. An unchanged duplicate label needs handled input, not an endless identical retry.
- 11ExampleRecognize a success with a lost reply
Store request key
reserve-720under a unique constraint in the same transaction as the reservation. If the connection drops duringCOMMIT, reconnect and look up that key. Its presence identifies the completed work even though the acknowledgment was lost. Use the same identifier when retrying a request; creating a fresh identifier would conceal that it represents the same operation. - 12ConnectionKeep delivery from repeating the effect
An email service is outside the database transaction. Rolling back SQL cannot unsend a message. Defer the message until the reservation commits, or use an idempotent delivery request so sending again has no extra effect. The request identifier solves a different boundary from a savepoint: it helps recognize repeated attempts across connections or services, after a transaction has ended.
- 13ChallengeChoose the response after reconnecting
The reply was lost, but the request key and reservation now exist. Should the application roll back that order or reserve another 4 units?
---reveal---
Neither. It should recognize the prior committed reservation and return its outcome. Rollback cannot reverse that completed commit, and reserving another 4 units would duplicate the request. Any pending external delivery should use its duplicate-safe request key.
- 14RecapCheck the three boundaries
Use one transaction for all required database changes. Use a savepoint only for a portion the application deliberately knows how to recover. Use a unique request identifier to recognize the same job after an uncertain commit. When concurrency forces a retry, read and decide again from the beginning; when the original work already committed, return that result.
2Trace concurrent work before choosing isolation
15 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionMake the interleaving visible
- 2ExampleCalculate the serial reference results
- 3ExplanationTurn operation order into arrows
- 4ExampleFind the reversal on Y
- 5ChallengeDoes every interleaving form a cycle?
- 6Key InsightCommit order answers another question
- 7ExampleDistinguish pending and changed data
- 8ExampleFollow a changed result set
- 9ChallengeFind the missing reduction
- 10ConnectionSeparate read skew from write skew
- 11ExplanationUse the minimum guarantee correctly
- 12ExampleMatch the view to the report
- 13ChallengeChoose protection for a shared decision
- 14TipCheck the product before setting the name
- 15RecapChoose from the dependency
3Protect a booking decision and untangle its locks
16 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionProtect what the decision depends on
- 2ExplanationRead the compatibility rule
- 3ExampleKeep acquisitions before releases
- 4ChallengeCompare strict and rigorous protection
- 5ConnectionChoose a useful lock size
- 6ExamplePut the stock test inside the change
- 7ExampleLock the read when calculation needs it
- 8TipUse a version during a long edit
- 9ChallengeProtect a room capacity
- 10Key InsightMake the shared-row method complete
- 11ExampleBuild the two waiting edges
- 12ChallengeRemove the opposite request order
- 13ExplanationLet one victim release the cycle
- 14ChallengeFollow the age rule
- 15TipDo not diagnose from the clock alone
- 16RecapAudit mode, timing and scope
4Follow row versions into a serializable decision
12 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionA stable view can coexist with writes
- 2ExampleChoose the version before commit
- 3ExampleRead again after the writer finishes
- 4ChallengeDoes beginning a transaction fix every view?
- 5ConnectionHistory takes space and cleanup
- 6ExampleKeep two different rows from hiding a conflict
- 7ChallengeCompare the serial alternatives
- 8ExampleGive the decisions one shared write
- 9ExplanationTrack the reads as well as the writes
- 10ExplanationValidate or enforce a timestamp order
- 11ChallengeChoose the response to a rejected pair
- 12RecapSeparate the view from the decision
5Rebuild a database from its recovery log
14 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionExpect mixed pages after a crash
- 2ExplanationRead what the record remembers
- 3ExampleWrite information before the page
- 4ExampleAcknowledge after the commit record
- 5ChallengeWhy can an unfinished value be on disk?
- 6ExampleRead the flushing checkpoint
- 7ExampleContinue the log to the crash
- 8ExampleRepeat history forward
- 9ChallengeFinish the backward pass
- 10Key InsightKeep completed undo through another crash
- 11ConnectionChange the checkpoint, change the start rule
- 12ExplanationRestore when the device is gone
- 13ChallengeChoose what the restore keeps
- 14RecapMatch the recovery action to the failure
SQL Transactions and Concurrency Control practice questions
Set 1: Schedules, anomalies and isolation choices10 Practice Questions
Question 1 of 10
Show answerHide answer
Question 2 of 10
R1(A) R2(A) W2(B) R1(B) in a single-version precedence graph?Show answerHide answer
Question 3 of 10
Show answerHide answer
Question 4 of 10
Show answerHide answer
Question 5 of 10
Show answerHide answer
Question 6 of 10
Show answerHide answer
Question 7 of 10
R1(P) W2(P) R2(Q) W3(Q) R3(R) W1(R), what does the single-version precedence graph establish?Show answerHide answer
Question 8 of 10
Show answerHide answer
Question 9 of 10
W1(K) R2(K) C1 C2, T2 reads T1's new value. How should this schedule be classified for recovery?Show answerHide answer
Question 10 of 10
Show answerHide answer
Set 2: Transaction boundaries and reliable requests10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
R1(M) W2(M) R1(N) W2(N), what equivalent serial order follows from the precedence graph?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
W1(X) R2(X) W2(Y) R3(Y) W1(Z) R3(Z) C3 C1 C2. What are its conflict-serializability and recoverability results?Show answerHide answer
Save this lesson to see this answer.
Set 3: Lock safe decisions and resolve deadlocks10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
WHERE qty >= 6 and commits. T2 then completes a concurrent atomic subtraction of 5 with WHERE qty >= 5. How many rows does T2 update, and what remains?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
UPDATE products SET price = 28.00, version = 13 WHERE id = 8 AND version = 12;. What result signals the conflict?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
enrolled <= capacity. Two transactions may insert different enrollment rows. How should a shared-counter protocol protect the rule and keep the count aligned with the rows?Show answerHide answer
Save this lesson to see this answer.
Set 4: Snapshots and serializable decisions10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
SELECT ... FOR UPDATE return?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 5: Log records, restart and recovery decisions10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
<T8, P, 45, 31>, what value is the before image?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
A simple flushing checkpoint occurs at record 5. The crash log is:
1 <T1 start>
2 <T1, A, 900, 650>
3 <T2 start>
4 <T2, C, 40, 55>
5 <checkpoint {T1, T2}>
6 <T1, B, 100, 350>
7 <T1 commit>
8 <T3 start>
9 <T3, A, 650, 600>
What values should recovery leave for A, B and C?
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Starting from a flushed state A = 90, B = 20, C = 8, recovery encounters:
<Ta start>
<Ta, A, 90, 50>
<Ta, A, 90> -- compensation: restore A
<Ta abort>
<Tb start>
<Tb, B, 20, 35>
<Tb commit>
<Tc start>
<Tc, C, 8, 2>
The log ends at the crash. What final state follows from repeating history and undo?
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
After image
ARIES
Atomic update
Atomicity
Autocommit
B
Before image
Buffer pool
C
Cascadeless schedule
Checkpoint
Commit
Compensating transaction
Compensation log record
Conflicting operations
Consistency
D
Deadlock
Deadlock victim
40P01, and its application retries the transaction with fresh reads.Dirty read
Dirty write
Durability
E
Exclusive lock
F
Fuzzy checkpoint
G
Group commit
I
Idempotency
Implicit commit
Intention lock
Isolation
Isolation level
K
Key-range lock
L
Lock escalation
Lock granularity
Lock point
Lock timeout
Locking read
FOR UPDATE waits for an earlier holder before the application computes a replacement.Log sequence number
Lost update
M
Materialized conflict
Media recovery
MVCC
N
No-force policy
Nonrepeatable read
O
Optimistic validation
Optimistic version check
P
Pessimistic concurrency control
Phantom
Point-in-time recovery
Precedence graph
Predicate lock
R
READ COMMITTED
Read skew
READ UNCOMMITTED
Read–write dependency
Recoverable schedule
Redo
REPEATABLE READ
Retry
Rigorous two-phase locking
Rollback
Row version
S
Savepoint
Schedule
Serial schedule
Serializability
SERIALIZABLE
Serializable snapshot isolation
Shared lock
Snapshot
Snapshot isolation
SQLSTATE
40001 as a reason to roll back and retry the whole transaction.Starvation
Steal policy
Strict two-phase locking
T
Timestamp ordering
Transaction
Two-phase locking
U
Undo
Undo history
V
VACUUM
W
Wait-die
Wait-for graph
Wound-wait
Write skew
Write-ahead logging
- 1SQL Subqueries and CTEs
- 2SQL Window Functions
- 3Entity-Relationship Modeling
- 4Database Normalization
- 5Indexes and Query Performance
- 6SQL Transactions and Concurrency Control
- 7SQL Views and Stored Procedures
- 8NoSQL Data Models
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.