PostgreSQL — Transactions
Basic Transaction
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;
Rollback
BEGIN;
DELETE FROM users WHERE id = 1;
ROLLBACK; -- Undo the delete
Savepoint
BEGIN;
INSERT INTO orders (user_id, total) VALUES (1, 100);
SAVEPOINT sp1;
INSERT INTO order_items (order_id, product) VALUES (1, 'Widget');
ROLLBACK TO sp1; -- Undo only the insert
COMMIT;
Transaction Properties
| Property | Description |
|---|---|
| Atomicity | All or nothing |
| Consistency | Valid state |
| Isolation | Concurrent access |
| Durability | Permanent |
Isolation Levels
| Level | Description |
|---|---|
| READ COMMITTED | Default |
| REPEATABLE READ | Consistent reads |
| SERIALIZABLE | Highest isolation |
BEGIN ISOLATION LEVEL SERIALIZABLE;
-- Transaction
COMMIT;
Mini Practice
- Start a transaction
- Commit changes
- Use rollback
- Set isolation level
Up Next
Continue with JSON — JSON support.
Related Topics
Frequently Asked Questions about Transactions
What is Transactions in PostgreSQL?
Transactions is a fundamental concept in PostgreSQL. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Transactions?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Transactions.
Why is Transactions important in PostgreSQL?
Transactions is essential for PostgreSQL development. Understanding this concept will help you write better code and solve real-world problems more effectively.