Sub topic 10
Wrapping Changes in a Transaction
Assume you already know how to use SELECT with WHERE, and that you understand tables, rows, primary keys, and foreign keys. A transaction groups several database operations into one unit. You can keep all of the changes with COMMIT or undo them with ROLLBACK.
Transactions protect related changes from being left half-finished. For example, cancelling an order might require changing the order status and recording an audit row. Both changes should succeed together. If either change fails, the database should keep neither change.
The transaction lifecycle
Start a transaction with BEGIN. Run the data-changing statements. Inspect the results if needed. Use COMMIT to make the changes permanent.
BEGIN;
UPDATE orders
SET status = 'cancelled'
WHERE id = 100;
SELECT id, status
FROM orders
WHERE id = 100;
COMMIT;The UPDATE is visible within the transaction. The COMMIT ends the transaction and preserves the new status. If you discover an error before committing, use ROLLBACK instead.
BEGIN;
UPDATE orders
SET status = 'cancelled'
WHERE id = 100;
SELECT id, status
FROM orders
WHERE id = 100;
ROLLBACK;After the rollback, order 100 has its original status. A rollback reverses changes made during the current transaction. It does not reverse changes that were committed earlier.
Transactions and errors
A transaction is especially useful when multiple statements depend on each other. Suppose you create an order and then add its items. If adding an item fails because its product does not exist, committing the new order alone could leave incomplete data.
BEGIN;
INSERT INTO orders (id, customer_id, total)
VALUES (101, 1, 25.00);
INSERT INTO order_items (order_id, product_id, quantity)
VALUES (101, 999, 1);
COMMIT;If the second statement violates a foreign key, the database reports an error. In many systems, the transaction is then marked as failed. Issue ROLLBACK to end it and remove the successful first insert. Do not assume that a later COMMIT will repair a failed transaction.
Some database clients use automatic commit mode. In that mode, each successful statement is committed immediately unless you explicitly start a transaction. Check your client settings before relying on rollback.
SQL Server commonly uses BEGIN TRANSACTION instead of BEGIN. The ideas remain the same: group changes, inspect them, then commit or roll back.
Exercise
You run an UPDATE and discover that its WHERE condition matched too many rows. What should you do if the transaction is still open?
Show answer
Run ROLLBACK, then correct the WHERE condition and try again.