Back to top
Documentation SurrealQL Transactions

Transactions

Each statement within SurrealDB is run within its own transaction. If a set of changes need to be made together, then groups of statements can be run together as a single transaction, either succeeding as a whole, or failing without leaving any residual data modifications.

Starting a transaction

The BEGIN TRANSACTION statement can be used to run a group of statements together, either succeeding as a whole, or failing. If all of the statements within a transaction succeed, and the transaction is successful, then all of the data modifications made during the transaction are committed and become a permanent part of the database. If a transaction encounters errors and must be cancelled or rolled back, then any data modification made within the transaction is rolledback, and will not be visible within the database.

BEGIN [ TRANSACTION ];

The following query shows example usage of this statement.

BEGIN TRANSACTION;
-- Setup accounts
CREATE account:one SET balance = 135,605.16;
CREATE account:two SET balance = 91,031.31;
-- Move money
UPDATE account:one SET balance += 300.00;
UPDATE account:two SET balance -= 300.00;
-- Finalise
COMMIT TRANSACTION;

Cancelling a transaction

The CANCEL TRANSACTION statement can be used to cancel a set of statements within a transaction, reverting or rolling back any data modification made within the transaction as a whole.

CANCEL [ TRANSACTION ];

The following query shows example usage of this statement.

BEGIN TRANSACTION;
-- Setup accounts
CREATE account:one SET balance = 135,605.16;
CREATE account:two SET balance = 91,031.31;
-- Move money
UPDATE account:one SET balance += 300.00;
UPDATE account:two SET balance -= 300.00;
-- Rollback all changes
CANCEL TRANSACTION;

Committing a transaction

The COMMIT TRANSACTION statement can be used to commit a set of statements within a transaction, ensuring that all data modifications become a permanent part of the database.

COMMIT [ TRANSACTION ];

The following query shows example usage of this statement.

BEGIN TRANSACTION;
-- Setup accounts
CREATE account:one SET balance = 135,605.16;
CREATE account:two SET balance = 91,031.31;
-- Move money
UPDATE account:one SET balance += 300.00;
UPDATE account:two SET balance -= 300.00;
-- Finalise all changes
COMMIT TRANSACTION;