Transaction with Isolation Levels
Demonstrates explicit transaction control with SET TRANSACTION isolation levels, savepoints, and conditional rollback for safe multi-step operations.
Code
BEGIN;
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
-- Step 1: Check available stock
SELECT stock_quantity INTO v_stock
FROM products
WHERE product_id = 101
FOR UPDATE;
IF v_stock < 5 THEN
ROLLBACK;
RAISE EXCEPTION 'Insufficient stock for product 101';
END IF;
-- Step 2: Create order
INSERT INTO orders (customer_id, order_date, status)
VALUES (p_customer_id, CURRENT_TIMESTAMP, 'pending')
RETURNING order_id INTO v_order_id;
-- Savepoint before risky operation
SAVEPOINT before_inventory_update;
-- Step 3: Update inventory
UPDATE products
SET stock_quantity = stock_quantity - 5
WHERE product_id = 101;
-- Step 4: Add order items
INSERT INTO order_items (order_id, product_id, quantity, unit_price)
VALUES (v_order_id, 101, 5, 29.99);
COMMIT;
EXCEPTION
WHEN OTHERS THEN
ROLLBACK TO SAVEPOINT before_inventory_update;
RAISE;
END;What the code does
The script mixes SELECT, INSERT and UPDATE across v_stock, products, orders, v_order_id and order_items to stage one checkout.
Breaking the statements into their working parts: a WHERE clause that limits which rows the statement affects; a RETURNING clause that hands the affected rows back to the caller.
Applying it
The v_stock table is the working surface here.
Statements that matter
SELECT stock_quantity INTO v_stock
FROM products
WHERE product_id = 101
FOR UPDATE;
UPDATE products
SET stock_quantity = stock_quantity - 5
WHERE product_id = 101;
INSERT INTO orders (customer_id, order_date, status)
VALUES (p_customer_id, CURRENT_TIMESTAMP, 'pending')
RETURNING order_id INTO v_order_id;
Interactive Tools for This Topic
FAQ
- Which tables does this file reference?
- The references are `v_stock`, `products`, `orders`, `v_order_id`, `order_items`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.