Grouping changes with transactions #
Every INSERT, UPDATE, and DELETE you have written so far ran on its own. But sometimes several statements only make sense as a group — for example, moving money between two bank accounts needs both the withdrawal and the deposit to happen together. If only one of them succeeded, the data would be left in a broken state.
A transaction groups statements together so that either all of them take effect, or none of them do:
BEGIN;
UPDATE table_name
SET
column_name = new_value
WHERE
condition;
COMMIT;
BEGIN: Starts a new transaction.COMMIT: Saves every change made sinceBEGIN, permanently.ROLLBACK: Instead ofCOMMIT, this undoes every change made sinceBEGIN, as if none of it ever happened.
ROLLBACK is what makes transactions useful for safety: if something goes wrong partway through (or you simply change your mind), you can back out of every change at once instead of trying to manually undo each statement.
BEGIN;
UPDATE table_name
SET
column_name = new_value
WHERE
condition;
ROLLBACK;
Exercise #
Write a command that starts a transaction, changes the price of the product with id 1 to 999.99, and then rolls the transaction back, so that the product's price ends up exactly the same as it was before.
Tests #
- Your command uses both
BEGINandROLLBACK. - After running your command, the
priceof the product withid1is unchanged from its original value.
Solution
BEGIN;
UPDATE products
SET
price = 999.99
WHERE
id = 1;
ROLLBACK;
Basic Data Retrieval
Filtering Data
Aggregating Data
Joining Tables
Creating and Managing Tables
Transactions and Data Integrity