ACID stands for atomicity, consistency, isolation and durability. A transaction is a group of SQL statements that either all take effect or none do (atomicity), moves the data between valid states (consistency), does not expose half-finished work to others (isolation), and survives a crash once committed (durability).
On this page
ACID in one table: what each letter promisesAtomicity and consistency: a transfer that rolls backDurability: killing the process mid-transactionIsolation and the four isolation levelsDeadlocks and lock conflictsInterview answers you can say out loudFrequently asked questionsACID is the most-asked theory topic in DBMS interviews, and the part most answers skip is evidence. This page runs each property in SQLite through Python's sqlite3 module: a failed bank transfer that rolls back, a process killed mid-transaction, two connections that cannot see each other's uncommitted work, and a lock conflict.
Every code block was executed on SQLite 3.54.0. SQLite is a single-file database, so its isolation behaviour is simpler than MySQL or PostgreSQL; the isolation table below says where servers differ, with the vendor documentation checked on 1 December 2026. For SQL practice beyond theory, pair this with SQL interview questions and the DBMS and SQL pages in the software development path.
ACID in one table: what each letter promises
A transaction is one logical unit of work, such as a bank transfer, made of several statements. ACID describes what a database promises about transactions. The table pairs each property with the mechanism behind it and the failure it prevents.
| Property | Promise | Mechanism (typical) | Failure it prevents |
|---|---|---|---|
| Atomicity | All statements apply, or none do | Undo log or rollback journal | Money debited but never credited |
| Consistency | Every commit leaves data valid under the rules | Constraints (CHECK, FOREIGN KEY, UNIQUE), triggers | A negative balance, an orphan row |
| Isolation | Concurrent transactions do not see each other's partial work | Locks or multi-version snapshots | Dirty reads, lost updates |
| Durability | Committed data survives a crash or power cut | Write-ahead log or journal flushed to disk | A confirmed order that disappears after restart |
Consistency is the odd one. The database enforces the rules you declare, but it cannot know a rule you never wrote. If nothing says balances must be non-negative, a commit that makes one negative is still consistent as far as the engine is concerned. That is why interviewers say consistency is shared between the database and the application.
Atomicity and consistency: a transfer that rolls back
The script creates two accounts with a CHECK (balance >= 0) rule, then runs transfers inside explicit BEGIN and COMMIT. The second transfer tries to move 900 from an account holding 500, so the debit violates the rule and the whole transaction is rolled back.
import sqlite3
db = sqlite3.connect(":memory:", isolation_level=None) # we issue BEGIN/COMMIT ourselves
db.executescript("""
CREATE TABLE accounts (id TEXT PRIMARY KEY, balance INTEGER NOT NULL CHECK (balance >= 0));
INSERT INTO accounts VALUES ('asha', 1000), ('ravi', 200);
""")
def balances():
return dict(db.execute("SELECT id, balance FROM accounts"))
def transfer(src, dst, amount):
db.execute("BEGIN")
try:
db.execute("UPDATE accounts SET balance = balance - ? WHERE id = ?", (amount, src))
db.execute("UPDATE accounts SET balance = balance + ? WHERE id = ?", (amount, dst))
db.execute("COMMIT")
print("committed", amount)
except sqlite3.Error as e:
db.execute("ROLLBACK")
print("rolled back:", e)
transfer("asha", "ravi", 300)
print(balances())
transfer("ravi", "asha", 900) # ravi has 500: the debit breaks CHECK (balance >= 0)
print(balances())
# Atomicity when the failure comes AFTER the first UPDATE succeeded:
db.execute("BEGIN")
db.execute("UPDATE accounts SET balance = balance - 100 WHERE id = 'asha'")
print("inside the transaction:", balances())
db.execute("ROLLBACK")
print("after rollback: ", balances())committed 300
{'asha': 700, 'ravi': 500}
rolled back: CHECK constraint failed: balance >= 0
{'asha': 700, 'ravi': 500}
inside the transaction: {'asha': 600, 'ravi': 500}
after rollback: {'asha': 700, 'ravi': 500}Read the last three lines carefully. Inside the open transaction Asha's balance reads 600, which is her own uncommitted change. After ROLLBACK it is back to 700, as if the statement never ran. That is atomicity: the database restores the state from before BEGIN. The CHECK failure is consistency doing its job.
By default Python's sqlite3 module opens transactions implicitly before INSERT, UPDATE and DELETE. The demo sets isolation_level=None so the commands you see are the commands that run. MySQL and PostgreSQL also use BEGIN (or START TRANSACTION) and COMMIT, but they default to autocommit per statement in the same way SQLite does outside a transaction.
Durability: killing the process mid-transaction
A rollback is easy to claim. This test is harder to fake: a child process updates both accounts and then ends with os._exit(1), which skips every cleanup step, the same effect as a power cut for the process. We run it twice, once before COMMIT and once after.
import sqlite3, subprocess, sys, tempfile, os
path = os.path.join(tempfile.mkdtemp(), "bank.db")
setup = sqlite3.connect(path)
setup.executescript("CREATE TABLE accounts (id TEXT PRIMARY KEY, balance INTEGER);"
"INSERT INTO accounts VALUES ('asha', 1000), ('ravi', 200);")
setup.commit(); setup.close()
def crash(commit_first):
"""Child process: update, optionally commit, then die without cleanup."""
code = f"""
import sqlite3, os
db = sqlite3.connect({path!r}, isolation_level=None)
db.execute('BEGIN')
db.execute("UPDATE accounts SET balance = balance - 300 WHERE id = 'asha'")
db.execute("UPDATE accounts SET balance = balance + 300 WHERE id = 'ravi'")
{"db.execute('COMMIT')" if commit_first else ""}
os._exit(1) # simulate a power cut: no rollback, no close
"""
subprocess.run([sys.executable, "-c", code])
db = sqlite3.connect(path)
return dict(db.execute("SELECT id, balance FROM accounts"))
print("crash before COMMIT:", crash(False)) # atomicity: nothing applied
print("crash after COMMIT: ", crash(True)) # durability: both updates survivedcrash before COMMIT: {'asha': 1000, 'ravi': 200}
crash after COMMIT: {'asha': 700, 'ravi': 500}Crash before COMMIT: both balances are unchanged, because SQLite uses its rollback journal to undo the half-finished work when the file is next opened. Crash after COMMIT: both updates survived. In server databases the same guarantee comes from a write-ahead log that is flushed to disk at commit. Durability is never absolute: it assumes the disk honours its flush request, which is why the synchronous setting in SQLite and fsync settings in PostgreSQL exist.
Isolation and the four isolation levels
Isolation decides what one transaction may see of another's work. Three anomalies are named in the standard. A dirty read sees uncommitted data. A non-repeatable read gets a different value when the same row is read twice. A phantom read gets a different set of rows when the same query runs twice. The SQL:1992 standard defines four levels by which anomalies each may allow.
| Level | Dirty read | Non-repeatable read | Phantom read | Default in |
|---|---|---|---|---|
| Read uncommitted | Allowed | Allowed | Allowed | None of the three below |
| Read committed | No | Allowed | Allowed | PostgreSQL |
| Repeatable read | No | No | Allowed by the standard | MySQL (InnoDB) |
| Serializable | No | No | No | SQLite (effectively) |
That table shows what the standard permits, not what every engine does. Engines may be stricter than the standard asks. The vendor pages say so directly:
- PostgreSQL accepts all four names but implements three. Read uncommitted behaves like read committed, so dirty reads never happen, and its repeatable read also prevents phantom reads. The default is read committed. (PostgreSQL docs, transaction isolation)
- MySQL with InnoDB offers all four levels. The default is repeatable read, and read uncommitted allows dirty reads. (MySQL 8.4 reference, isolation levels)
- SQLite shows serializable isolation for all transactions, except between shared-cache connections that turn on
PRAGMA read_uncommitted. It achieves this by allowing only one writer at a time. (SQLite isolation documentation)
A quick way to remember it: higher levels give more correctness and less concurrency. Most applications use the default and move one transaction to a higher level only when a specific anomaly appears in testing.
Isolation demo with two connections
Connection A starts a write transaction and changes a balance without committing. Connection B reads, tries to write, then reads again after A commits. WAL mode is switched on so readers and the writer do not block each other.
import sqlite3, tempfile, os
path = os.path.join(tempfile.mkdtemp(), "iso.db")
a = sqlite3.connect(path, isolation_level=None, timeout=0)
b = sqlite3.connect(path, isolation_level=None, timeout=0)
a.execute("PRAGMA journal_mode=WAL") # readers and the writer stop blocking each other
a.executescript("CREATE TABLE accounts (id TEXT PRIMARY KEY, balance INTEGER);"
"INSERT INTO accounts VALUES ('asha', 1000);")
read = lambda c: c.execute("SELECT balance FROM accounts WHERE id = 'asha'").fetchone()[0]
a.execute("BEGIN IMMEDIATE")
a.execute("UPDATE accounts SET balance = 700 WHERE id = 'asha'")
print("A sees its own change: ", read(a))
print("B reads while A is open: ", read(b), "(no dirty read)")
try:
b.execute("UPDATE accounts SET balance = 0 WHERE id = 'asha'")
except sqlite3.OperationalError as e:
print("B tries to write: ", e)
a.execute("COMMIT")
print("B reads after A commits: ", read(b))
# Repeatable reads inside one transaction (snapshot) when A writes in between:
b.execute("BEGIN")
print("B first read in its txn: ", read(b))
a.execute("UPDATE accounts SET balance = 650 WHERE id = 'asha'")
print("B second read, same txn: ", read(b), "(A's commit is invisible to B's open read)")
b.execute("COMMIT")
print("B after its txn ends: ", read(b))A sees its own change: 700
B reads while A is open: 1000 (no dirty read)
B tries to write: database is locked
B reads after A commits: 700
B first read in its txn: 700
B second read, same txn: 700 (A's commit is invisible to B's open read)
B after its txn ends: 650B never saw 700 while A was still open, so there was no dirty read. B's write failed with database is locked because SQLite allows one writer. The last pair shows a snapshot: B's second read inside its transaction still returned 700 although A had committed 650 in between. That is repeatable-read behaviour from WAL mode's snapshot. Do not generalise from SQLite alone: in PostgreSQL's default read committed level, B's second read would see 650.
Deadlocks and lock conflicts
A deadlock happens when transaction 1 holds a lock that transaction 2 needs while transaction 2 holds one that transaction 1 needs, so neither can continue. PostgreSQL detects this and aborts one of the transactions (explicit locking docs). InnoDB does too and rolls back a transaction, trying to pick the smaller one (InnoDB deadlock detection). SQLite has no row locks, but a similar trap exists: two transactions both read, then both try to write.
import sqlite3, tempfile, os
path = os.path.join(tempfile.mkdtemp(), "dead.db")
a = sqlite3.connect(path, isolation_level=None, timeout=0)
b = sqlite3.connect(path, isolation_level=None, timeout=0)
a.executescript("CREATE TABLE t (id INTEGER PRIMARY KEY, v INTEGER); INSERT INTO t VALUES (1, 0);")
# Both transactions read first (shared lock), then both try to write: neither can proceed.
a.execute("BEGIN"); a.execute("SELECT v FROM t").fetchall()
b.execute("BEGIN"); b.execute("SELECT v FROM t").fetchall()
a.execute("UPDATE t SET v = v + 1") # A takes the write intent
try:
b.execute("UPDATE t SET v = v + 10") # B would have to wait for A, A waits for B at commit
except sqlite3.OperationalError as e:
print("B:", e)
try:
a.execute("COMMIT") # A cannot commit while B still holds its read lock
except sqlite3.OperationalError as e:
print("A:", e)
b.execute("ROLLBACK") # the application breaks the deadlock
a.execute("COMMIT")
print(a.execute("SELECT v FROM t").fetchone())B: database is locked
A: database is locked
(1,)SQLite returns the error at once instead of waiting forever, and the application must retry. Servers do the same by killing a victim, so well-written code retries on a deadlock error. Three habits reduce deadlocks: touch rows in the same order everywhere (always the lower account id first), keep transactions short, and never wait for user input inside an open transaction.
Interview answers you can say out loud
- Define a transaction. A group of statements treated as one unit; it ends with COMMIT or ROLLBACK.
- Which property does a rollback show? Atomicity. A crash recovery that keeps a committed row shows durability.
- Is consistency the database's job? Partly. The database enforces declared constraints, the application defines the business rules.
- Name the default isolation level. PostgreSQL: read committed. MySQL InnoDB: repeatable read. Say "it depends on the engine" first, then name them.
- Give an example of a non-repeatable read. You read a balance of 700, another transaction commits 650, you read again and get 650.
- How do you avoid a lost update? Use
SELECT ... FOR UPDATE(MySQL, PostgreSQL), an atomicUPDATE balance = balance - 100, or a higher isolation level.
For a longer list of database questions, see SQL interview questions and the DBMS interview questions page. To understand how the schema side of design prevents bad data, read normalization in DBMS.
Frequently asked questions
What are the ACID properties in DBMS?
ACID stands for atomicity, consistency, isolation and durability. Together they make a transaction safe: it completes entirely or not at all, leaves data valid, does not interfere with concurrent transactions, and stays saved after a crash. Relational databases such as PostgreSQL, MySQL (InnoDB) and SQLite provide ACID transactions.
What is a transaction in DBMS?
A transaction is a sequence of database operations treated as a single unit of work. It begins with BEGIN or START TRANSACTION and ends with COMMIT, which makes the changes permanent, or ROLLBACK, which discards them. A money transfer is the standard example: debit and credit must both happen or neither.
What are the four isolation levels?
The SQL:1992 standard names read uncommitted, read committed, repeatable read and serializable. Going up the list prevents more anomalies (dirty reads, non-repeatable reads, phantoms) at the cost of concurrency. Real engines vary: PostgreSQL treats read uncommitted as read committed, and MySQL InnoDB defaults to repeatable read.
What is a dirty read?
A dirty read happens when a transaction reads data that another transaction has changed but not yet committed. If that other transaction rolls back, the first one has acted on data that never officially existed. Read committed and higher levels prevent dirty reads; in the demo above, connection B read 1000, not 700.
What is the difference between atomicity and durability?
Atomicity concerns the middle of a transaction: if anything fails before commit, all of its changes are undone. Durability concerns the end: once commit has returned, the changes stay even if the server crashes immediately after. The crash test above shows both: no commit meant rollback, commit meant survival.
How does a database handle a deadlock?
Server databases detect the cycle of waiting transactions, abort one of them (the victim) and let the others finish. The application should catch the error and retry the transaction. SQLite, with a single writer, returns a 'database is locked' error rather than waiting indefinitely.
Do NoSQL databases support ACID?
It depends on the product, so check its own documentation. Many NoSQL stores were designed around single-record operations and scale, and added multi-record transactions later, or not at all. Do not assume a database is ACID or not by its family. The MongoDB explainer and types of databases show how the models differ.
Learn this with mentors
Programmes for builders and engineers with admissions open: live classes, mentors and project work.


