What is BEGIN?
BEGIN starts a transaction. A transaction is a group of SQL commands that must all succeed together or all fail together.
Think of BEGIN like opening a safety box. Everything you put inside stays protected until you decide to save it (COMMIT) or throw it away (ROLLBACK).
How BEGIN Works
Why Use BEGIN?
Without BEGIN, each SQL command runs independently. If you run 3 commands and the third one fails, the first two are already saved. You cannot undo them.
With BEGIN, all commands wait until you say COMMIT. If anything fails, you can cancel everything with ROLLBACK.
Basic Syntax
BEGIN;
-- Your SQL commands here
-- Nothing is saved yet
COMMIT; -- Now everything is savedReal-life Example: Bank Transfer
Imagine you want to transfer 100 dollars from your account to your friend.
This requires two steps:
- Remove 100 dollars from your account
- Add 100 dollars to your friend's account
Both steps must succeed. If step 2 fails, step 1 must be cancelled.
BEGIN;
-- Step 1: Remove money from sender
UPDATE accounts SET balance = balance - 100 WHERE user_id = 1;
-- Step 2: Add money to receiver
UPDATE accounts SET balance = balance + 100 WHERE user_id = 2;
COMMIT;If the second UPDATE fails for any reason, the entire transaction is cancelled. No money is lost.
Real-life Example: Online Order
When a customer places an order, multiple things must happen:
- Create the order record
- Add items to the order
- Reduce product stock
All three must succeed together.
BEGIN;
-- Create order
INSERT INTO orders (customer_id, total) VALUES (1, 150.00);
-- Add items to order
INSERT INTO order_items (order_id, product_id, quantity) VALUES (1001, 5, 2);
-- Reduce stock
UPDATE products SET stock = stock - 2 WHERE product_id = 5;
COMMIT;If the stock update fails because there is not enough inventory, the order and order items are also cancelled.
What Happens After BEGIN
After you run BEGIN:
- All your changes are temporary
- Other users cannot see your changes yet
- You can still cancel everything with ROLLBACK
- Changes become permanent only after COMMIT
Summary
BEGIN starts a transaction where:
- Multiple commands are grouped together
- Nothing is saved until COMMIT
- Everything can be cancelled with ROLLBACK
- Either all commands succeed or none do
This is the foundation of safe database operations.