ACID

ACID is the acronym for the four properties a transaction must keep: Atomicity, Consistency, Isolation, and Durability. The concept is explained in 4.2 The Four Properties of an ACID Transaction. This document collects which mechanism, at which default, and how far each of the five DBMSs guarantees each property. The four letters are the same, but the range guaranteed at default settings differs by product. Isolation and Durability in particular can weaken with a single setting.

Key specs

PropertyAccident it preventsMechanism that keeps itHow products differ
AtomicityOnly part of a transaction is appliedUndo (old values), rollback, restart recoveryWhether a failed statement puts the whole transaction in a failed state
ConsistencyA constraint is brokenPRIMARY KEY, UNIQUE, foreign key, CHECK, NOT NULLWhich constraint types are supported, whether checking can be deferred to commit (DEFERRABLE)
IsolationAnother transaction's intermediate state is visibleLocks, MVCCDefault isolation level, which anomalies an isolation level of the same name actually prevents
DurabilityA change whose commit was acknowledged is lostWAL (Redo log), fsync, restart recoveryWhether the log is written to the device before the commit response, and the setting that turns that off
PostgreSQLMySQL (InnoDB)OracleSQL ServerKDBS
Where old values are keptOld row versions inside the tableUndo logUndo segmentTransaction log (the version store with RCSI or snapshot)Undo pages
LogWALRedo log + binary logRedo logTransaction logWAL
Transaction after a statement errorThe whole transaction failsOnly that statement is cancelledOnly that statement is cancelledOnly that statement is cancelled (XACT_ABORT OFF)The whole transaction fails
DDLCan be rolled back inside a transactionImplicit commit before and afterImplicit commit before and afterMostly rollbackableRollbackable. But the catalog is not recovered after a crash
Default isolation levelRead CommittedRepeatable ReadRead CommittedRead Committed (locking)Read Committed
Highest isolation levelSerializable (SSI)Serializable (locking)Serializable (actually snapshot isolation)Serializable (range locks)Repeatable Read
Log written before commit response (default)YesYesYesYesYes (group)
Setting that lowers Durabilitysynchronous_commit = offinnodb_flush_log_at_trx_commit = 0, 2COMMIT_WRITE = NOWAITDELAYED_DURABILITYrelaxed

Atomicity

Atomicity is the property that undoes all changes of a transaction that fails before commit. To make undoing possible, the DBMS keeps the old value before it changes data (PostgreSQL does this by leaving the old row version in place). There are three cases where changes are undone: when the application issues ROLLBACK, when the DBMS cancels the transaction because of an error or deadlock, and when the server dies before commit and restarts.

Figure. When a transfer transaction is interrupted midway

flowchart TB
  B["BEGIN"] --> W["① Withdraw 100,000 won from account A<br/>Old value to Undo, change to the log buffer"]
  W --> X1{"Server stops here"}
  X1 -->|"Restart"| R1["Recovery: no commit record<br/>Undo the withdrawal"]
  W --> D["② Deposit 100,000 won to account B"]
  D --> C["③ COMMIT<br/>Write the commit record to the log file, then respond"]
  C --> X2{"Server stops here"}
  X2 -->|"Restart"| R2["Recovery: commit record exists<br/>Reapply the withdrawal and deposit from the log"]
  R1 --> S1["Result: state before the transfer<br/>Atomicity"]
  R2 --> S2["Result: state after the transfer<br/>Durability"]

Diagram notes: the left branch is Atomicity and the right branch is Durability.

  1. When ① runs the withdrawal, the DBMS keeps the old value, writes the change to the log buffer, and then modifies the page in memory. This change is not yet committed.
  2. The first Server stops here is the point where only the withdrawal has run. On restart, recovery reads the log, finds no commit record for this transaction, and undoes the withdrawal. The result is the state before the transfer. A state with only the withdrawal does not remain.
  3. ③ COMMIT responds after the commit record is written to the log file. The data pages need not be on disk yet.
  4. The second Server stops here is after the commit response. The data files may contain neither the withdrawal nor the deposit, but recovery reapplies both changes from the log. The result is the state after the transfer.

The point of this figure is that Atomicity and Durability are implemented on the same log. Whether the log has a commit record decides between the two branches (5.4 Redo and Undo, 6.5 Restart Recovery).

When one statement fails

When one statement in a transaction fails with an error (duplicate key, constraint violation), what follows differs by product.

Figure. Results when the same statements are sent

block-beta
  columns 4
  h0["Order and statement"] h1["PostgreSQL, KDBS"] h2["MySQL, Oracle"] h3["SQL Server"]
  s1["1 BEGIN"] a1["Transaction starts"] b1["Transaction starts"] c1["Transaction starts"]
  s2["2 UPDATE withdraw from account A"] a2["Succeeds"] b2["Succeeds"] c2["Succeeds"]
  s3["3 INSERT duplicate key"] a3["Fails<br/>Transaction is in a failed state"] b3["Fails<br/>Only this statement is cancelled"] c3["Fails<br/>Only this statement is cancelled"]
  s4["4 UPDATE deposit to account B"] a4["Rejected<br/>Accepts only ROLLBACK"] b4["Succeeds"] c4["Succeeds"]
  s5["5 COMMIT"] a5["Treated as rollback<br/>2 is also cancelled"] b5["2 and 4 are committed"] c5["2 and 4 are committed"]
  n0["With SET XACT_ABORT ON"]:3 n3["The whole transaction rolls back at 3"]
  class h0,h1,h2,h3 meta
  class s1,s2,s3,s4,s5,n0 plain
  class a1,b1,c1,a2,b2,c2,b4,c4,b5,c5 data
  class a3,b3,c3 hot
  class a4,a5,n3 warn

Diagram notes: each row is one statement sent, from the top, and the three columns on the right are the result for each product.

  • PostgreSQL, KDBS. When the statement fails at 3, the whole transaction enters a failed state. Later statements are not executed (Rejected at 4), and PostgreSQL returns current transaction is aborted, commands ignored until end of transaction block. Even if 5 COMMIT is sent, it is treated as a rollback, and the withdrawal from 2, which had succeeded, is cancelled too. To tolerate a failure inside a transaction in PostgreSQL, place a SAVEPOINT before a statement that may fail and ROLLBACK TO it. KDBS has no savepoints, so the whole transaction is rerun.
  • MySQL, Oracle. Only the failed 3 is cancelled (statement-level atomicity) and the transaction continues. 5 commits 2 and 4. If the application commits as is after receiving the error, only an unintended part may be applied, so deciding whether to roll back on an error is the application's job.
  • SQL Server. By default (XACT_ABORT OFF), most errors cancel only that statement. With SET XACT_ABORT ON, as in the bottom row, the whole transaction rolls back as soon as a runtime error occurs. It is usually turned on so that no open transaction is left behind when the client aborts on a command timeout.

The victim of a deadlock is cancelled differently by product. PostgreSQL, MySQL, and SQL Server roll back the victim's whole transaction, while Oracle rolls back only the one statement that caused the deadlock (ORA-00060) and leaves the decision to the application. A MySQL lock wait timeout (innodb_lock_wait_timeout) cancels only that statement by default (innodb_rollback_on_timeout = OFF).

Consistency

Consistency means the DBMS enforces declared constraints on every transaction. The DBMS guarantees the other three properties by itself, but Consistency holds only if the schema declares what a correct state is. Rules that are not declared ("the sum of balances is the same before and after a transfer") must be kept by the application.

PostgreSQLMySQL (InnoDB)OracleSQL ServerKDBS
PRIMARY KEY, UNIQUESupportedSupportedSupportedSupportedSupported (UNIQUE via CREATE UNIQUE INDEX)
Foreign keySupportedSupportedSupportedSupportedSupported. Points only at the parent's tuple key
CHECKSupportedEnforced from 8.0.16. Before that, parsed and ignoredSupportedSupportedNo column CHECK syntax. CREATE ASSERTION and CREATE TRANSITION instead
Deferring checks (DEFERRABLE)UNIQUE, PRIMARY KEY, foreign key, EXCLUDENoneMost constraints, including CHECKNoneNone
Rules across multiple rowsEXCLUDE constraint, triggersTriggersTriggersTriggers, indexed viewsCREATE ASSERTION: per-group count and sum limits
State-change rulesTriggersTriggersTriggersTriggersCREATE TRANSITION: allowed value changes
  • Immediate and deferred checks. By default, constraints are checked at the end of a statement. A constraint declared DEFERRABLE INITIALLY DEFERRED is checked at commit, so you can insert two rows that point at each other one after another, or split an update that swaps unique values across several statements. SET CONSTRAINTS ALL DEFERRED (PostgreSQL, Oracle) can also defer only within a transaction.
  • MySQL foreign keys. InnoDB checks foreign keys per row, not at the end of the statement. A statement that should succeed under the standard (an update that changes the keys of several rows at once in a table with a foreign key pointing at itself) can fail.
  • Relation to Isolation. Even with declared constraints, a low isolation level can break application rules. For example, for "at least one doctor on call", if two transactions each check and each remove one doctor, both succeed under snapshot isolation and the count becomes 0 (write skew). Such rules hold only if you run at Serializable, lock the rows you read with FOR UPDATE, or declare a constraint. KDBS CREATE ASSERTION has the engine check per-group count and sum rules on every write, so this problem does not occur (ASSERTION and TRANSITION).

Isolation

Isolation is the property that keeps concurrently running transactions from seeing each other's intermediate state. Because full isolation (Serializable) is expensive, the SQL standard defines four isolation levels and specifies the anomalies each level permits. However, isolation levels of the same name are implemented differently by product, so the anomalies they prevent differ as well (7.8 Isolation Levels).

AnomalyMeaning
Dirty readReads an uncommitted change
Non-repeatable readReads the same row twice and the value differs because of another commit in between
PhantomReads with the same condition twice and rows were added or removed because of another commit in between
Lost updateTwo transactions read the same value and each computes and writes, so one change is lost
Write skewTwo transactions read overlapping data and write different rows, producing a state that cannot hold together
ProductLevelImplementationPreventsDoes not prevent
PostgreSQLRead Committed (default)Snapshot per statementDirty readNon-repeatable read, phantom, lost update
Repeatable ReadSnapshot per transaction. Update conflict raises error 40001Above + non-repeatable read, phantom, lost updateWrite skew
SerializableSnapshot + serializable snapshot isolation (SSI). Raises 40001 when a dangerous dependency is foundAll anomalies
MySQL (InnoDB)Read CommittedSnapshot per statementDirty readNon-repeatable read, phantom
Repeatable Read (default)Snapshot at the first read. Locking reads and writes read the latest value using next-key locksNon-repeatable read and phantom for plain readsLost update when reading from the snapshot, computing, and writing (overwrites without error), write skew
SerializableTurns even a plain SELECT into a read that takes a shared lockAll anomalies(More deadlocks and waits)
OracleRead Committed (default)Read time (SCN) per statementDirty readNon-repeatable read, phantom, lost update
SerializableReads as of the transaction start. Update conflict raises ORA-08177Above + non-repeatable read, phantom, lost updateWrite skew (actually snapshot isolation)
SQL ServerRead Committed (default)Takes a shared lock briefly when reading and releases it immediatelyDirty readNon-repeatable read, phantom
Read Committed + RCSIRow version per statementDirty read. Reads do not wait for writesNon-repeatable read, phantom
Repeatable ReadShared locks on rows read, held until commitAbove + non-repeatable readPhantom
SnapshotRow version per transaction. Update conflict raises error 3960Above + phantom, lost updateWrite skew
SerializableRange locks (key-range locks)All anomalies(More waits and deadlocks)
KDBSRead Committed (default)Read view per statementDirty readNon-repeatable read, phantom
Repeatable ReadRead view per transaction. The first updater winsAbove + non-repeatable read, phantomWrite skew
  • Read Uncommitted. PostgreSQL accepts this level but runs it as Read Committed, so dirty reads do not occur. Oracle and KDBS do not have this level. Dirty reads actually occur only in MySQL and SQL Server (including the NOLOCK hint).
  • Same name, different behavior. PostgreSQL's Repeatable Read stops a conflicting update with an error, while MySQL's Repeatable Read waits in the same situation and overwrites on top of the latest value. So in MySQL, "read, compute, and write" must read with SELECT … FOR UPDATE to prevent lost updates.
  • Retry. High isolation levels that use snapshots do not wait on a conflict but end with an error (PostgreSQL 40001, Oracle ORA-08177, SQL Server 3960, KDBS TXN_CONFLICT retryable=1). When the application receives this error, it must rerun the whole transaction.

Durability

Durability is the property that a change whose commit was acknowledged survives a server or power failure. All DBMSs use the same approach. Before the commit response, they write the transaction's log to the device and confirm it with fsync. Data pages may be written later, and if the server dies before that, they are rebuilt from the log (Chapter 6 Durability).

Figure. What the commit response promises

sequenceDiagram
  participant C as Client
  participant D as DBMS
  participant B as Log buffer (memory)
  participant F as Log file (device)
  C->>D: COMMIT
  D->>B: Append commit record
  alt Default: log written to the device at every commit
    D->>F: Write and fsync, together with transactions committing at the same time
    F-->>D: Write complete
    D-->>C: Commit complete
    Note over C,F: Survives a server crash after this point
  else Setting with lowered Durability
    D-->>C: Commit complete
    Note over C,F: May be lost if the server dies in this gap
    D->>F: A moment later the background writes and fsyncs
  end

Diagram notes: the upper alt box is the default behavior, and the lower else box is the setting with lowered Durability.

  1. In both cases, on receiving COMMIT the DBMS puts the commit record in the Log buffer.
  2. In the default behavior, it responds Commit complete after writing to the Log file and finishing fsync. If the server dies after that, recovery restores the change from the log. When many transactions commit at the same time, the cost is shared by group commit, which carries them together in one fsync (6.3 Group Commit).
  3. In the setting with lowered Durability, the DBMS responds before writing the log to the device. If the server dies between the response and the background write, a transaction for which the client received commit completion is lost. Atomicity is preserved. A lost transaction disappears entirely, with no partial remainder.
ProductDefault settingSetting that lowers DurabilityRange that can be lost
PostgreSQLsynchronous_commit = onsynchronous_commit = off (per session or transaction)Up to about three times wal_writer_delay (600 ms at the default 200 ms)
MySQLinnodb_flush_log_at_trx_commit = 1, sync_binlog = 1= 2 (write to the operating system cache and respond), = 0 (log buffer only)About 1 second (innodb_flush_log_at_timeout). With = 2, nothing is lost if only the server process dies
OracleCOMMIT_WRITE not set (WAIT)COMMIT WRITE NOWAIT, COMMIT_WAIT = NOWAITCommits before LGWR writes
SQL ServerDELAYED_DURABILITY = DISABLEDALLOWED (the transaction chooses), FORCED (all)Commits before the log buffer fills or is flushed
KDBSdurability = grouprelaxed (per session or transaction)Commits within the sync interval
  • When the device lies. Even if fsync succeeds, if the disk's write cache is on without power protection, the data is lost when power fails. Durability depends not only on the DBMS settings but also on the storage device's write cache setting (6.1 Storage Layers on the Write Path, OS cache).
  • Torn pages. If power fails while a page is being written, the front and back of the page contain content from different points in time. The log alone cannot repair such a page, so PostgreSQL guards against it with full page write, InnoDB with the doublewrite buffer, and SQL Server with page verify.
  • Replication. The description so far covers the Durability of a single server. To survive the loss of the whole machine, you need synchronous replication, which responds after the commit is recorded on another server (PostgreSQL synchronous_standby_names, MySQL semi-synchronous replication, Oracle Data Guard SYNC mode, SQL Server availability group synchronous commit).
  • KDBS DDL. KDBS can roll back DDL such as CREATE TABLE inside a transaction, but the manual states that catalog writes are not logged and so are not recovered after a crash. A committed CREATE TABLE survives a crash only if its page was written to the device. For DDL, only Atomicity and Isolation are guaranteed, not Durability.

Configuration and checks

-- PostgreSQL
SHOW default_transaction_isolation;          -- read committed
SHOW synchronous_commit;                     -- on
SELECT conname, contype, condeferrable, condeferred FROM pg_constraint WHERE conrelid = 'orders'::regclass;

-- MySQL
SELECT @@transaction_isolation, @@innodb_flush_log_at_trx_commit, @@sync_binlog, @@innodb_rollback_on_timeout;

-- Oracle
SELECT name, value FROM v$parameter WHERE name IN ('commit_write', 'commit_wait', 'commit_logging');
SELECT constraint_name, constraint_type, deferrable, deferred FROM user_constraints WHERE table_name = 'ORDERS';

-- SQL Server
SELECT name, is_read_committed_snapshot_on, snapshot_isolation_state_desc, delayed_durability_desc FROM sys.databases;
SELECT session_id, transaction_isolation_level FROM sys.dm_exec_sessions WHERE session_id = @@SPID;   -- 2 = Read Committed

-- KDBS (in the admin tool)
SHOW ASSERTIONS;
SHOW TRANSITIONS;

In this site's PostgreSQL sandbox, when one statement in a transaction failed, every later statement was rejected with ERROR: current transaction is aborted, commands ignored until end of transaction block, and only ROLLBACK was accepted. This is the behavior of the PostgreSQL column in the earlier figure.

In the articles

NOTE Defaults are based on PostgreSQL 17, MySQL 8.0 and 8.4, Oracle 23, SQL Server 2022, and KDBS v3.5, and may differ by version. Azure SQL Database has RCSI on by default.

Related pages