Stored Procedures & Transaction Control Inside Procedures
Use procedures for multi-statement workflows that can manage transactions.
In plain words
A stored procedure is a saved list of SQL steps the database can run for you in one go.
Think of it like…
A procedure is a recipe card kept in the kitchen: instead of the waiter shouting each step to the cook, they say "make recipe 12" and the kitchen does everything, including deciding when each batch is finished.
Where you’ve seen it
A nightly job archives old orders in batches of 10,000, committing after each batch so locks stay short: CALL archive_old_orders(now() - interval '2 years');. Doing that from the application would mean thousands of round trips.
Words you’ll hear
- Procedure
- Saved routine run with CALL; can include transaction control.
- Function
- Saved routine that returns a value or table; usable in queries; no COMMIT.
- PL/pgSQL / T-SQL
- Procedural languages for writing routines in PostgreSQL and SQL Server.
- SECURITY DEFINER
- Runs with the owner's privileges, so callers don't need direct table access.
Visual diagram
Theory & example queries
Procedures vs functions
Functions compute and return something, a scalar or a set of rows, and can appear in SELECT, WHERE or FROM: SELECT customer_lifetime_value(id) FROM customers. They run inside the caller's transaction and can't commit or roll it back.
Procedures are invoked with CALL and don't return a value in the same way (they can use OUT parameters). Their distinguishing feature is transaction control: a PostgreSQL procedure can COMMIT or ROLLBACK part-way, as long as the CALL isn't itself inside an explicit transaction block, which makes them suited to long batch jobs.
| id | customer_id | status | amount | coupon_code |
|---|---|---|---|---|
| 101 | 1 | paid | 249 | NULL |
| 102 | 2 | paid | 120 | WELCOME10 |
| 103 | 1 | shipped | 89.5 | NULL |
CREATE PROCEDURE archive_old_orders(cutoff timestamptz)LANGUAGE plpgsqlAS $$DECLARE n int;BEGINLOOPWITH movedAS (DELETEFROM ordersWHERE id IN (SELECT idFROM ordersWHERE created_at < cutoffLIMIT 10000)RETURNING *)INSERT INTO orders_archiveSELECT *FROM moved;GET DIAGNOSTICS n = ROW_COUNT;COMMIT;EXIT WHEN n = 0;END LOOP;END $$;PostgreSQL is the lesson baseline unless noted otherwise.
Identify the table or database object the statement will modify.
Procedure definition status
Note: The output reports creation only. Archival row counts and the number of loop batches appear when the procedure is called and depend on the data.
Key takeaway: Functions return values inside queries; procedures run workflows and can commit.
When database logic is worth it
Good fits: set-based batch jobs that would otherwise make thousands of round trips, operations that must be identical for every client (often exposed with EXECUTE grants and SECURITY DEFINER so callers can't touch tables directly), and maintenance tasks run by schedulers.
Costs: the logic lives outside your application's code review, tests and deployment pipeline unless you deliberately manage it with migrations; debugging tools are weaker; and procedural SQL is dialect-specific, which ties you to one database. Many teams keep business rules in the application and use procedures for data-heavy operations only.
REVOKE ALL ON ordersFROM support_role;GRANTEXECUTE ON PROCEDURE refund_order (bigint) TO support_role;PostgreSQL is the lesson baseline unless noted otherwise.
Read this line together with the surrounding statement as part of the same SQL expression.
Representative privilege responses
Note: PostgreSQL-style command tags; support_role gains EXECUTE on the procedure while direct DML remains revoked.
Support can issue refunds through the procedure, but can't edit orders freely.
Key takeaway: Use procedures for data-heavy or tightly controlled operations, and version them like code.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Decide: procedure, function or app code?
Returning a value used in queries means a function. A multi-step job with commits means a procedure. Business rules that change often usually stay in the application.
value → function · workflow → procedure
When to use it & trade-offs
What it is
A stored procedure is named code saved in the database and run with CALL name(args). It can execute many statements, use variables, loops and conditions, and (unlike a function) control transactions, committing partway through a long job. A function returns a value or table and can be used inside SELECT, but can't commit. In PostgreSQL, procedures arrived in version 11; MySQL, SQL Server and Oracle have had them for decades.
Why it matters: Procedures cut round trips for multi-step operations, keep data-heavy logic next to the data, and let you grant EXECUTE on a controlled operation instead of direct table access. They also make logic harder to version, test and debug. "Procedure vs function" and "should business logic live in the database?" are common interview questions.
When to reach for it
- Batch archiving, cleanup and backfills
- Exposing tightly controlled operations through EXECUTE grants
- Reducing round trips for multi-statement operations
When to avoid or be careful
- Putting fast-changing business logic only in the database
- Row-by-row loops where one set-based statement would do
- Routines created by hand in production and missing from version control
Procedure vs function vs application code
Strengths: One round trip, runs next to the data, can commit in batches.
Watch out: Harder to test and debug; dialect-specific.
Strengths: Composable inside SELECT, WHERE and indexes.
Watch out: No transaction control; can hide expensive per-row work.
Strengths: Normal tooling: tests, code review, debugging, logging.
Watch out: More round trips for data-heavy operations.
Interview signals & numbers to know
When this topic comes up
- “Stored procedure vs function”
- “Should business logic be in the database?”
- Large batch jobs
- CALL statements
- T-SQL or PL/pgSQL codebases
Benchmarks & rules of thumb
- PostgreSQL 11
- CREATE PROCEDURE introduced
- CALL
- how procedures are invoked
- 1
- round trip for a whole multi-step job
Common mistakes & follow-ups
Common interview mistakes
- Trying to COMMIT inside a PostgreSQL function and getting an error.
- Calling a committing procedure inside an explicit BEGIN block, where transaction control isn't allowed.
- Writing a procedure that loops over millions of rows one at a time.
Likely interviewer follow-ups
- What's the difference between a stored procedure and a function?
- What are the pros and cons of business logic in stored procedures?
- How would you delete millions of old rows in batches without long locks?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Stored Procedures & Transaction Control Inside Procedures with hands-on SQL practice and interview Q&A.