bhylu.com

Advertisements

SQL Savepoints

A savepoint marks a position inside a transaction. It lets you roll back a later part while keeping earlier uncommitted work, which can help with optional steps or batches that have a clear partial-failure policy.

Understand the idea

The first stock adjustment happens before the savepoint. The second happens after it and is rolled back. Releasing a savepoint removes that marker; it does not replace the outer transaction's final commit. Keep the nesting simple and use your driver's transaction facilities consistently so application and database state agree.

Where to try it

Run this example in the SQL playground. The lesson link loads the shop tables and sample rows before this query. Select Run when you are ready. Every run starts fresh, so your changes do not affect the website or a previous run.

SQLite sample data · MySQL / MariaDB sample data · See the sample tables

A worked example

SQLite

BEGIN;
UPDATE products SET stock = stock + 2 WHERE product_id = 1;
SAVEPOINT optional_step;
UPDATE products SET stock = stock + 10 WHERE product_id = 2;
ROLLBACK TO optional_step;
RELEASE optional_step;
COMMIT;
SELECT product_id, stock FROM products WHERE product_id IN (1, 2) ORDER BY product_id;

Read the result

Product 1 ends at 42, while product 2 stays at 8. Only the work after optional_step was undone before the outer transaction committed.

Try one change

Add a third optional adjustment after releasing the savepoint. Decide whether it belongs inside the same all-or-nothing business operation.