Stored Procedures — Complete Guide
Stored Procedures — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of PostgreSQL Tutorial on Toolliyo Academy.
On this page
PostgreSQL Tutorial · Lesson 42 of 100
Stored Procedures
SQL ✓ → Advanced
Advanced · 2 — Production · ~6 min · PostgreSQL — Functions & Automation
What is this?
Procedures (CREATE PROCEDURE) are transaction-aware routines that can COMMIT or ROLLBACK internally — PostgreSQL 11+. Functions cannot commit; procedures fit multi-step batch workflows.
Why should you care?
PostgresVerse end-of-day settlement runs procedure that posts batches and commits per chunk without one giant transaction.
See it live — copy this example
Run in pgAdmin or psql.
CREATE OR REPLACE PROCEDURE settle_pending_orders(batch_size int)
LANGUAGE plpgsql
AS $$
BEGIN
UPDATE orders SET status = 'settled'
WHERE order_id IN (
SELECT order_id FROM orders
WHERE status = 'confirmed'
LIMIT batch_size
);
COMMIT;
END;
$$;
CALL settle_pending_orders(100);
What happened?
- Procedure updates up to 100 confirmed orders to settled then COMMIT inside body.
- CALL executes it — unlike SELECT function().
Practice next
- Create procedure in PostgresVerse.
- Seed confirmed orders and CALL with small batch.
- Verify status changes and transaction committed.
- Add second COMMIT loop with FOR batch in plpgsql.
- Wrap CALL in outer transaction and observe interaction.
Remember
Procedures use CALL, not SELECT. Can commit/rollback sub-steps. Good for ETL chunks and maintenance jobs.
PostgresVerse settlement job
Cron CALL settle_pending_orders(500) every minute during reconciliation window.
Outcome: Long lock held on entire orders table avoided.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!