BEGIN / START TRANSACTION example
We try reducing the stock and then decide to undo it:
BEGIN TRANSACTION;
UPDATE products
SET stock = stock - 1
WHERE id = 1;
SELECT id, name, stock
FROM products
WHERE id = 1;
ROLLBACK;After ROLLBACK, the stock goes back to 18. Had we run COMMIT, the change would have been committed.
Check the result with small data
We start with two units saved and try a change inside BEGIN.
CREATE TABLE demo_stock (id INTEGER, units INTEGER);
INSERT INTO demo_stock VALUES (1, 2);
BEGIN;
UPDATE demo_stock SET units = 1 WHERE id = 1;
ROLLBACK;
SELECT units FROM demo_stock WHERE id = 1;| units |
|---|
| 2 |
After ROLLBACK we see two units again: the change made in the transaction was undone. BEGIN on its own commits nothing.
Check your understanding: What value would you see if you used COMMIT instead of ROLLBACK?
Show answer
1. COMMIT would confirm the UPDATE and the final SELECT would show one unit instead of two.
How BEGIN / START TRANSACTION is used
The exact syntax and options depend on the engine and the client. PostgreSQL accepts BEGIN as a functional equivalent of START TRANSACTION; MySQL documents START TRANSACTION and its synonyms; SQLite lets you start one manually with BEGIN; SQL Server uses BEGIN TRANSACTION and a BEGIN on its own only marks a block of statements.
Common mix-ups with BEGIN / START TRANSACTION
Opening one and forgetting to close it
BEGIN;
UPDATE products SET stock = stock - 1 WHERE id = 1;
-- Missing COMMIT or ROLLBACKAn open transaction can hold on to locks or resources and hold up other sessions. Your code must close it on every path, including when an error occurs.
Mark where an all-or-nothing operation starts and ends
Open a transaction when several operations must succeed or fail together. Reserving stock and recording the order need a plan for a failure halfway through: commit both or undo the pending changes. Opening the transaction does not add missing validation or fix a wrong filter; you still need to check the affected rows and the process constraints.
All the statements must run on the same connection. If an application takes different connections from a pool, the BEGIN issued on one does not group writes sent on another. Also check the client's autocommit mode: there may be an implicit transaction or a dedicated API for opening and closing it.
Plan for both the success path and the failure path. An exception does not always mean a full rollback on every engine and client. Close the unit of work explicitly and do not keep it open while waiting for a person to respond. In SQLite, the BEGIN modes affect when write access is requested, but they do not make concurrent writes independent of each other. Test a failure after the first change, not just the sequence that always succeeds.
Technical questions: SQLite: transactions (opens in a new tab).