Set and Test Isolation Levels
In this step, you will learn about transaction isolation levels in PostgreSQL and how to set and test them. Isolation levels control the degree to which concurrent transactions are isolated from each other. Higher isolation levels provide greater protection against data corruption but can reduce concurrency.
You should still be connected to the PostgreSQL database from the previous step. If not, connect again using:
sudo -u postgres psql
Open two separate terminal windows. In each terminal, connect to the PostgreSQL database as the postgres
user. You should have two postgres=#
prompts.
Terminal 1:
sudo -u postgres psql
Terminal 2:
sudo -u postgres psql
In Terminal 1, set the isolation level to READ COMMITTED
(although this is the default, we'll set it explicitly for demonstration).
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
Then, begin a transaction.
BEGIN;
In Terminal 1, read Alice's balance.
SELECT balance FROM accounts WHERE name = 'Alice';
Note the balance. Now, in Terminal 2, begin a transaction and update Alice's balance.
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
BEGIN;
UPDATE accounts SET balance = 90.00 WHERE name = 'Alice';
COMMIT;
In Terminal 1, read Alice's balance again.
SELECT balance FROM accounts WHERE name = 'Alice';
Because the isolation level is READ COMMITTED
, you will see the updated balance (90.00) committed by Terminal 2.
Now, let's test the REPEATABLE READ
isolation level. In Terminal 1, roll back the current transaction and set the isolation level to REPEATABLE READ
.
ROLLBACK;
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;
BEGIN;
In Terminal 1, read Alice's balance again.
SELECT balance FROM accounts WHERE name = 'Alice';
Note the balance. Now, in Terminal 2, begin a transaction and update Alice's balance again.
BEGIN;
UPDATE accounts SET balance = 100.00 WHERE name = 'Alice';
COMMIT;
In Terminal 1, read Alice's balance again.
SELECT balance FROM accounts WHERE name = 'Alice';
Because the isolation level is REPEATABLE READ
, you will still see the original balance from when the transaction started, even though Terminal 2 has committed a new value.
Finally, in Terminal 1, commit the transaction.
COMMIT;
Now, if you read Alice's balance in Terminal 1 again, you will see the latest committed value (100.00).
Exit both psql
shells.
\q