SQL · Queries that survive scale

What are stored procedures and when should you use them?

Mediumstored proceduresplpgsqlbusiness logicUpdated Oct 2026
Quiz this track

Short answer

A stored procedure is database-side code that runs inside the database. It can reduce round trips and centralize data-heavy logic, but it is harder to version and test than application code.

Stored procedures and functions live in the database and are invoked by name. They are useful for multi-step data operations that benefit from running close to the data, especially when they avoid many network round trips.

sql
CREATE PROCEDURE transfer_funds(
  p_from BIGINT,
  p_to BIGINT,
  p_amount NUMERIC
)
LANGUAGE plpgsql
AS $$
BEGIN
  UPDATE accounts
  SET balance = balance - p_amount
  WHERE id = p_from;

  UPDATE accounts
  SET balance = balance + p_amount
  WHERE id = p_to;
END;
$$;

Trade-offs

  • Fewer network round trips for multi-step logic
  • Centralized enforcement for operations used by several services
  • Database-specific language and tooling, which reduces portability
  • Harder to unit test, review, and deploy than application code
  • Versioning and rollback need a migration process
  • Security definer functions can bypass caller permissions if misused

Keep business rules in application code when they change often or need rich testing. Use procedures for stable, data-intensive operations where locality and atomicity matter more than portability.

Check whether the engine supports transaction control inside a procedure. PostgreSQL procedures can commit, while functions usually cannot. That affects how you design retries and batch work.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1What is the difference between a stored procedure and a function?
  2. 2How do you test and version stored procedures?
  3. 3What security risks come with SECURITY DEFINER?
  4. 4When would you keep logic in the application instead?

Say it in the interview

A stored procedure is code that runs inside the database. I use it when a data-heavy multi-step operation benefits from avoiding round trips or needs centralized enforcement. The trade-off is portability, testing, and deployment complexity. I keep fast-changing business rules in the application and reserve procedures for stable operations where database locality and atomicity are the main win.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live SQL mock interview and get scored feedback on depth, clarity and confidence.