Step 14
5 min read

BEGIN

Learn how to start a transaction - the first step!

What is BEGIN?

BEGIN starts a transaction. A transaction is a group of SQL commands that should all succeed together.

Simple analogy: Like saying "I am starting a task" before doing multiple steps.

Basic Syntax

BEGIN; -- Your SQL commands here COMMIT;

Simple Example

Money transfer (multiple steps):

BEGIN; UPDATE accounts SET balance = balance - 100 WHERE user_id = 1; UPDATE accounts SET balance = balance + 100 WHERE user_id = 2; COMMIT;

What this does:

  • BEGIN: Start transaction
  • Step 1: Take $100 from user 1
  • Step 2: Give $100 to user 2
  • COMMIT: Save everything

If step 2 fails, step 1 is automatically cancelled!

Real Examples

Example 1: Create Order

BEGIN; INSERT INTO orders (customer_id, total) VALUES (1, 150.00); INSERT INTO order_items (order_id, product_id, quantity) VALUES (101, 5, 2); UPDATE products SET stock = stock - 2 WHERE product_id = 5; COMMIT;

All three steps happen together or not at all.

Example 2: Enroll Student

BEGIN; INSERT INTO enrollments (student_id, course_id) VALUES (1, 101); UPDATE courses SET enrolled_count = enrolled_count + 1 WHERE course_id = 101; COMMIT;

Summary

BEGIN = Start transaction

  • Groups multiple commands
  • All succeed together
  • Or all cancelled together

Finished this topic?

Mark it complete to track your progress and maintain your streak!

SkillsetMaster - AI, Web Development & Data Analytics Courses