Part 13 / Topic 6 of 8
Procedures
Functions compute inside a statement and live inside its transaction. Procedures (PostgreSQL 11+) are invoked standalone with CALL — and uniquely, they may COMMIT and ROLLBACK inside, slicing long maintenance work into batches:
CREATE PROCEDURE archive_cancelled()
LANGUAGE plpgsql
AS $$
DECLARE
v_count integer;
BEGIN
-- EXCLUDING IDENTITY: the archive stores ids, it must not mint them.
CREATE TABLE IF NOT EXISTS orders_archive (LIKE orders INCLUDING ALL EXCLUDING IDENTITY);
WITH moved AS (
DELETE FROM orders
WHERE status = 'cancelled'
AND NOT EXISTS (SELECT 1 FROM order_items oi WHERE oi.order_id = orders.order_id)
RETURNING *
)
INSERT INTO orders_archive SELECT * FROM moved;
GET DIAGNOSTICS v_count = ROW_COUNT;
RAISE NOTICE 'archived % cancelled order(s)', v_count;
END;
$$;
CALL archive_cancelled();
CREATE PROCEDURE
NOTICE: archived 0 cancelled order(s)
CALL
Zero rows moved — shopdb's one cancelled order still has lines, so the guard held it back (deliberately: archiving a parent while its children point at the live table would break the foreign key — a DELETE ... RETURNING feeding an INSERT is the move idiom, and the NOT EXISTS keeps it honest). Function vs procedure in one line: functions return values into queries; procedures orchestrate work, transactions included.
🧪 Quick quiz — answer from memory, then check.
- What can a procedure do that a function never can?
- How do you run one?
Show the answers
- Control transactions — COMMIT/ROLLBACK inside its body (when called outside an explicit transaction).
CALL procedure_name(args);
Done here? The practice set for Part 13 — 6 exercises with solutions — is on the part page.