Transactions (BEGIN, COMMIT, ROLLBACK)

RoadmapsSQL

Overview

A transaction groups multiple SQL statements into a single, all-or-nothing logical unit of work. You start with BEGIN. If all commands succeed, you COMMIT to save them permanently. If something fails, you ROLLBACK to undo all changes made since BEGIN, leaving the database exactly as it was.

Without transactions, a failure halfway through a complex operation (like deducting money from one account but failing to add it to another) leaves the database in an inconsistent, corrupt state.

Where used: checkout processes, inventory management, bulk data imports

Why learn this

Query walkthrough

BEGIN;
UPDATE employees SET salary = salary + 5000 WHERE id = 7;
UPDATE employees SET salary = salary - 5000 WHERE id = 6;
COMMIT;

Focus: Both updates act as a single unit. Either both employees have their salaries adjusted, or neither do.

Common mistakes

Glossary

inconsistent
A state where data does not match or make sense anymore, like money leaving one account but not arriving in another.
destructive
Having the potential to cause significant damage or permanent loss of data.
aborted
A process that is stopped early before it can finish, usually because an error occurred.

Recall questions

Understanding checks

What rows does the final SELECT query return?

price: 49.99

The update was wrapped in a transaction that was rolled back, so the price reverted to its original value of 49.99.

What rows does the final SELECT query return?

(No rows)

The transaction was committed successfully, making both deletions permanent.

Practice tasks

Rollback a mistake

You accidentally deleted all customers! Add the command needed to undo the deletion before it becomes permanent.

Challenge

Complete the transfer

Write a transaction that starts a block, updates the status of order id 3 to 'cancelled', then commits the changes.

Continue learning

Previous: UPDATE, DELETE & Returning

Return to SQL Roadmap