Curious Minds

Clear answers to science and history questions

What Makes a Database Transaction a Transaction?

· 6 min read · Science

A sequence of database operations is a transaction when it is treated as a single, indivisible unit of work that either completes entirely or has no effect at all, and it must satisfy the ACID properties: atomicity, consistency, isolation, and durability. In practice, this means the database system guarantees that even if the sequence contains many steps, the outside world sees only two possible outcomes: all steps succeed and are permanently recorded, or none of them do.

Background: Why Transactions Exist

Early database systems and file-based data processing exposed a fundamental problem: real-world operations rarely consist of a single change. Transferring money from one account to another requires at least two updates—subtracting from one balance and adding to another. If the system crashes between those two steps, the data becomes inconsistent. Transactions were formalized in the 1970s and 1980s, most notably by researchers at IBM and in the SQL standard, to give application developers a way to group operations so that partial failure cannot corrupt the database.

The concept is not unique to relational databases. Many NoSQL systems, message queues, and even file systems implement transaction-like guarantees, though the scope and strength of those guarantees vary widely. The core idea remains the same: define a boundary around a set of changes and let the database enforce the boundary.

The ACID Properties in Detail

ACID is the standard checklist for what a transaction must provide. Each letter addresses a different failure mode.

  • Atomicity — The transaction is all-or-nothing. If any statement fails, the database rolls back every change made since the transaction began. For example, if a bank transfer debits one account but the credit fails because the target account is closed, atomicity ensures the debit is undone.
  • Consistency — The transaction moves the database from one valid state to another, respecting all declared constraints (primary keys, foreign keys, check constraints, uniqueness). If a constraint would be violated, the transaction is rejected. Consistency is partly the database's job and partly the application's: the database enforces declared rules, but it cannot know every business rule unless those rules are encoded as constraints or triggers.
  • Isolation — Concurrent transactions do not interfere with each other in ways that produce incorrect results. The strongest isolation level, serializable, makes concurrent transactions behave as if they ran one after another. Weaker levels (read committed, repeatable read) allow some concurrency anomalies in exchange for performance.
  • Durability — Once the database confirms a commit, the changes survive crashes, power loss, and restarts. This is typically achieved with write-ahead logging: changes are written to a durable log before being applied to the main data files.

How a Transaction Works Internally

Understanding the mechanics helps explain why transactions behave the way they do. A typical lifecycle looks like this:

  1. BEGIN — The database starts a transaction and assigns it a unique identifier. Changes made from this point are provisional.
  2. Execute statements — Each INSERT, UPDATE, DELETE, or SELECT runs within the transaction's context. The database records undo information (for rollback) and redo information (for durability) in a log.
  3. COMMIT or ROLLBACK — On commit, the database flushes the log to durable storage and marks the transaction as committed. On rollback, it uses the undo information to reverse provisional changes.

Most relational databases use a write-ahead log (WAL) or redo log. The log is written sequentially, which is much faster than updating scattered data pages. Only after the log record is safely on disk does the database consider the transaction durable. The actual data pages may be updated later, a process called checkpointing.

Isolation is implemented with locks, multiversion concurrency control (MVCC), or a combination. MVCC, used by PostgreSQL, Oracle, and others, lets readers see a consistent snapshot without blocking writers, which improves concurrency at the cost of storing multiple versions of rows.

Isolation Levels and Their Trade-offs

The SQL standard defines four isolation levels, each permitting different concurrency anomalies. The exact behavior varies by database product, so the standard is a guide rather than a guarantee.

  • Read uncommitted — Allows dirty reads: a transaction can see uncommitted changes from another. Rarely used because it can produce results that never logically existed.
  • Read committed — Prevents dirty reads but allows non-repeatable reads: re-running the same query within a transaction can return different rows if another transaction commits in between. This is the default in many systems, including PostgreSQL and Oracle.
  • Repeatable read — Prevents non-repeatable reads but may allow phantom reads: new rows inserted by another transaction can appear in a repeated range query. MySQL's InnoDB uses next-key locking to prevent phantoms at this level, which is stronger than the standard requires.
  • Serializable — Provides the strongest guarantee: concurrent transactions produce the same result as some serial order. Implementations use strict two-phase locking or serializable snapshot isolation, which can abort transactions that would violate serializability.

Choosing an isolation level is a trade-off between correctness and throughput. Higher isolation reduces anomalies but increases blocking, deadlocks, and abort rates.

Common Problems and How They Are Handled

Transactions solve many problems but introduce others. Being aware of these helps avoid surprises.

  • Deadlocks — Two transactions each hold a lock the other needs, so neither can proceed. Databases detect deadlocks and abort one transaction, which the application must retry. Keeping transactions short and accessing tables in a consistent order reduces deadlocks.
  • Long-running transactions — A transaction left open for minutes or hours holds locks and prevents vacuuming or log truncation, degrading performance. Applications should commit promptly and avoid interactive transactions that wait on user input.
  • Lost updates — Two transactions read the same value and both write based on it, so one update overwrites the other. Optimistic concurrency control (version columns) or SELECT FOR UPDATE prevents this.
  • Distributed transactions — When a transaction spans multiple databases or services, atomicity requires a two-phase commit protocol, which is slower and can block if a participant fails. Many modern systems prefer sagas or compensating actions instead.

Transactions vs. Batches and Other Groupings

Not every group of operations is a transaction. A batch is simply a collection of statements executed together; without an explicit transaction boundary, each statement may commit independently. A stored procedure may contain many statements but is only transactional if it runs inside a transaction. Similarly, a database connection in autocommit mode treats each statement as its own transaction. The defining feature is the explicit guarantee of atomicity and the other ACID properties, not the mere grouping of commands.

Some systems offer relaxed guarantees. For example, many NoSQL databases provide per-document atomicity but not multi-document transactions, or they offer transactions only within a single partition. These are still transactions, but with a narrower scope. The application must understand the scope to avoid assuming guarantees that do not exist.

Frequently Asked Questions

Can a transaction contain only one statement?

Yes. In autocommit mode, every statement is its own transaction. Even a single UPDATE is atomic and durable. The concept matters most when multiple statements must succeed or fail together.

What happens if the database crashes during a transaction?

On restart, the database uses its log to recover. Committed transactions are reapplied if needed (redo), and uncommitted transactions are rolled back (undo). The result is that the database reflects only committed work.

Is a transaction the same as a lock?

No. A lock is one mechanism used to implement isolation, but transactions also involve logging, rollback, and commit protocols. Some databases use MVCC instead of locks for reads, yet transactions still work.

Do all databases support transactions?

Most relational databases do. Support among NoSQL systems varies: some offer multi-document transactions, others only single-document atomicity. It is important to check the specific product's documentation.

Can I roll back after a commit?

No. Once a transaction commits, its changes are durable and visible. Reversing them requires a new transaction that performs compensating changes, which is not the same as a rollback.

Why do some transactions abort even without errors?

Under serializable isolation, the database may abort a transaction to prevent a serialization anomaly. The application should be prepared to retry such transactions.

In this article
  1. Background: Why Transactions Exist
  2. The ACID Properties in Detail
  3. How a Transaction Works Internally
  4. Isolation Levels and Their Trade-offs
  5. Common Problems and How They Are Handled
  6. Transactions vs. Batches and Other Groupings
  7. Frequently Asked Questions