Try Changes in a Transaction
Part of the SQL Foundations section of Coddy's PostgreSQL journey. Lesson 19 of 22.
BEGIN starts a transaction: a group of changes that can succeed together. COMMIT keeps them and ROLLBACK discards them. You can inspect changes inside a transaction before deciding.
Input table products:
id | name | category | price | stock | active | note |
|---|---|---|---|---|---|---|
1 | Map | travel | 12 | 5 | True | NULL |
2 | Notebook | books | 8 | 0 | True | Recycled |
3 | Atlas | books | 24 | 3 | False | NULL |
4 | Mug | home | 12 | 8 | True | Blue |
5 | lamp | home | 30 | 2 | False | Clearance |
6 | Mini map | travel | 6 | 10 | True | NULL |
BEGIN;
UPDATE products SET stock = 0 WHERE id = 1;
ROLLBACK;
SELECT id, stock FROM products WHERE id = 1;The final stock is still 5 because the rollback undid the update. Place the result SELECT after ROLLBACK when you want to inspect restored data. This is a local exercise database, not the store itself.
BEGIN groups work; COMMIT saves it and ROLLBACK undoes it. End with a query when the exercise needs a result table.
Challenge
MediumStart a transaction, change product id 4 stock to 99, roll back, then return id and stock for id 4 to verify restoration.
The input tables are shown in the test panel. Each run starts from fresh data. Return the named columns in the stated order; do not hard-code the displayed rows.
Try it yourself
-- Write your SQL here.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in SQL Foundations
1Types and Casts
Convert with CastsExact Decimal DivisionBoolean ValuesCreate a Typed TableActive Price Review4Change Data Safely
Insert and ReturnUpdate Selected RowsDelete and ReturnTry Changes in a TransactionReceive and VerifyPractice on your own: PostgreSQL playground