Isolation level quy định các transaction chạy song song "thấy" được gì của nhau — càng cô lập càng đúng nhưng càng kém song song. Mỗi mức loại bỏ thêm một loại lỗi (anomaly):
- READ UNCOMMITTED: cho phép dirty read — đọc dữ liệu B chưa commit, nếu B rollback thì A đọc sai. Không DB production nào khuyên dùng.
- READ COMMITTED (mặc định PostgreSQL): hết dirty read, nhưng còn non-repeatable read — đọc lại cùng dòng có thể thấy giá trị khác (vì B đã commit).
- REPEATABLE READ (mặc định MySQL InnoDB): hết non-repeatable read, nhưng còn phantom read — query lại bằng cùng điều kiện có thể thấy dòng mới do B chèn.
- SERIALIZABLE: không còn anomaly nào, như chạy tuần tự — cô lập cao nhất, song song thấp nhất.
Mẹo: PostgreSQL dùng MVCC — mỗi transaction thấy một "ảnh chụp" DB tại lúc bắt đầu, nên người đọc không chặn người ghi và ngược lại.
Lời khuyên thực dụng: dùng READ COMMITTED cho hầu hết trường hợp; REPEATABLE READ khi cần đọc nhất quán trong một transaction; SERIALIZABLE chỉ khi thật sự cần.
Isolation levels define what concurrently-running transactions can "see" of each other — more isolation means more correctness but less concurrency. Each level removes one more anomaly:
- READ UNCOMMITTED: allows dirty reads — reading B's uncommitted data; if B rolls back, A read wrong data. No production DB recommends it.
- READ COMMITTED (PostgreSQL default): no dirty reads, but non-repeatable reads remain — re-reading the same row may show a different value (because B committed).
- REPEATABLE READ (MySQL InnoDB default): no non-repeatable reads, but phantom reads remain — re-querying with the same condition may show new rows B inserted.
- SERIALIZABLE: no anomalies at all, as if run sequentially — highest isolation, lowest concurrency.
Tip: PostgreSQL uses MVCC — each transaction sees a "snapshot" of the DB from when it started, so readers don't block writers and vice versa.
Practical advice: use READ COMMITTED for most cases; REPEATABLE READ when you need consistent reads within a transaction; SERIALIZABLE only when truly necessary.