Question presented to candidate: "What is a stored procedure? How is it different from a function, and when would you put logic in the database instead of in the application?"
What a strong answer should cover:
- A stored procedure is named code stored in the database (SQL plus control flow such as variables,
IF, loops, error handling) that clients run with one call,CALL transfer(1, 3, 30) - Procedure vs function in PostgreSQL: a function returns a value and is used inside queries (
SELECT ... FROM f()); a procedure is invoked withCALL, returns results only throughINOUTparameters, and (since PostgreSQL 11) mayCOMMIT/ROLLBACKinside - Benefits: one round trip for a multi-step operation, logic and invariants enforced next to the data for every client, permission control with
GRANT EXECUTEandSECURITY DEFINER - Costs: harder to version, test, debug and deploy than application code; vendor lock-in (PL/pgSQL, T-SQL, MySQL syntax all differ); database CPU is the hardest tier to scale
- Correct the myth: "precompiled" is not a unique advantage; PL/pgSQL caches statement plans per session, and prepared statements from the application get plan reuse too; SQLite has no stored procedures at all
Code / implementation expected: Optional β a small CREATE PROCEDURE with parameters and a CALL, and the difference from a function.
Schema used by the examples: