Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 150/ 160
08. Transactions, Security & Production SQL Administration

Stored Procedures & Transaction Control Inside Procedures

Use procedures for multi-statement workflows that can manage transactions.

IntermediatePROCEDURE · CALL3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

A batching procedure (PostgreSQL 11+)Query example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sqlReadable preview
1CREATE PROCEDURE archive_old_orders(cutoff timestamptz)2LANGUAGE plpgsql3AS $$4DECLARE n int;5BEGIN6LOOP7WITH moved8AS (DELETE9FROM orders10WHERE id IN (11SELECT id12FROM orders13WHERE created_at < cutoff14LIMIT 10000)15RETURNING *)16INSERT INTO orders_archive17SELECT *18FROM moved;1920GET DIAGNOSTICS n = ROW_COUNT;21COMMIT;2223EXIT WHEN n = 0;24END LOOP;25END $$;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/25
3OutputInspect the representative rows, affected-row count, plan, or command status.
Procedure definition status
CREATE PROCEDURE

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.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Granting a controlled operationQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1REVOKE ALL ON orders2FROM3  support_role;45GRANT6EXECUTE ON PROCEDURE refund_order (bigint) TO support_role;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/6
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative privilege responses
REVOKE GRANT

Note: PostgreSQL-style command tags; support_role gains EXECUTE on the procedure while direct DML remains revoked.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Design

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.

Focus at this step

value → function · workflow → procedure

What to watch at this step
Default
app code for business rules
Tip: use ← → to move between steps

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

Stored procedure
Best for: Batch jobs and multi-step operations that need transaction control

Strengths: One round trip, runs next to the data, can commit in batches.

Watch out: Harder to test and debug; dialect-specific.

Function
Best for: Reusable calculations used in queries

Strengths: Composable inside SELECT, WHERE and indexes.

Watch out: No transaction control; can hide expensive per-row work.

Application code
Best for: Business rules that change often or call external services

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?
Interview tip: Give the technical difference (CALL and transaction control vs returning values in queries), then a balanced opinion on when to use them. Interviewers want to hear the trade-offs, not a blanket yes or no.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
User-Defined Functions (PL/pgSQL / T-SQL) & Control Flow
Next topic
Triggers (BEFORE / AFTER, FOR EACH ROW / STATEMENT) & Audit Logging