SQL Transactions & ACID Properties
Definition
A SQL transaction is a sequence of one or more SQL statements executed as a single atomic unit, ensuring all changes either fully commit or fully roll back.
Introduction to SQL Transactions & ACID Properties
Transactions are the safety net of relational databases. They ensure that bank transfers don't lose money, e-commerce orders don't lose items, and concurrent users don't corrupt each other's data. ACID guarantees — Atomicity, Consistency, Isolation, Durability — define what makes a transaction reliable.
Syntax
BEGIN TRANSACTION; -- or BEGIN; UPDATE accounts SET balance = balance - 500 WHERE id = 1; UPDATE accounts SET balance = balance + 500 WHERE id = 2; COMMIT; -- or ROLLBACK;
Examples
Bank Transfer Transaction
BEGIN; -- Debit sender UPDATE accounts SET balance = balance - 500 WHERE account_id = 'ACC-001'; -- Credit recipient UPDATE accounts SET balance = balance + 500 WHERE account_id = 'ACC-002'; -- Both updates succeed or both roll back COMMIT;
If any statement fails, ROLLBACK reverts all changes. The transfer is atomic — it either fully happens or not at all.
Try in PlaygroundSAVEPOINT for Partial Rollback
BEGIN; INSERT INTO orders (customer_id, total) VALUES (42, 150.00); SAVEPOINT order_created; INSERT INTO order_items (order_id, product_id, qty) VALUES (LASTVAL(), 99, 2); -- If item insert fails, roll back only the item part ROLLBACK TO SAVEPOINT order_created; COMMIT; -- Order saved, items not
SAVEPOINTs create intermediate checkpoints within a transaction, allowing partial rollbacks without discarding all work.
Try in PlaygroundCommon Mistakes
Long-running transactions — hold locks for too long, blocking other users
Not wrapping related operations in a transaction — leaves data in partial state on failure
Wrong isolation level — READ UNCOMMITTED allows dirty reads; SERIALIZABLE has high contention
Implicit autocommit — in many tools, each statement auto-commits; wrap in BEGIN...COMMIT explicitly
Frequently Asked Questions
What are ACID properties in a database?
What is the difference between COMMIT and ROLLBACK?
What are database isolation levels?
What is a deadlock in SQL?
Related SQL Topics
Practice This in the SQL Playground
Write real queries, see live results, and master SQL Transactions & ACID Properties hands-on. 100% free.