SQL•Transactions
SQL Transactions: BEGIN, COMMIT, and ROLLBACK
Transactions bundle multiple SQL queries into an atomic unit: all succeed (COMMIT) or all are reverted (ROLLBACK).
Syntax
BEGIN TRANSACTION;
UPDATE ...;
COMMIT;
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| COMMIT | Command | Permanently saves all changes made in the transaction. |
| ROLLBACK | Command | Discards all changes made in the transaction, restoring previous state. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing SQL locally:
CREATE TABLE bank_wallets (
user_id TEXT PRIMARY KEY,
balance REAL
);
INSERT INTO bank_wallets VALUES ('Alice', 500.0), ('Bob', 200.0);
-- Atomic money transfer transaction
BEGIN TRANSACTION;
UPDATE bank_wallets SET balance = balance - 100.0 WHERE user_id = 'Alice';
UPDATE bank_wallets SET balance = balance + 100.0 WHERE user_id = 'Bob';
COMMIT;
SELECT * FROM bank_wallets;Expected Output:
user_id balance ------- ------- Alice 400.0 Bob 300.0
How It Works: Step-by-Step
- Lines 1-6: Sets up bank balances.
- Lines 9-14: BEGIN TRANSACTION ensures transfer is atomic; COMMIT locks in updates.
Key Concepts
- Transactions satisfy ACID properties (Atomicity, Consistency, Isolation, Durability).
- If a failure occurs midway through a transaction, ROLLBACK reverts all intermediate steps.
Common Mistake: Performing multi-step fund transfers or inventory changes outside a transaction
Without transactions, a crash between statements deducts money from sender without crediting recipient.
❌ Incorrect
UPDATE accounts SET bal = bal - 100; // Crash here causes lost funds!
✅ Correct
BEGIN TRANSACTION; UPDATE ...; UPDATE ...; COMMIT;
Related SQL Tutorials & Compiler
SQL Multirow Aggregate Metrics Calculation: COUNT, SUM, AVG, and GROUP BY
Calculate multirow aggregate metrics using COUNT, SUM, AVG, MIN, MAX, and partitioned GROUP BY filters with HAVING.
SQL DDL: CREATE TABLE, Constraints (PRIMARY KEY, NOT NULL)
Design schemas using CREATE TABLE with PRIMARY KEY, FOREIGN KEY, NOT NULL, and UNIQUE.
SQL Indexes: B-Tree Indexing and Query Performance
Accelerate search lookups from O(N) table scans to O(log N) using CREATE INDEX.
SQL Online Compiler
Open in Compilra IDE
Run and test SQL on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.