Stored Procedures

Difficulty: Intermediate

Question

What are stored procedures, and what are the pros and cons of putting business logic in them instead of in your application code?

Answer

A stored procedure is a named block of SQL plus procedural logic (variables, loops, conditionals) that is saved inside the database and executed there with a single call, such as CALL transfer_funds(...). The main benefits are fewer network round trips, a single enforced path for critical operations, and tighter permissions. The main costs are logic that is harder to test, version and scale, and code that ties you to one database vendor.

How a stored procedure actually runs

The client sends one statement, like CALL place_order(42, 'SKU-9'). The database parses it, runs every statement inside the procedure on the server, and returns only the final result. If the same work were done from the application, each SELECT, UPDATE and INSERT would be a separate round trip over the network.

Each database has its own language:

  • PostgreSQL: PL/pgSQL. CREATE FUNCTION returns a value; CREATE PROCEDURE (added in PostgreSQL 11) is invoked with CALL and can run COMMIT or ROLLBACK inside its body.
  • MySQL: CREATE PROCEDURE with its own SQL/PSM style syntax.
  • SQL Server: T-SQL, where procedures are the traditional way to expose data access.
  • Oracle: PL/SQL, often organised into packages.

The advantages

  • Fewer round trips. A five-step workflow becomes one call. This matters most when the app server and database are far apart or the workflow loops over many rows.
  • One enforced code path. If every service must call debit_wallet() instead of writing to the wallets table directly, rules like "balance can never go negative" cannot be bypassed by a buggy microservice.
  • Least-privilege security. You can GRANT EXECUTE on a procedure while denying direct table access. In PostgreSQL a SECURITY DEFINER function runs with the owner's rights, so the caller never needs table permissions.
  • Data stays close to compute. Set-based work over millions of rows (bulk recalculation, archiving) is often faster inside the database than pulling rows into the app.

The disadvantages

  • Version control and deployment. Procedure code lives in the database, so it must be shipped through migrations (Flyway, Liquibase, Prisma migrations). Teams that forget this end up with "which version is running in prod?" problems.
  • Testing and debugging. Unit testing PL/pgSQL or T-SQL is possible (pgTAP, tSQLt) but far less common and less pleasant than testing Java or TypeScript.
  • Scaling the wrong tier. App servers scale horizontally by adding pods. The primary database is usually a single machine, so CPU-heavy logic there competes with every query.
  • Vendor lock-in. PL/pgSQL does not run on MySQL. Migrating databases means rewriting the logic.
  • Split business logic. Half the rules in the app and half in the database makes onboarding and code review harder.

When teams use them today

Good fitPoor fit
Atomic multi-row money movementsGeneral CRUD behind a REST API
Bulk data maintenance jobsLogic that changes every sprint
Legacy enterprise systems built around themLogic that calls external APIs
Exposing a narrow, audited API to reporting usersTeams with no DBA or migration discipline

Most modern product companies keep business rules in the application and use procedures selectively, for example a single function that atomically moves money between two ledger rows. Banks and older enterprise systems often still run large parts of their logic as procedures.

Gotchas interviewers probe

  • Procedures do not automatically prevent SQL injection. Building a string and running it with EXECUTE (PostgreSQL) or sp_executesql without parameters is still injectable.
  • Plan caching differs by vendor. SQL Server caches procedure plans, which can cause parameter sniffing problems; PL/pgSQL caches plans per session for its statements.
  • Long procedures holding locks for the whole call can increase contention.

Code examples

PostgreSQL procedure for an atomic wallet transfer

-- Amounts stored in paise to avoid floating point errors
CREATE OR REPLACE PROCEDURE transfer_funds(
  p_from BIGINT, p_to BIGINT, p_amount_paise BIGINT
)
LANGUAGE plpgsql
AS $
BEGIN
  -- Lock both rows in a fixed order to avoid deadlocks
  PERFORM 1 FROM wallets
   WHERE id IN (p_from, p_to)
   ORDER BY id
   FOR UPDATE;

  UPDATE wallets SET balance_paise = balance_paise - p_amount_paise
   WHERE id = p_from AND balance_paise >= p_amount_paise;
  IF NOT FOUND THEN
    RAISE EXCEPTION 'Insufficient balance in wallet %', p_from;
  END IF;

  UPDATE wallets SET balance_paise = balance_paise + p_amount_paise
   WHERE id = p_to;
END;
$;

-- One round trip from the app
CALL transfer_funds(101, 202, 50000);  -- Rs 500

The debit, credit and balance check run as one server-side unit. If the balance is too low, the exception rolls back the whole call.

Granting execute without table access

REVOKE ALL ON wallets FROM app_user;
GRANT EXECUTE ON PROCEDURE transfer_funds(BIGINT, BIGINT, BIGINT) TO app_user;

-- For this to work without table rights, the routine
-- must run with its owner's privileges:
ALTER PROCEDURE transfer_funds(BIGINT, BIGINT, BIGINT) SECURITY DEFINER;
ALTER PROCEDURE transfer_funds(BIGINT, BIGINT, BIGINT) SET search_path = public;

The app role can only move money through the procedure. Pinning search_path is the standard hardening step for SECURITY DEFINER routines.

Key points

  • Stored procedures run on the database server and cut network round trips for multi-step work
  • They enforce a single code path and enable GRANT EXECUTE style least-privilege access
  • Costs: harder testing, migration-based deployment, vendor lock-in, and load on the hardest tier to scale
  • PostgreSQL CREATE PROCEDURE (v11+) supports transaction control; functions do not
  • Dynamic SQL inside a procedure can still be vulnerable to SQL injection

Common follow-up questions

  • What is the difference between a function and a procedure in PostgreSQL?
  • How would you version control and deploy stored procedures safely?
  • What is parameter sniffing in SQL Server and how do you fix it?
  • Would you put payment logic in a procedure or in a service? Why?

Interview tips

  • Give a balanced answer and finish with when you would personally use one, such as atomic ledger updates
  • Mention the scaling argument: app servers scale out easily, the primary database usually does not
  • Avoid claiming procedures are always faster or always secure; name the dynamic SQL exception

Concepts covered

Stored Procedures, PL/pgSQL, Network Round Trips, SECURITY DEFINER, Vendor Lock-in

More Database Design questions