// dialect comparison

Explicit transactions in every SQL dialect

The core transaction statements: BEGIN, COMMIT and ROLLBACK, with Oracle as the odd one out since its transactions start implicitly.

Filed under Sessions & admin

The verdict

Portable enough to memorize once: BEGIN/COMMIT/ROLLBACK everywhere, with two gotchas. Oracle has no BEGIN, and in MySQL and Oracle any DDL commits the transaction underneath you.

Where they differ

Four engines open explicit transactions with a statement; Oracle starts a transaction at your first DML and ends it only with COMMIT, ROLLBACK or session end.

How each engine writes it

SQL Server

BEGIN TRANSACTION;
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
UPDATE accounts SET balance = balance + 10 WHERE id = 2;
COMMIT;

Also spelled BEGIN TRAN. ROLLBACK undoes everything back to the start; SET XACT_ABORT ON makes any runtime error roll back automatically.

PostgreSQL

BEGIN;
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
UPDATE accounts SET balance = balance + 10 WHERE id = 2;
COMMIT;

START TRANSACTION is a synonym. After an error inside a transaction, statements fail until ROLLBACK (the transaction is aborted).

MySQL

START TRANSACTION;
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
UPDATE accounts SET balance = balance + 10 WHERE id = 2;
COMMIT;

BEGIN also works unless inside a stored program. Most clients keep autocommit on; DDL statements commit implicitly.

SQLite

BEGIN;
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
UPDATE accounts SET balance = balance + 10 WHERE id = 2;
COMMIT;

BEGIN DEFERRED is the default; BEGIN IMMEDIATE grabs the write lock at once, which avoids SQLITE_BUSY surprises on multi-statement writes.

Oracle

UPDATE accounts SET balance = balance - 10 WHERE id = 1;
UPDATE accounts SET balance = balance + 10 WHERE id = 2;
COMMIT;

No BEGIN: the transaction starts at the first DML. ROLLBACK undoes uncommitted work; keep transactions short, they hold undo space.

Questions that come up

Do I need COMMIT for a SELECT?

No changes to commit, but in PostgreSQL and Oracle leaving read transactions open holds back cleanup; end them.

What happens if I forget COMMIT?

The transaction stays open, holding locks: SQL Server/Oracle block other writers, MySQL's InnoDB waits or times out, PostgreSQL blocks cleanup. The connection dropping rolls it back.

Which statements auto-commit?

DDL commits implicitly in MySQL and Oracle. SQL Server, PostgreSQL and SQLite run DDL inside the transaction, so a CREATE TABLE rolls back with everything else.

Keep reading

// write it once, run it anywhere

Switch engines without relearning SQL

SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.