SQL Transactions and Concurrency Control: ACID and Locks

Learn how a relational database keeps data correct when many users change it at once and when the server fails. Group SQL statements into transactions with COMMIT, ROLLBACK and savepoints, and see what the ACID properties guarantee. Analyze concurrent schedules, recognize dirty reads, phantoms, lost updates and write skew, and choose an isolation level. Then see how locks, two-phase locking and multiversion concurrency control prevent these anomalies, how databases handle deadlocks, and how the write-ahead log restores a database after a crash.

IntermediateLesson 6 of 8 in Database Design and Advanced SQL Course

What you will learn

  1. 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 guarantees
      Define 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 SQL
      Use 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 code
      Undo 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.
  2. 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 serializability
      Model 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 anomalies
      Describe 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 levels
      Map 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.
  3. 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 locking
      Use 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 phantoms
      Keep read-then-write logic correct with atomic updates, SELECT … FOR UPDATE, version checks and range or parent-row locks.
    • Detect, prevent and recover from deadlocks
      Recognize a deadlock in a wait-for graph, explain how databases detect it or prevent it, and write transactions that avoid deadlocks and survive them.
  4. 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 snapshots
      Follow 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 alternatives
      Explain 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.
  5. 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 logging
      Name 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 failure
      Carry 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.

SQL Transactions and Concurrency Control study guide

5 chapters

1

Group 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
PropertyWhat it guaranteesWhat the transfer needs
AtomicityAll changes take effect together, or none do.A failure after the debit must cancel it.
ConsistencyA correct transaction preserves the database's rules.The total stays 800.00 and constraints hold.
IsolationFull isolation gives an outcome equivalent to a serial order.Concurrent work cannot produce an impossible combination.
DurabilityA 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 settingEffect of a typical statement error inside a transaction
PostgreSQLLeaves the transaction aborted until rollback, or recovery to an earlier savepoint. A commit in the aborted state rolls back.
MySQL and SQL Server default behaviorMany errors undo the failing statement while earlier work remains pending.
SQL Server with SET XACT_ABORT ONRuntime 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.
2

Recognize 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.

  1. Draw one node per transaction.
  2. For each conflicting pair, draw an edge from the transaction acting first to the one acting later.
  3. Look for a cycle. No cycle means the schedule is conflict serializable.
  4. 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
PhenomenonTimelineWhat changes
Nonrepeatable readT1 reads balance 500.00; T2 withdraws 100.00 and commits; T1 rereads 400.00.An existing row's value or existence.
PhantomT1 counts 29 enrollments; T2 adds a matching enrollment and commits; T1 recounts 30.The set matching a search condition.
Read skewT1 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
LevelDirty readsNonrepeatable readsPhantoms
READ UNCOMMITTEDPossiblePossiblePossible
READ COMMITTEDPreventedPossiblePossible
REPEATABLE READPreventedPreventedPossible
SERIALIZABLEPreventedPreventedPrevented

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
ProductImportant behavior
PostgreSQLREAD UNCOMMITTED behaves as READ COMMITTED. REPEATABLE READ uses snapshot isolation and prevents snapshot-read phantoms, but permits write skew. SERIALIZABLE adds dependency checks.
MySQL InnoDBREPEATABLE READ keeps a snapshot for plain reads, but read-then-write replacement code can lose updates. Locking reads use current data.
SQL ServerREPEATABLE READ holds read locks. SNAPSHOT uses row versions. READ_COMMITTED_SNAPSHOT enables versioned READ COMMITTED.
OracleREAD 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.
3

Control 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 lockAnother transaction holds SAnother transaction holds X
Shared (S)CompatibleWait
Exclusive (X)WaitWait

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.

ProtocolExtra rule beyond basic 2PLResult
Strict 2PLHold every exclusive lock until commit or abort.Prevent dirty reads and cascading rollback.
Rigorous 2PLHold 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.

ProtocolOlder requester meets younger holderYounger requester meets older holder
Wait-dieWaitRequester rolls back
Wound-waitHolder rolls backWait

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.
4

Explain 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 readResultReason
Under the original transaction-wide snapshot500.00T21 committed after that snapshot.
Under a new READ COMMITTED statement snapshot300.00T21 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
MethodHow it handles a dangerous dependencyMain cost
Two-phase lockingMakes incompatible requests wait.Lock waits and possible deadlocks.
SSITracks snapshot read–write dependencies and rejects a dangerous pattern.Serialization retries, including some harmless cases rejected conservatively.
Optimistic validationChecks whether intervening writes invalidate a transaction's reads.Discarded work when validation fails.
Basic timestamp orderingRejects 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.
5

Explain 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
FailureWhat is lost or interruptedRequired response
Transaction failureOne logical operation cannot finish.Roll back its pending work.
System crashVolatile memory is lost; stored files survive.Recover from persistent records.
Media failureStored 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:

PolicyPermissionRecovery consequence
StealWrite a page containing uncommitted work to disk.Need undo for unfinished changes.
No-forceConfirm 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.

  1. Initialize the undo list with T1 and T2 from the checkpoint.
  2. 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.
  3. 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.
  4. 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

5 Walkthroughs

1

Keep a reservation complete through failure

14 steps
Build one stock reservation, recover an optional failure, and decide what can safely be retried.
  1. 1
    IntroductionGive 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.

  2. 2
    ExampleIdentify 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.

  3. 3
    ExplanationAssign 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.

  4. 4
    ChallengeWhat 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.

  5. 5
    ExampleStart 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.

  6. 6
    ExampleCommit 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 later ROLLBACK; 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.

  7. 7
    ChallengeHandle 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.

  8. 8
    ExplanationIsolate 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.

  9. 9
    ChallengeRead 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.

  10. 10
    TipRestart 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.

  11. 11
    ExampleRecognize a success with a lost reply

    Store request key reserve-720 under a unique constraint in the same transaction as the reservation. If the connection drops during COMMIT, 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.

  12. 12
    ConnectionKeep 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.

  13. 13
    ChallengeChoose 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.

  14. 14
    RecapCheck 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.

2

Trace concurrent work before choosing isolation

15 steps
Use a precedence graph, diagnose changing observations, and select a view that protects the job.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionMake the interleaving visible
  2. 2
    ExampleCalculate the serial reference results
  3. 3
    ExplanationTurn operation order into arrows
  4. 4
    ExampleFind the reversal on Y
  5. 5
    ChallengeDoes every interleaving form a cycle?
  6. 6
    Key InsightCommit order answers another question
  7. 7
    ExampleDistinguish pending and changed data
  8. 8
    ExampleFollow a changed result set
  9. 9
    ChallengeFind the missing reduction
  10. 10
    ConnectionSeparate read skew from write skew
  11. 11
    ExplanationUse the minimum guarantee correctly
  12. 12
    ExampleMatch the view to the report
  13. 13
    ChallengeChoose protection for a shared decision
  14. 14
    TipCheck the product before setting the name
  15. 15
    RecapChoose from the dependency
3

Protect a booking decision and untangle its locks

16 steps
Apply lock compatibility, fix a capacity race, and trace the cycle that makes a deadlock different from a wait.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionProtect what the decision depends on
  2. 2
    ExplanationRead the compatibility rule
  3. 3
    ExampleKeep acquisitions before releases
  4. 4
    ChallengeCompare strict and rigorous protection
  5. 5
    ConnectionChoose a useful lock size
  6. 6
    ExamplePut the stock test inside the change
  7. 7
    ExampleLock the read when calculation needs it
  8. 8
    TipUse a version during a long edit
  9. 9
    ChallengeProtect a room capacity
  10. 10
    Key InsightMake the shared-row method complete
  11. 11
    ExampleBuild the two waiting edges
  12. 12
    ChallengeRemove the opposite request order
  13. 13
    ExplanationLet one victim release the cycle
  14. 14
    ChallengeFollow the age rule
  15. 15
    TipDo not diagnose from the clock alone
  16. 16
    RecapAudit mode, timing and scope
4

Follow row versions into a serializable decision

12 steps
Compare statement and transaction snapshots, then expose the different-row conflict that needs stronger control.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionA stable view can coexist with writes
  2. 2
    ExampleChoose the version before commit
  3. 3
    ExampleRead again after the writer finishes
  4. 4
    ChallengeDoes beginning a transaction fix every view?
  5. 5
    ConnectionHistory takes space and cleanup
  6. 6
    ExampleKeep two different rows from hiding a conflict
  7. 7
    ChallengeCompare the serial alternatives
  8. 8
    ExampleGive the decisions one shared write
  9. 9
    ExplanationTrack the reads as well as the writes
  10. 10
    ExplanationValidate or enforce a timestamp order
  11. 11
    ChallengeChoose the response to a rejected pair
  12. 12
    RecapSeparate the view from the decision
5

Rebuild a database from its recovery log

14 steps
Apply the WAL rules, repeat a checkpointed history, undo unfinished work, and choose the right restore boundary.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionExpect mixed pages after a crash
  2. 2
    ExplanationRead what the record remembers
  3. 3
    ExampleWrite information before the page
  4. 4
    ExampleAcknowledge after the commit record
  5. 5
    ChallengeWhy can an unfinished value be on disk?
  6. 6
    ExampleRead the flushing checkpoint
  7. 7
    ExampleContinue the log to the crash
  8. 8
    ExampleRepeat history forward
  9. 9
    ChallengeFinish the backward pass
  10. 10
    Key InsightKeep completed undo through another crash
  11. 11
    ConnectionChange the checkpoint, change the start rule
  12. 12
    ExplanationRestore when the device is gone
  13. 13
    ChallengeChoose what the restore keeps
  14. 14
    RecapMatch the recovery action to the failure

SQL Transactions and Concurrency Control practice questions

50 Practice Questions in 5 sets

Set 1: Schedules, anomalies and isolation choices10 Practice Questions

Question 1 of 10

What is the weakest SQL standard isolation level that prevents dirty reads?
  1. READ COMMITTED
  2. READ UNCOMMITTED
  3. REPEATABLE READ
  4. SERIALIZABLE
Show answerHide answer
Answer: A
READ COMMITTED is the first standard level that forbids dirty reads. REPEATABLE READ also forbids them, but adds protection against nonrepeatable reads, so it is stronger than the question requires. The minimum guarantee still permits newly committed changes between statements.

Question 2 of 10

What verdict follows for R1(A) R2(A) W2(B) R1(B) in a single-version precedence graph?
  1. Conflict serializable as T1 then T2
  2. Conflict serializable as T2 then T1
  3. Not conflict serializable because both read A
  4. Not conflict serializable because B creates a cycle
Show answerHide answer
Answer: B
The two reads of A create no conflict. T2's write of B precedes T1's read, producing the single edge T2 → T1 and an acyclic graph. Drawing an edge for the reads of A would add a dependency that the conflict rule does not support.

Question 3 of 10

A transaction reads the same product row twice. Another transaction commits a price change between those reads, so the two prices differ. What happened?
  1. A dirty read
  2. A lost update
  3. A dirty write
  4. A nonrepeatable read
Show answerHide answer
Answer: D
The repeated read of an existing row sees a committed change, so it is nonrepeatable. A dirty read would use the price before its writer committed. The changed price alone does not imply that an update was lost or that either transaction overwrote uncommitted work.

Question 4 of 10

A report counts 8 open jobs. Another transaction changes one closed job to open and commits. The repeated query counts 9. What phenomenon changed the report?
  1. A nonrepeatable read of one job's stored count
  2. A dirty read of the changed job's status
  3. A phantom caused by a qualifying update
  4. A lost update to the report's search condition
Show answerHide answer
Answer: C
The status update moves a row into the set matching the report's condition, producing a phantom. An insert is not required. Describing the effect only as a changed value in an existing row misses that this report observes the membership of a search result.

Question 5 of 10

Stock is 24. Two clients both read 24; one stores 17 for an order of 7 and commits, then the other stores 19 for an order of 5 and commits. What is the final stored quantity and the quantity after both reductions?
  1. Stored 12; both reductions give 19
  2. Stored 17; both reductions give 12
  3. Stored 19; both reductions give 12
  4. Stored 19; both reductions give 17
Show answerHide answer
Answer: C
The last literal replacement stores 19, overwriting the earlier reduction to 17. Applying both orders to 24 should leave 12. The result 17 includes only the first order; merely keeping the smaller replacement would still omit the other change.

Question 6 of 10

A PostgreSQL report reads totals from several tables in separate statements and needs one committed view throughout. It never writes. What level supplies that view without requiring SERIALIZABLE?
  1. READ COMMITTED
  2. REPEATABLE READ
  3. READ UNCOMMITTED
  4. READ COMMITTED with autocommit
Show answerHide answer
Answer: B
PostgreSQL REPEATABLE READ keeps a transaction-wide snapshot for the report's queries. READ COMMITTED takes a new statement snapshot and can mix commits across tables. Turning on autocommit makes separate statements separate transactions, so it does not provide the required shared view.

Question 7 of 10

For R1(P) W2(P) R2(Q) W3(Q) R3(R) W1(R), what does the single-version precedence graph establish?
  1. The order T1, T2, T3 satisfies every conflict.
  2. The order T3, T2, T1 satisfies every conflict.
  3. Three independent conflicts permit any serial order.
  4. A cycle prevents conflict serializability.
Show answerHide answer
Answer: D
P gives T1 → T2, Q gives T2 → T3, and R gives T3 → T1. Together they form a three-transaction cycle, so no serial order preserves every conflict. Ordering only the first two edges overlooks the final dependency back to T1.

Question 8 of 10

Two services maintain a cross-row eligibility rule in PostgreSQL. Service A uses SERIALIZABLE; service B makes uncoordinated READ COMMITTED decisions and writes. The rule sometimes fails. What should change to rely on the serializable guarantee?
  1. Make all rule-maintaining transactions participate at SERIALIZABLE with retries.
  2. Keep only service A serializable and retry its final statement on failure.
  3. Keep service B unchanged and refresh service A's snapshot after each read.
  4. Make service B REPEATABLE READ and rely on its same-row writer check.
Show answerHide answer
Answer: A
The rule depends on all participating transactions, so one serializable service cannot control uncoordinated weaker-level decisions. Both services must use sufficient coordination; for the requested guarantee, that means SERIALIZABLE with whole-transaction retries. Snapshot isolation alone still permits different-row write skew.

Question 9 of 10

In W1(K) R2(K) C1 C2, T2 reads T1's new value. How should this schedule be classified for recovery?
  1. Cascadeless, but not recoverable
  2. Both recoverable and cascadeless
  3. Recoverable, but not cascadeless
  4. Neither recoverable nor cascadeless
Show answerHide answer
Answer: C
T1 commits before T2, so the read dependency meets recoverability. T2 nevertheless reads before T1 commits, making the schedule non-cascadeless. Requiring only the final commit order permits a dirty read and potential cascading rollback if the writer fails earlier.

Question 10 of 10

A rule requires at least one active supervisor. At snapshot isolation, two transactions each read all active supervisors, see two, then deactivate a different supervisor only if the count exceeds one. Both commit. Why does this show the level is not serializable?
  1. Either serial order would make the second transaction see only one active supervisor.
  2. Each transaction must have read the other's uncommitted supervisor change.
  3. Both transactions must have written the same supervisor row without waiting.
  4. The first commit must have made the second transaction's snapshot refresh.
Show answerHide answer
Answer: A
The two snapshots allow both decisions, but neither serial order does: the second decision would see just one supervisor and refuse. The writes affect different rows, so this is write skew, not a same-row lost update. Stable snapshots do not refresh at the competing commit.
Set 2: Transaction boundaries and reliable requests10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A reservation reduces availability but crashes before inserting its booking. What ACID property requires the unfinished reduction to disappear?
  1. Consistency
  2. Isolation
  3. Atomicity
  4. Durability
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A transfer debits 65.00 from one account and credits 60.00 to another. Every declared constraint passes, and the transaction commits. Why can this still violate ACID consistency?
  1. The commit ended before both statements had executed.
  2. The application failed to preserve the total-balance rule.
  3. The database permitted another writer to change the debit.
  4. The log failed to make the two changed pages durable.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A client runs two successful standalone updates with autocommit enabled and no explicit transaction. How many transactions commit?
  1. Two transactions
  2. One transaction
  3. No transactions
  4. Three transactions
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

In PostgreSQL, a transaction inserts a shipment, then an unhandled constraint error occurs. No savepoint exists. What should the application do before starting the corrected shipment?
  1. Commit the insertion, then repeat the update.
  2. Repeat the failed update, then commit both.
  3. Release the transaction, then keep its insertion.
  4. Roll back, then begin the shipment again.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A transaction inserts package P, creates savepoint S, inserts Q, rolls back to S, inserts R and commits. Which packages remain?
  1. P, Q and R
  2. P and R
  3. Q and R
  4. R only
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A new transaction repeatedly tries to insert the same identifier that already violates a unique constraint. What should change before another attempt?
  1. The delay before the identical insertion
  2. The maximum number of identical attempts
  3. The conflicting input or the operation itself
  4. The order of unrelated statements only
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A client loses its connection while committing a ticket order. The order stores a unique request identifier with its changes. What should the client do on reconnect?
  1. Check for that request before deciding to repeat the order.
  2. Repeat the order with a fresh identifier to ensure delivery.
  3. Assume rollback and repeat the order with no lookup.
  4. Assume commit and acknowledge success without a lookup.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

For R1(M) W2(M) R1(N) W2(N), what equivalent serial order follows from the precedence graph?
  1. T2 before T1
  2. Neither order: the graph cycles
  3. Either order: no pair conflicts
  4. T1 before T2
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A billing transaction reads a pending price of 9.00 written by another transaction. The writer later rolls back to 90.00. What anomaly affected billing?
  1. Lost update
  2. Nonrepeatable read
  3. Dirty read
  4. Phantom
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A single-version schedule is W1(X) R2(X) W2(Y) R3(Y) W1(Z) R3(Z) C3 C1 C2. What are its conflict-serializability and recoverability results?
  1. Conflict serializable, but not recoverable
  2. Conflict serializable and recoverable
  3. Not conflict serializable, but recoverable
  4. Neither conflict serializable nor recoverable
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

T1 holds a shared lock on row J. What basic lock can T2 acquire on J immediately, if no other locks exist?
  1. An exclusive lock
  2. A shared lock
  3. An upgrade to exclusive
  4. A table-wide exclusive lock
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A transaction acquires S(A), acquires X(B), releases S(A), then requests X(C). What prevents this sequence from following basic 2PL?
  1. It holds a shared and exclusive lock together.
  2. It reads A before obtaining an exclusive lock.
  3. It requests a new lock after releasing one.
  4. It releases a shared lock before transaction end.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

PostgreSQL READ COMMITTED stock is 9. T1 atomically subtracts 6 with 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?
  1. Zero rows; quantity 3
  2. One row; quantity 4
  3. One row; quantity -2
  4. Zero rows; quantity 9
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

Two editors read version 12. The first writes a price and advances the version to 13. The second submits UPDATE products SET price = 28.00, version = 13 WHERE id = 8 AND version = 12;. What result signals the conflict?
  1. One affected row; version checks serialize both prices.
  2. Zero affected rows; commit makes the price replace the first.
  3. One affected row; the first price remains because versions tie.
  4. Zero affected rows; reload before resolving the edit.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A wait-for graph contains T1 → T2 and T2 → T3. T3 is running and has no outgoing wait edge. What can this graph establish?
  1. All three transactions form one deadlock cycle.
  2. T1 and T2 form a deadlock independently of T3.
  3. Blocking exists, but these edges show no deadlock.
  4. T3 must be aborted before either waiter can finish.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

At PostgreSQL READ COMMITTED, a workshop has capacity 20 and 19 bookings. Every booking transaction first locks the workshop row, then counts bookings in a separate statement, inserts only below capacity and commits. Two arrive together. What final booking count follows?
  1. 21, because both transactions keep the snapshot from before waiting.
  2. 20, because the second count sees the first committed booking.
  3. 19, because both counts wait for a booking row that does not exist.
  4. 20, because row locks automatically reject every phantom insert.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A PostgreSQL REPEATABLE READ booking transaction fixes its snapshot before waiting on an unchanged event row. The first locker inserts the final booking and commits. The waiter gets the event lock, counts bookings and inserts when below capacity. What outcome is possible, and why?
  1. Both inserts can commit because the waiter's count keeps its old snapshot.
  2. Only the first can commit because acquiring the parent lock refreshes the view.
  3. The waiter must abort because the lock-only parent access changes its version.
  4. Both can commit only if the waiter releases the parent lock before counting.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

T1 locks account 30; T2 locks account 10. T1 then requests 10 and T2 requests 30. What consistent rewrite removes this cycle while preserving each transfer's debit and credit direction?
  1. Both debit their source first, then credit the destination after it unlocks.
  2. Both acquire account 30 first only when transferring toward account 10.
  3. Both release their first lock before requesting the other account's lock.
  4. Both acquire account 10 before account 30, then apply their own signed changes.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A transaction timestamped 80 requests a lock held by timestamp 20. Smaller timestamps are older. Under wait-die and wound-wait, what happens to the requester?
  1. Wait-die makes it wait; wound-wait aborts it.
  2. Wait-die aborts it; wound-wait makes it wait.
  3. Both protocols abort the older lock holder.
  4. Both protocols let it wait for the older holder.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A database must keep 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?
  1. Constrain each enrollment row; increment the counter after committing each insertion separately.
  2. Read the shared counter first; insert and store the computed replacement in separate transactions.
  3. Constrain the shared counter; increment it and insert in one transaction, rolling back either failure.
  4. Lock existing enrollment rows; insert new rows and periodically rebuild the unprotected counter.
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

A snapshot reader encounters a row version created by another transaction that has not committed. The preceding version was committed and visible in the snapshot. What does the reader use?
  1. The newer uncommitted version
  2. Nothing until the writer commits
  3. The preceding committed version
  4. The pending value if it is smaller
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A PostgreSQL READ COMMITTED transaction reads fee 70. Another transaction changes it to 82 and commits before the next statement starts. What does the second ordinary read return?
  1. 82
  2. 70
  3. A serialization failure
  4. A mandatory lock wait
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

InnoDB REPEATABLE READ has a plain-read snapshot showing quantity 15. Another transaction commits quantity 11. With no pending row locks, what can a plain read followed by SELECT ... FOR UPDATE return?
  1. 11, then 11
  2. 15, then 15
  3. 11, then a dirty value
  4. 15, then 11
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

Two PostgreSQL REPEATABLE READ transactions read stock 16. T1 writes 10 and commits while T2 is waiting to write 12 based on its old read. What should T2's application do after the resulting concurrency error?
  1. Repeat only the replacement of 12, keeping the read of 16.
  2. Roll back and retry the full operation, reading 10 before subtracting 4.
  3. Commit its earlier read, then repeat the replacement of 12.
  4. Switch to autocommit and store 12 without reading again.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A roster needs one active coordinator. L and M are active, and a shared counter is 2 with a constraint requiring at least 1. Two PostgreSQL REPEATABLE READ transactions both read 2 and allow departure only above 1. Each decrements the counter before deactivating its own coordinator in the same transaction. T1 handles L and commits first. What happens to T2 handling M, including a fresh retry?
  1. T2 commits from its snapshot count of 2, leaving both coordinators inactive.
  2. T2 fails on the counter write; a fresh attempt reads 1 and keeps M active.
  3. T2 can retry only its counter write, retaining the old decision to remove M.
  4. T2 refreshes its snapshot after T1 commits and completes the approved departure.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

Three transactions first read initial values: T1 reads P, T2 reads Q and T3 reads R. Each decision then writes the next item: T1 writes Q, T2 writes R and T3 writes P. How can their outcomes differ between PostgreSQL REPEATABLE READ and SERIALIZABLE, and what must an aborted application repeat?
  1. Both levels reject a same-row write collision; repeating only the last write is sufficient.
  2. REPEATABLE READ rejects the read cycle; SERIALIZABLE allows it because each written row differs.
  3. REPEATABLE READ can commit all three; SERIALIZABLE breaks the dependency cycle and needs a whole retry.
  4. Both levels commit all three; SERIALIZABLE merely orders their independent writes by commit time.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

An optimistic engine gives T1 the first commit slot. T1 read A and plans to change B; T2 read B and plans to change A. A proposed implementation validates both before either writes. What coordinated commit sequence is needed when T1 uses its slot first?
  1. Validate and write T1 indivisibly; reject T2's stale B read and recompute T2 after fresh reads.
  2. Validate T1, validate T2, then write T1 and T2 serially without checking their reads again.
  3. Validate both privately, write T1, then accept T2 because the two transactions write different rows.
  4. Write T1 and T2 first, then validate their original reads together after both commits are durable.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

Basic timestamp ordering gives T1 timestamp 10 and T2 timestamp 30. T2 reads X, then T1 tries to write X. No one has written X since initialization. What happens, and what order is protected?
  1. T1 waits; the lack of a later write makes its replacement safe.
  2. T2 aborts; only writes can establish a read timestamp on X.
  3. T1 writes; a read by T2 creates no timestamp constraint.
  4. T1 aborts; allowing its write would violate T1-before-T2 order.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

An Oracle transaction updates row A successfully, then receives ORA-00060 while trying to update B. The application wants to retry the whole operation. What should it do first?
  1. Commit A before repeating the operation on B.
  2. Repeat both statements inside the still-open transaction.
  3. Explicitly roll back the remaining transaction.
  4. Assume Oracle already rolled back all earlier work.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A PostgreSQL SERIALIZABLE workload has many readers and two writers updating the same rows in opposite order. A developer expects SSI to remove all waits and deadlocks. What is wrong with that expectation?
  1. SSI read tracking is nonblocking, but the underlying writer locks can still cycle.
  2. SSI read tracking blocks writers, but the underlying writer locks never wait.
  3. SSI permits different-row write skew whenever every snapshot stays stable.
  4. SSI removes writer locks only after both transactions pass validation.
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

In an undo/redo log record <T8, P, 45, 31>, what value is the before image?
  1. 31
  2. 45
  3. 8
  4. 14
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

An engine confirms commit after flushing its log, while changed data pages remain only in memory. A system crash then loses memory. What policy made this possible, and what reconstructs the missing committed pages?
  1. Steal; undo
  2. No-force; undo
  3. Steal; redo
  4. No-force; redo
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A buffer manager flushes a page modified by an unfinished transaction, after making its update log durable. The transaction later fails. What policy and recovery action explain this case?
  1. Steal permits the flush; undo restores the earlier value.
  2. No-force permits the flush; redo removes the unfinished change.
  3. Steal permits the flush; commit must preserve the unfinished change.
  4. No-force permits the flush; undo confirms that the change committed.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A useful full backup exists, but the disk holding the live database is destroyed. A complete archived log survives through the failure. What recovery sequence can restore later committed work?
  1. Replay only unfinished transactions, then restore the backup.
  2. Run rollback on the destroyed files, then replay the backup.
  3. Restore the backup, then roll forward the archived log.
  4. Restore the backup, then undo every archived commit record.
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?

  1. A = 600, B = 350, C = 55
  2. A = 900, B = 100, C = 40
  3. A = 650, B = 350, C = 40
  4. A = 650, B = 350, C = 55
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?

  1. A = 90, B = 35, C = 8
  2. A = 50, B = 35, C = 8
  3. A = 90, B = 20, C = 8
  4. A = 90, B = 35, C = 2
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

T4 changes P from 60 to 42 and Q from 25 to 43 without committing. During undo, recovery restores Q to 25 and makes its compensation record durable, then crashes before undoing P. What must the next recovery accomplish?
  1. Redo both original changes and keep P = 42, Q = 43.
  2. Treat the compensation as commit and keep P = 42, Q = 25.
  3. Undo the compensation to Q = 43 and restore P = 60.
  4. Preserve Q = 25 from compensation and finish restoring P = 60.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

At an ARIES fuzzy checkpoint, page P still lacks a logged change from before the checkpoint. Transaction T6 also has an uncommitted earlier change on another page already on disk. A crash follows. Why is "redo only after the checkpoint and undo only later records" unsafe?
  1. It would undo P's committed change twice but preserve all of T6 correctly.
  2. It can miss P's earlier redo and leave T6's earlier unfinished change.
  3. It would replay too much committed history and necessarily duplicate P's value.
  4. It is safe because a fuzzy checkpoint flushes every page before recording state.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

Full backups exist from 09:00 and 10:12. Archived logs cover 09:00–10:00 and 10:10–11:00, with a gap at 10:00–10:10. A mistaken delete commits at 10:40 and a valid order at 10:41. How can recovery retain the latest available complete state before the delete, and what must happen to the later order?
  1. Restore 09:00 and replay to 10:39 across the gap; re-enter the later order.
  2. Restore 10:12 and replay to 10:41; the later order needs no re-entry.
  3. Restore 10:12 and replay to 10:39; re-enter the later order separately.
  4. Restore 09:00 and replay to 09:59; the later backup cannot bypass the gap.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

An order transaction stores a unique request key. Its commit reply is lost; on reconnect, that key exists. The application had deferred email until after commit, and the email service accepts the same key idempotently. What should recovery of this request do?
  1. Recognize the committed order and submit the email with its existing key.
  2. Repeat the order with a new key and submit the email with that new key.
  3. Roll back the committed order and repeat both operations with a new key.
  4. Repeat the order with its existing key before checking whether email was sent.
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

82 Key Terms, each with its definition

A

After image
An after image records the new value produced by an update, supplying the information needed to repeat that change during redo.
A redo record setting the balance to 300.00 reconstructs the change without subtracting the amount twice.
ARIES
ARIES is a recovery method with analysis, repeating-history redo and undo passes, using LSNs and compensation records to survive repeated crashes.
After redo reconstructs history, ARIES undo removes the transactions that had not finished at the crash.
Atomic update
An atomic update expresses a test and data change in one statement, allowing the database to protect them as one operation.
A conditional stock reduction checks availability and subtracts the order quantity without a stale application replacement.
Atomicity
Atomicity is the guarantee that a transaction takes effect completely or leaves none of its changes in the committed state.
After a failed transfer, atomicity prevents the debit from surviving without its matching credit.
Autocommit
Autocommit is a mode in which each successful standalone statement commits as its own transaction without a separate commit command.
Two updates issued under autocommit can leave only the first one permanent if failure separates them.

B

Before image
A before image records the value preceding an update, supplying the information needed to restore that value during undo.
The before image 500.00 lets an undo/redo engine remove an unfinished debit that wrote 300.00.
Buffer pool
A buffer pool is the database's memory area for cached data pages, including modified pages that have not yet reached storage.
A committed update may still be in the buffer pool when a crash destroys volatile memory.

C

Cascadeless schedule
A cascadeless schedule permits reads only from committed transactions, preventing aborts from spreading through dirty-read dependencies.
A report reading only committed row versions does not need to abort when an unseen writer rolls back.
Checkpoint
A checkpoint records recovery state to reduce restart work; a simple flushing checkpoint also writes every modified page to disk.
A flushing checkpoint lets redo start there, while earlier updates of active transactions can still need undo.
Commit
A commit makes a transaction's changes permanent after the database has met its configured commit requirements.
The application commits an order only after its reservation and order records both succeed.
Compensating transaction
A compensating transaction is new committed work that reverses or offsets the business effect of a previously committed transaction.
An opposite transfer compensates for a completed transfer that a later rollback cannot undo.
Compensation log record
A compensation log record (CLR) describes a completed undo action for redo, preserving rollback progress through another crash.
Replaying a CLR keeps a previously restored balance from being replaced by the original unfinished debit.
Conflicting operations
Conflicting operations belong to different transactions, access the same item and include at least one write.
A read followed by another transaction's write on A conflicts; reads of A by both transactions do not.
Consistency
Consistency means a correctly written transaction preserves the database's integrity rules when it commits.
A nonnegative-balance constraint helps consistency, while matching debits and credits also need application logic.

D

Deadlock
A deadlock is a cycle of transactions each waiting for a lock held by another in the cycle, leaving none able to finish normally.
Opposite account-lock orders can leave both transfers waiting for the row that the other already holds.
Deadlock victim
A deadlock victim is a transaction whose work the system rolls back to break a lock-wait cycle and let other work proceed.
A PostgreSQL victim receives 40P01, and its application retries the transaction with fresh reads.
Dirty read
A dirty read uses another transaction's uncommitted value, which may disappear if the writing transaction rolls back.
An invoice using an uncommitted price cut can keep a price that was never part of the committed catalog.
Dirty write
A dirty write overwrites a value another transaction changed but has not committed, making independent rollback unsafe.
Holding the first writer's exclusive lock prevents another writer from replacing its pending change.
Durability
Durability keeps a confirmed transaction through later system crashes by preserving the recovery information on persistent storage.
The server can acknowledge a durable commit before all its changed table pages have reached disk.

E

Exclusive lock
An exclusive lock gives one transaction write access that conflicts with other transactions' shared or exclusive locks on the item.
A second stock writer waits while the first transaction holds the row's exclusive write lock.

F

Fuzzy checkpoint
A fuzzy checkpoint records recovery information without forcing all dirty pages to disk, so redo may need an earlier starting point.
ARIES analysis can find an unflushed change older than the checkpoint and begin redo from that earlier position.

G

Group commit
Group commit makes one durable log flush serve several transactions, reducing write overhead while preserving their commit requirements.
Several transactions can wait for the same log flush and then receive their own commit acknowledgments.

I

Idempotency
Idempotency means that repeating an operation has no additional effect beyond performing it once, often enforced with a request identifier.
A payment service can recognize a repeated request identifier and avoid charging for the same request twice.
Implicit commit
An implicit commit ends pending work as a side effect of another command, such as many table definition commands in MySQL.
A MySQL schema change can commit earlier updates before the application reaches its explicit commit.
Intention lock
An intention lock announces lower-level locks in a hierarchy so a broader lock request can be checked efficiently.
An intention-exclusive table lock signals row write locks without excluding every other row writer.
Isolation
Isolation controls interference between concurrent transactions; full isolation gives the effect of a serial execution.
A report needs enough isolation to avoid combining account balances from different committed states.
Isolation level
An isolation level specifies the protection a transaction receives against concurrent changes and the anomalies it may observe.
A dashboard and a cross-table financial report can need different isolation levels in the same application.

K

Key-range lock
A key-range lock protects an index interval and relevant gaps, preventing changes that would introduce phantoms into a protected search.
A serializable SQL Server search can lock an empty key range so a matching insert must wait.

L

Lock escalation
Lock escalation replaces many fine-grained locks with a broader lock, reducing tracking cost while blocking more work.
SQL Server can escalate many row locks to a table lock, delaying a transaction touching a different row.
Lock granularity
Lock granularity is the size of the protected item, such as a row or table, balancing concurrency against lock-management cost.
Row granularity lets two clients update unrelated products without taking one exclusive lock on the whole table.
Lock point
A lock point is a transaction's final lock acquisition under 2PL; lock-point order gives an equivalent serial order.
After reaching its lock point, a transaction can release locks but cannot acquire an additional one.
Lock timeout
A lock timeout limits how long a lock request can wait before failing, without establishing whether a deadlock exists.
A busy but progressing transaction can cause a timeout even though the wait-for graph has no cycle.
Locking read
A locking read acquires row protection while retrieving data so the transaction can base a later change on that protected read.
A stock read with FOR UPDATE waits for an earlier holder before the application computes a replacement.
Log sequence number
A log sequence number (LSN) identifies an ordered log position, letting recovery track records and changes already applied to pages.
ARIES can skip a redo record when the page's stored LSN shows that the change has already been applied.
Lost update
A lost update occurs when a computed replacement overwrites another change because both transactions used the same earlier value.
Two clients calculate stock replacements from 10, and the later stored replacement omits the first order.

M

Materialized conflict
A materialized conflict makes transactions maintaining a cross-row rule update one shared row so write-conflict control can detect overlap.
A shared on-call counter turns two separate departure decisions into competing writes to the same shift row.
Media recovery
Media recovery rebuilds data after storage failure by restoring a backup and replaying the surviving archived log.
A complete log chain lets a restored backup include committed orders created after that backup was taken.
MVCC
Multiversion concurrency control (MVCC) retains row history so readers can see suitable committed versions while writers change data.
A snapshot report can read an earlier price while another transaction updates the current price.

N

No-force policy
A no-force policy allows commit without flushing every changed data page, so redo must recover committed updates still missing from disk.
The log is durable at acknowledgment even though the changed account page will be written later.
Nonrepeatable read
A nonrepeatable read occurs when rereading a row sees another transaction's committed update or deletion.
A transaction reads a balance, then sees a smaller balance after another transaction commits a withdrawal.

O

Optimistic validation
Optimistic validation checks a transaction's reads against concurrent changes before applying its privately computed writes.
A validator rejects a calculation whose input changed, instead of committing a result based on that stale input.
Optimistic version check
An optimistic version check makes a write conditional on an unchanged version value and advances that version when it succeeds.
A form submitted with version 5 affects no row if another edit has already advanced the stored version to 6.

P

Pessimistic concurrency control
Pessimistic concurrency control acquires protection before accessing decision inputs and makes incompatible transactions wait.
A short reservation transaction can lock its stock row before checking whether enough units remain.
Phantom
A phantom is a change in the rows matching a repeated search condition after another transaction commits a relevant change.
A new enrollment changes a repeated course count, even though the previously returned rows remain unchanged.
Point-in-time recovery
Point-in-time recovery restores a backup and replays archived changes only through a selected boundary before an unwanted event.
Stopping before a committed delete also excludes valid transactions committed after the chosen restore boundary.
Precedence graph
A precedence graph directs each operation conflict from the transaction acting earlier to the one acting later.
Opposite dependencies on A and B create a cycle that rules out conflict serializability.
Predicate lock
A predicate lock represents protection or tracking of rows satisfying a condition, including relevant rows absent from the current result.
Blocking predicate protection can stop matching inserts; PostgreSQL SSI markers instead track dependencies without blocking.

R

READ COMMITTED
READ COMMITTED prevents dirty reads while allowing later statements to observe newly committed changes.
Two PostgreSQL READ COMMITTED queries can see different enrollment totals in the same transaction.
Read skew
Read skew combines related values from different committed states, producing an observation that is inconsistent as a whole.
Reading one account before a transfer and the other after it can report a total that never held in a committed state.
READ UNCOMMITTED
READ UNCOMMITTED is the weakest standard isolation level and permits reading values that other transactions have not committed.
SQL Server can expose rolled-back values at READ UNCOMMITTED, making it unsuitable for exact accounting.
Read–write dependency
A read–write dependency links a reader to a concurrent writer that changes data the reader relied on for its decision.
SSI tracks these dependencies to detect patterns that snapshot same-row writer checks would miss.
Recoverable schedule
A recoverable schedule delays a reader's commit until every transaction whose writes it read has committed.
T2 may read a pending T1 value in a recoverable schedule, but it cannot commit before T1 does.
Redo
Redo reapplies logged changes needed to reconstruct stored pages; repeating-history designs include unfinished and compensation records.
Recovery sets A to its logged new value before later undo removes an unfinished transaction's effect.
REPEATABLE READ
REPEATABLE READ prevents dirty and nonrepeatable reads as a standard minimum, while products differ on snapshots and phantoms.
PostgreSQL implements REPEATABLE READ with snapshot isolation; SQL Server normally keeps shared read locks.
Retry
A transaction retry starts the complete operation again after a transient failure, using fresh reads to make a new decision.
After a serialization failure, retrying only the final update can preserve the stale decision that caused it.
Rigorous two-phase locking
Rigorous two-phase locking retains both shared and exclusive locks until commit or abort, serializing transactions in commit order.
A rigorous report holds its read locks through completion, so conflicting writers may wait for the report.
Rollback
A rollback cancels pending transaction work, restoring its earlier logical state without reversing a completed commit.
The application rolls back the order insertion when the stock subtraction fails its constraint.
Row version
A row version is one historical or current state of a row, with information that lets the database determine its visibility.
An uncommitted version of a changed balance is hidden from another transaction's committed snapshot read.

S

Savepoint
A savepoint is a named position inside an open transaction that lets the application undo later work while keeping earlier work pending.
A savepoint before an optional insertion lets PostgreSQL recover from that insertion's duplicate-key error.
Schedule
A schedule lists operations of concurrent transactions in execution order while preserving the order inside each transaction.
A schedule can alternate T1 and T2 operations without matching either transaction's serial placement.
Serial schedule
A serial schedule finishes each transaction before the next one starts, so their database operations do not interleave.
Three transactions have six serial orders, even if several of those orders produce the same values.
Serializability
Serializability means concurrent execution is equivalent to some serial order of the same transactions.
A transfer and interest calculation can safely interleave when their outcome fits one complete serial order.
SERIALIZABLE
SERIALIZABLE is the standard level requiring concurrent transactions to have the effect of a serial order.
PostgreSQL SERIALIZABLE can reject an on-call change that would create an unsafe dependency between transactions.
Serializable snapshot isolation
Serializable snapshot isolation (SSI) adds read–write dependency checks to snapshot isolation and aborts dangerous patterns.
PostgreSQL SSI can reject a transaction even when its write targets a different row from its competitor.
Shared lock
A shared lock permits concurrent shared holders on the same item while excluding another transaction's exclusive lock.
Two lock-based readers can share a row, while a writer requesting exclusive access must wait.
Snapshot
A snapshot fixes the committed changes visible to a statement or transaction at a visibility boundary, alongside its own writes.
A transaction-wide snapshot keeps the old account balance even after a later transaction commits a new value.
Snapshot isolation
Snapshot isolation gives a stable view and rejects conflicting concurrent same-row writes, but can allow different-row write skew.
Two transactions can keep consistent snapshots yet both remove different people from an on-call shift.
SQLSTATE
A SQLSTATE is a five-character code classifying a database result or error, such as a serialization failure or constraint violation.
Application code can treat SQLSTATE 40001 as a reason to roll back and retry the whole transaction.
Starvation
Starvation occurs when one transaction repeatedly fails to make progress while other transactions continue completing work.
Repeatedly choosing the same transaction as a deadlock victim can delay that transaction indefinitely.
Steal policy
A steal policy lets the buffer manager flush a page containing uncommitted changes, requiring undo in a classic undo/redo engine.
An unfinished stock change can be on disk already, so missing commit does not mean there is nothing to undo.
Strict two-phase locking
Strict two-phase locking follows 2PL and retains all exclusive locks until transaction end, preventing dirty reads.
A reader cannot acquire a shared lock on an unfinished writer's row under strict two-phase locking.

T

Timestamp ordering
Timestamp ordering enforces a chosen serial order by rejecting reads and writes inconsistent with transaction timestamps.
A transaction cannot write an item after a younger transaction has already read it under basic timestamp ordering.
Transaction
A transaction groups one or more database operations into one logical unit whose changes commit together or are canceled.
A transfer needs one transaction so its debit and credit cannot become separate permanent results.
Two-phase locking
Two-phase locking first acquires locks without releasing any, then releases locks without acquiring new ones.
A transaction violates two-phase locking if it releases its A lock and then acquires its first B lock.

U

Undo
Undo restores earlier values to remove unfinished work in an undo/redo design, logging each restoration for safe recovery.
Undo follows a transaction active at a checkpoint back to an update that occurred before that checkpoint.
Undo history
Undo history stores earlier row information that engines such as InnoDB and Oracle use to reconstruct older versions.
An Oracle query can fail with "snapshot too old" if the undo needed for its consistent view has been overwritten.

V

VACUUM
VACUUM is PostgreSQL maintenance that reclaims unneeded dead row-version space once no active snapshot requires it.
A long-held snapshot can delay vacuum cleanup while frequent updates create additional versions.

W

Wait-die
Wait-die prevents deadlocks by allowing only older requesters to wait; a younger requester facing an older holder aborts.
A restarted wait-die transaction keeps its original timestamp so repeated restarts do not make it younger.
Wait-for graph
A wait-for graph directs an edge from each waiting transaction to the holder of the incompatible lock it requests.
The edges T1 → T2 and T2 → T1 identify a deadlock, while one edge alone does not establish a cycle.
Wound-wait
Wound-wait prevents deadlocks by letting older requesters abort younger holders, while younger requesters wait for older holders.
When an older transaction needs a younger holder's row, the younger holder is the one forced to roll back.
Write skew
Write skew occurs when transactions read overlapping data and write different rows, jointly violating a shared rule.
Two on-call doctors can each see the other available and both commit their departure from the shift.
Write-ahead logging
Write-ahead logging (WAL) makes change records durable before changed pages, and transaction records durable before normal commit confirmation.
Recovery can redo a committed balance change when its page was never flushed before the crash.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started