Each statement within SurrealDB is run within its own transaction by default. The BEGIN statement can be used to modify this behaviour by running a group of statements inside a single transaction, either succeeding as a whole, or failing. Once all of the statements within a transaction succeed, then all of the data modifications can be made permanent by finalizing the transaction with a COMMIT statement at the end. If any statement within a transaction encounters an error or the transaction is manually cancelled (CANCEL), then any data modification made within the transaction is rolled back, and will not become a permanent part of the database.
Statement syntax
SurrealQL Syntax
BEGIN[TRANSACTION];
Example usage
The following query shows example usage of this statement.
-- Start a new database transaction. Transactions are a way to ensure multiple operations -- either all succeed or all fail, maintaining data integrity. BEGINTRANSACTION;
-- Create a new account with the ID 'one' and set its initial balance to 135605.16 CREATEaccount:oneSETbalance=135605.16;
-- Create another new account with the ID 'two' and set its initial balance to 91031.31 CREATEaccount:twoSETbalance=91031.31;
-- Update the balance of account 'one' by adding 300.00 to the current balance. -- This could represent a deposit or other form of credit on the balance property. UPDATEaccount:oneSETbalance+=300.00;
-- Update the balance of account 'two' by subtracting 300.00 from the current balance. -- This could represent a withdrawal or other form of debit on the balance property. UPDATEaccount:twoSETbalance-=300.00;
-- Finalize the transaction. This will apply the changes to the database. If there was an error -- during any of the previous steps within the transaction, all changes would be rolled back and -- the database would remain in its initial state. COMMITTRANSACTION;
Returning early from a transaction
While all transactions require a final COMMIT or CANCEL statement in order to run, an early return can take place via the following:
An error inside one of the statements inside the transaction,
A THROW statement to return early with an error,
A RETURN statement to return early. This is often used to customize the output of a transaction.