COMMIT inside a procedure in SQL
Only procedures may commit mid-run, releasing work batch by batch.
-- Only procedures may COMMIT mid-run, releasing work batch by batch.
CREATE PROCEDURE archive_canceled()
LANGUAGE plpgsql
AS $$
DECLARE
doomed RECORD;
BEGIN
FOR doomed IN
SELECT id
FROM orders
WHERE status = 'canceled'
LOOP
UPDATE orders
SET status = 'archived'
WHERE id = doomed.id;
COMMIT;
END LOOP;
END;
$$;
CALL archive_canceled();
SELECT id, status
FROM orders
WHERE status = 'archived';
How it works
- The
FOR ... IN SELECTloop visits each canceled order. - Each pass archives one order and
COMMITs it before the next begins. - A crash mid-run keeps every batch already committed — the point of the pattern.
Keywords and builtins used here
ASBEGINCALLCOMMITCREATEDECLAREENDFORFROMINLANGUAGEPROCEDURESELECTSETUPDATEWHERE
The run, in numbers
- Lines
- 25
- Characters to type
- 395
- Tokens
- 67
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 62 seconds.
Step 3 of 4 in Procedures & transactions, step 11 of 23 in PostgreSQL Stored Procedures.