BEGIN
Start a new transaction.
Syntax
START TRANSACTION and BEGIN TRANSACTION are aliases for BEGIN.
Isolation levels
| Level | Description |
|---|---|
REPEATABLE READ | Default. Snapshot is pinned at the first data access. Concurrent commits are not visible within the transaction |
READ COMMITTED | Fresh snapshot per statement. Concurrent commits become visible between statements |
note
SERIALIZABLE is not currently supported.
You can also set the isolation level inside a transaction (before the first query):
BEGIN;
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
Or set the default for the session:
SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL REPEATABLE READ;
Examples
Basic transaction
BEGIN;
INSERT INTO accounts (id, balance) VALUES (1, 1000);
INSERT INTO accounts (id, balance) VALUES (2, 500);
COMMIT;
Transaction with isolation level
BEGIN TRANSACTION ISOLATION LEVEL READ COMMITTED;
SELECT balance FROM accounts WHERE id = 1;
-- Concurrent updates to account 1 become visible on the next SELECT
SELECT balance FROM accounts WHERE id = 1;
COMMIT;
Rollback on error
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
-- Something went wrong
ROLLBACK;
Autocommit
By default, each statement runs in its own implicit transaction and is automatically committed. Use BEGIN/COMMIT to group multiple statements into a single atomic transaction.