Transactions enable running multiple queries, on multiple tables, such that either all of them succeeds or none runs.
This allows performing mutating operations on the target tables, such as inserting or deleting rows, and either commit to all changes or roll back atomically.
Transactions guarantee ACID properties. During a transaction, all reads return a consistent snapshot of the tables.
If a statement in a multi-statement transaction modifies a table, the changes are visible subsequent statements within the same transaction.
Example use case ๐
The incoming order data from an ETL pipeline brings orders for the last 24 hours, everyday. Orders can be mutated within the 24 hour period in different ways. For example, inventory amount can change, or order status can change to “Cancelled” or “Refunded”.
Two queries need to run.
- The orders from the incoming set needs to be inserted to the destination table.
- Older version of the same orders need to be deleted from the destination table.
Using a transaction for these two queries ensures atomicity
Transaction structure ๐
BEGIN TRANSACTION statement starts a transaction.
A transaction ends when any of the following occurs:
- A
COMMIT TRANSACTIONstatement is executed. This statement commits, or executes, all statements inside the transaction. - A
ROLLBACK TRANSACTIONstatement is executed. This will abandon all changes made inside the transaction. - The query ends before reaching either of the above statements. In this case, a roll back is executed.
If an error occurs and the query has an exception handler, the control is taken inside the exception handler. Can choose to either commit or rollback inside the exception block.
If an error occurs and there is no exception handler, then the transaction fails and all changes are rolled back.
Transaction example ๐
BEGIN TRANSACTION;
INSERT INTO mydataset.NewArrivals
VALUES ('top load washer', 100, 'warehouse #1');
-- Trigger an error.
SELECT 1/0;
COMMIT TRANSACTION;
EXCEPTION WHEN ERROR THEN
-- Roll back the transaction inside the exception handler.
SELECT @@error.message;
ROLLBACK TRANSACTION;
Statements supported in transactions ๐
The following statement types are supported in transactions:
- Query statements:
SELECT - DML statements:
INSERT,UPDATE,DELETE,MERGE, andTRUNCATE TABLE - DDL statements on temporary entities:
CREATE TEMP TABLECREATE TEMP FUNCTIONDROP TABLEon a temporary tableDROP FUNCTIONon a temporary function
- DDL statements on permanent entities, such as datasets, tables, and functions, are not supported inside transactions.
- Within a transaction, the following date/time functions have special behaviors:
- The
CURRENT_TIMESTAMP,CURRENT_DATE, andCURRENT_TIMEfunctions return the timestamp when the transaction started. FOR SYSTEM_TIME AS OFclause cannot be used to read a table beyond the timestamp when the transaction started. Doing so returns an error.
- The