SQL:SQL Transactions: BEGIN, COMMIT, and ROLLBACK
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:

ParameterTypeDescription
COMMITCommandPermanently saves all changes made in the transaction.
ROLLBACKCommandDiscards all changes made in the transaction, restoring previous state.

Ready-to-Run Code Example

Executable in Compilra

Run 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

Run and test SQL on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

SQL Online Compiler