0
0
SQLquery~5 mins

BEGIN TRANSACTION syntax in SQL

Choose your learning style9 modes available
Introduction
BEGIN TRANSACTION starts a group of database actions that should be done together. It helps keep data safe and correct.
When you want to make several changes to the database and ensure all succeed or all fail.
When updating multiple tables that depend on each other.
When transferring money between bank accounts to avoid errors.
When inserting related data that must stay consistent.
When you want to undo changes if something goes wrong.
Syntax
SQL
BEGIN TRANSACTION;
This command marks the start of a transaction block.
You usually follow it with SQL commands and end with COMMIT or ROLLBACK.
Examples
Starts a transaction to transfer 100 units from account 1 to account 2, then saves changes.
SQL
BEGIN TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;
Starts a transaction to insert an order but then cancels it, so no change happens.
SQL
BEGIN TRANSACTION;
INSERT INTO orders (id, product) VALUES (1, 'Book');
ROLLBACK;
Sample Program
This example adds two users inside a transaction and then saves the changes. Finally, it shows all users.
SQL
BEGIN TRANSACTION;
INSERT INTO users (id, name) VALUES (1, 'Alice');
INSERT INTO users (id, name) VALUES (2, 'Bob');
COMMIT;

SELECT * FROM users;
OutputSuccess
Important Notes
Always use COMMIT to save changes or ROLLBACK to undo after BEGIN TRANSACTION.
If you forget COMMIT or ROLLBACK, changes may stay locked or uncommitted.
Transactions help keep data correct when many changes happen together.
Summary
BEGIN TRANSACTION starts a safe group of database actions.
Use COMMIT to save or ROLLBACK to cancel changes.
Transactions keep your data accurate and consistent.