BEGIN statement
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.
BEGIN TRANSACTION;
CREATE account:one SET balance = 135605.16;
CREATE account:two SET balance = 91031.31;
UPDATE account:one SET balance += 300.00;
UPDATE account:two SET balance -= 300.00;
COMMIT TRANSACTION;
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.
An example of the above:
BEGIN;
CREATE account:one SET balance = 135605.16;
CREATE account:two SET balance = 91031.31, wants_to_send_money = true;
IF !account:two.wants_to_send_money {
THROW "Customer doesn't want to send any money!";
};
LET $first = UPDATE ONLY account:one SET balance += 300.00;
LET $second = UPDATE ONLY account:two SET balance -= 300.00;
RETURN "Money sent! Status:\n" + <string>$first + '\n' + <string>$second;
COMMIT;
Output
'Money sent! Status:
{ balance: 135905.16f, id: account:one }
{ balance: 90731.31f, id: account:two, wants_to_send_money: true }'