PostgreSQL
Transactions & Isolation
Control transactions, savepoints, and isolation levels.
By EZ4Code Team
transactionisolationsavepoint
Code
-- Basic transaction
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;
-- Savepoint for partial rollback
BEGIN;
INSERT INTO orders(customer_id, total) VALUES (1, 50);
SAVEPOINT sp1;
INSERT INTO orders(customer_id, total) VALUES (2, -1); -- may fail
ROLLBACK TO sp1;
INSERT INTO orders(customer_id, total) VALUES (2, 10);
COMMIT;
-- Set isolation level (must be before any query)
BEGIN ISOLATION LEVEL SERIALIZABLE;
SELECT count(*) FROM products WHERE stock > 0;
-- business logic here
COMMIT;Explanation
PostgreSQL transactions are atomic and support savepoints for partial rollbacks within a transaction. The default READ COMMITTED isolation level avoids dirty reads; SERIALIZABLE prevents all anomalies but may require retry on serialization failures. Always commit or rollback to release locks.
More PostgreSQL Snippets
SELECT with JOINs
Use INNER, LEFT, and LATERAL joins in PostgreSQL.
JSONB Operations
Store, query, and index JSONB documents.
Window Functions
Compute rankings, running totals, and moving averages.
Common Table Expressions
Use CTEs and recursive CTEs for readable queries.
Index Types
Create B-tree, GIN, GiST, and partial indexes.
Full-Text Search
Search text using tsvector, tsquery, and ranking.