Combined review · full transaction

INSERT, UPDATE and DELETE: a SQL exercise with ROLLBACK

Choose the right operation, and protect your changes with a check beforehand and a transaction where the engine allows it.

25 minIntermediate levelFirst you need: INSERT, UPDATE, DELETE and transactions

Have a go before opening the examples

First you need: Add rows with INSERT, Update rows with UPDATE, Delete rows with DELETE, Control changes with COMMIT and ROLLBACK. If any of the groundwork is missing, go back to that lesson and then carry on from here.

Complete each task, predict a row and explain the decision that produces it. Results are saved per activity.

Practice

Rehearse three operations and undo them

Not started

The inventory_review table already contains Keyboard (id 1, stock 5) and Cable (id 2, stock 8). Open a transaction, add Adapter (id 3, stock 4), reduce the stock of id 1 to 3, query id 2 before deleting it, delete it, check id, name and stock for the remaining rows, and undo the rehearsal.

We check the full final state: the change you were asked to make and that every other row is untouched. Review the output of each statement too.

The table for this activity is already set up. Look at its data; you do not need to create it again.

Every attempt resets the data, so include all the steps you need to check in a single attempt.

View tables and data

Open this panel to see the full data.

Run the full example in SQLite too

Download the prepared file. Open an empty SQLite database and import the file as a script. If you use the sqlite3 shell, type .read name-del-archivo.sql. Read the checking SELECTs in the order they appear in the file. To start again from scratch, open another empty database and import the same script again.

PRAGMA inspects the schema in SQLite and is not available in the teaching lab. The activities on this page already set up their own tables and reset the data on every attempt.

To finish: explain what a row represents, which requirement you checked and what would change if the rule changed.

See worked examples and checks

By the end, you will be able to

  • Choose between adding, changing or deleting rows.
  • Turn the condition for a change into a SELECT that checks it first.
  • Use COMMIT and ROLLBACK deliberately.

Three operations, three intents

OperationQuestion it answersMain risk
INSERTWhich new row should exist?Leaving out columns, duplicating keys or breaking constraints.
UPDATEWhich values change in existing rows?Changing more rows than intended because of an incomplete condition.
DELETEWhich rows should stop existing?Deleting information that cannot be recovered, or that other tables depend on.

A safe process in four steps

  1. Write a SELECT with the same condition that you will use in UPDATE or DELETE.
  2. Check the number of rows and which rows they are.
  3. Open an explicit transaction when you need to group several changes.
  4. Check the result and finish with COMMIT or ROLLBACK.

Do not rely on ROLLBACK without knowing the engine and the type of table. Some data definition operations and some configurations cannot be undone in the same way. Practise with test data first.

Reversible example

This block adds a test product, reduces its stock and checks the result. It ends with ROLLBACK, so the product is not saved.

SQL
BEGIN;

INSERT INTO products
  (id, name, category, category_id, price, stock)
VALUES
  (11, 'HDMI Adapter', 'Accessories', 1, 19.90, 5);

SELECT id, name, stock
FROM products
WHERE id = 11;

UPDATE products
SET stock = stock - 2
WHERE id = 11
  AND stock >= 2;

SELECT id, name, stock
FROM products
WHERE id = 11;

ROLLBACK;
Checking before and after the UPDATE
stepidnamestock
after INSERT11HDMI Adapter5
after UPDATE11HDMI Adapter3

Full exercise: add, change and delete, then undo

Reproduce this case in an empty SQLite test database. The table has its own name to keep it apart from the course products. Create the two rows first; that setup sits outside the transaction you are going to undo.

SQL · SQLite
CREATE TABLE inventory_review (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  stock INTEGER NOT NULL CHECK (stock >= 0)
);
INSERT INTO inventory_review (id, name, stock)
VALUES (1, 'Keyboard', 5), (2, 'Cable', 8);

Before running it, predict which rows will remain after the cable is deleted, and which will reappear after ROLLBACK. The SELECT before DELETE lets you check the row that is about to be deleted.

SQL · SQLite
BEGIN;
INSERT INTO inventory_review (id, name, stock)
VALUES (3, 'Adapter', 4);

UPDATE inventory_review SET stock = stock - 2
WHERE id = 1 AND stock >= 2;

SELECT id, name, stock FROM inventory_review WHERE id = 2;
DELETE FROM inventory_review WHERE id = 2;

SELECT id, name, stock FROM inventory_review ORDER BY id;
ROLLBACK;
SELECT id, name, stock FROM inventory_review ORDER BY id;
Compare the two full results
stepidnamestock
before ROLLBACK1Keyboard3
before ROLLBACK3Adapter4
after ROLLBACK1Keyboard5
after ROLLBACK2Cable8

Three changes are undone together: the inserted adapter disappears, the keyboard gets its stock back and the cable row returns. The table and its two original rows remain, because they were created before BEGIN. With COMMIT instead of ROLLBACK, the changes would be committed.

Download the full exercise for SQLite. The site's teaching editor supports a subset of SQL; run this file with SQLite to reproduce the table creation too. In MySQL you use START TRANSACTION with a transactional table; do not assume that rolling back these row changes extends to any DDL operation.

Two mistakes you should spot

UPDATE without a sufficient condition

UPDATE products SET stock = 0;

The statement changes every row. Before running it, check the selection with SELECT id, name FROM products WHERE ....

DELETE used to «clear a value»

DELETE FROM customers WHERE id = 4;

DELETE removes the whole row. To change just one attribute, use UPDATE and check the column constraints.

Key takeaways

  • Check the affected rows first.
  • A transaction ends explicitly with COMMIT or ROLLBACK.
  • What can be rolled back depends on the engine, the type of operation and the configuration.

Suggested path

Checklist before changing data

Before running an operation that changes rows, break the decision into three questions: which rows should be affected, which new value should remain, and how you would go back if the result were not what you expected. For UPDATE and DELETE, turn the condition into a SELECT first and review the rows it returns. For INSERT, check the required columns, keys and defaults.

In a real database, correct syntax is only part of safety. Constraints, foreign keys, triggers, permissions and transactions may also come into play. Practise the mental pattern here and, before applying it in production, check the behaviour in a controlled environment against your engine's documentation.