What belongs in the database at all
Moving logic into the database buys three things: no data movement, atomic multi-statement work, and a single place where the rules run regardless of which client calls them. It costs three things: deployment becomes a database release, testing needs a database, and the logic is now coupled to one engine's dialect. Deciding where a rule lives is therefore a question about change frequency and transactional need, not about where the code happens to be shortest.
The practical dividing line is transactional scope. Anything that must be atomic with the data â a multi-table transfer, a status transition guarded by a check, a batch close that touches many rows â belongs in the database because that is where the atomic boundary exists. Validation that only needs one row and one call, and computation that needs external services, belongs outside. Reporting logic that analysts need to iterate on belongs where they can version and review it, which usually means a query file rather than a procedure body.
By the end of this lesson you should be able to write a procedure whose error handling and transaction control are explicit, express a transform as a set-based function rather than a loop, and explain the security consequences of definer rights.
Procedures and functions are not interchangeable
Both encapsulate logic, but their contracts with the caller differ in ways that determine which one you can use.
| Property | Procedure | Function |
|---|---|---|
| Callable from | Explicit call statement | From within a query |
| Returns | Zero or more result sets, out parameters | A single value or table |
| May run transactions | Yes, including commit and rollback | No, in most engines |
| May execute DDL | Often, with elevated rights | Rarely |
| Optimiser visibility | Opaque | Often inlined or optimised |
Use in a WHERE clause | No | Yes, if not prohibited |
| Side effects | Expected | Discouraged, sometimes banned |
The optimiser row in that table is the one that surprises people. A function that performs I/O or reads the database for each row defeats inlining and can turn a set-based query into an evaluation per row â the classic performance cliff where a query that took two seconds takes twenty minutes after someone "just extracted a rule into a helper". Keep functions deterministic and side-effect free, and they stay optimisable.
A procedure with explicit transactions and traps
The anatomy of a production procedure is short: validate inputs, open an explicit transaction, do the work in as few statements as possible, commit, and trap every exit path. Ambiguity about who committed what is the most expensive class of bug in procedural SQL.
CREATE OR REPLACE PROCEDURE settle_batch(
p_batch_id bigint,
p_settled_by text
)
LANGUAGE plpgsql
AS $$
DECLARE
v_rows bigint;
v_open boolean;
BEGIN
-- 1: validate before touching anything
IF p_batch_id IS NULL THEN
RAISE EXCEPTION 'p_batch_id is required';
END IF;
SELECT is_open INTO v_open FROM batches WHERE batch_id = p_batch_id FOR UPDATE;
IF NOT FOUND THEN
RAISE EXCEPTION 'batch % does not exist', p_batch_id;
END IF;
IF NOT v_open THEN
RAISE EXCEPTION 'batch % is already settled', p_batch_id;
END IF;
-- 2: the atomic section: few statements, no external calls
UPDATE batches
SET is_open = false,
settled_by = p_settled_by,
settled_at = now()
WHERE batch_id = p_batch_id;
UPDATE ledger_entries
SET settled = true,
settled_batch_id = p_batch_id
WHERE batch_id = p_batch_id
AND settled = false;
GET DIAGNOSTICS v_rows = ROW_COUNT;
IF v_rows = 0 THEN
RAISE EXCEPTION 'no open ledger entries for batch %', p_batch_id;
END IF;
INSERT INTO settlement_audit(batch_id, settled_by, entry_count, settled_at)
VALUES (p_batch_id, p_settled_by, v_rows, now());
-- 3: success ends here; any exception above rolls the whole call back
EXCEPTION
WHEN serialization_failure OR deadlock_detected THEN
RAISE NOTICE 'batch % conflicted, retryable', p_batch_id;
RAISE;
WHEN raise_exception THEN
RAISE; -- business error: unchanged state, clear message
WHEN OTHERS THEN
RAISE EXCEPTION 'settle_batch failed for %: %', p_batch_id, SQLERRM;
END;
$$;
Notice the discipline around the exception block. Business errors are re-raised without being swallowed, so the caller sees a meaningful message and the transaction rolls back cleanly. Transient concurrency errors are identified explicitly and re-raised so the caller can retry â a procedure that quietly caught a deadlock would leave the caller believing work succeeded. The OTHERS branch exists to add context, never to hide the original failure.
Set-based transforms instead of loops
A loop over rows in procedural SQL is a promise that the engine cannot do better â and with a set-based alternative available, that promise is almost always false. The test is simple: if the operation can be expressed as a join, a window function, or a set update, it should be.
-- Anti-pattern: one statement per row inside a cursor loop
-- FOR r IN SELECT * FROM invoices WHERE batch_id = p_batch LOOP
-- UPDATE customers SET balance = balance + r.amount WHERE customer_id = r.customer_id;
-- END LOOP;
-- The same rule as one set-based statement
CREATE OR REPLACE FUNCTION apply_batch_to_balances(p_batch_id bigint)
RETURNS bigint
LANGUAGE sql
VOLATILE
AS $$
WITH deltas AS (
SELECT customer_id,
SUM(amount) AS delta
FROM invoices
WHERE batch_id = p_batch_id
AND status = 'posted'
GROUP BY customer_id
)
UPDATE customers c
SET balance = c.balance + d.delta,
updated_at = now()
FROM deltas d
WHERE c.customer_id = d.customer_id
RETURNING c.customer_id;
$$;
-- Derived columns computed with window functions, not application round trips
SELECT invoice_id,
customer_id,
amount,
amount - SUM(amount) OVER (PARTITION BY customer_id
ORDER BY invoice_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
AS running_balance,
RANK() OVER (PARTITION BY customer_id ORDER BY invoice_date DESC) AS recency_rank
FROM invoices
WHERE batch_id = 4821;
The set version does one pass, one plan, and one round trip. It also scales with the data rather than with the number of round trips, which is the difference between a nightly job that shrinks as indexes improve and one that grows with row count regardless of tuning.
Transactions, savepoints, and propagation
Inside a procedure, transaction boundaries are a design decision. Some engines forbid commits in functions entirely, which is a feature: a function called from a query must not be able to commit the caller's transaction. Procedures that do manage transactions must decide what a partial failure means, and savepoints are how you express "this part may fail and be rolled back while the rest continues".
CREATE OR REPLACE PROCEDURE import_day(p_day date)
LANGUAGE plpgsql
AS $$
DECLARE
r record;
sp_succeeded boolean := false;
BEGIN
FOR r IN SELECT source FROM import_sources WHERE active LOOP
SAVEPOINT before_source;
BEGIN
PERFORM load_source(r.source, p_day);
PERFORM validate_source(r.source, p_day);
sp_succeeded := true;
EXCEPTION WHEN OTHERS THEN
ROLLBACK TO SAVEPOINT before_source;
INSERT INTO import_errors(source, run_day, error_text, occurred_at)
VALUES (r.source, p_day, SQLERRM, now());
sp_succeeded := false;
END;
IF NOT sp_succeeded THEN
RAISE NOTICE 'source % failed and was isolated', r.source;
END IF;
END LOOP;
END;
$$;
The pattern separates isolation from success. Each source gets its own savepoint, a failure rolls back only that source, and the error is recorded rather than lost. The final decision â whether the day is acceptable with one source missing â is a policy, so make it explicit at the end instead of letting control flow decide implicitly.
Security: definer rights and injection
Stored procedures often run with elevated privileges, which makes them an attractive target. Two rules cover most of the risk. Never build statement text by concatenating untrusted input; pass values as parameters so the engine binds them, and if an identifier must be dynamic, validate it against a catalogue of permitted names rather than escaping quotes. And be deliberate about whether a procedure executes with the caller's rights or the owner's, because definer rights turn a low-privilege caller into a path to whatever the owner can reach.
Grant execute narrowly. The common mistake is granting execute on a procedure to PUBLIC while the procedure itself does privileged work, which quietly hands every login a capability they were never given directly. Combine that with input validation at the top of the body and an audit table for sensitive operations, and procedural code becomes an enforcement point rather than an exposure.
â ī¸Dynamic identifiers are the injection hole
Parameters neutralise values but not identifiers. A table name concatenated into a statement cannot be bound, so the only safe approach is an allow-list checked against the catalogue before the statement is ever assembled.
Common Mistakes
Looping over rows with a cursor where a set-based statement would do
Fix: Rewrite as a join, window function, or set update and measure the plan before and after
Swallowing exceptions in an OTHERS block so failures look like successes
Fix: Trap specific conditions, re-raise with context, and let the transaction roll back
Making a query-side function perform I/O or database reads per row
Fix: Keep functions deterministic and side-effect free, or move the work into a procedure
Concatenating input into statement text
Fix: Bind values as parameters and allow-list any identifier that must be dynamic
Best Practices
- Keep the transactional section short and free of external calls
- Decide the partial-failure policy in code rather than by accident of control flow
- Prefer set-based statements and verify with an execution plan after every rewrite
- Grant execute narrowly and document whether each procedure uses definer or invoker rights
- Version procedural code in source control and deploy it through the same review path as application code
Interview Questions
Q1: When does procedural logic belong in the database?
When it must be atomic with the data, must be enforced identically for every client, or would otherwise require moving large volumes of rows.
Q2: Why can a function inside a query be slow?
If it is not inlined and performs I/O, it may be evaluated once per row instead of once per set.
Q3: What does a savepoint buy you?
A rollback point inside a transaction, so one failing unit of work can be isolated while the rest continues.
Q4: What are definer rights?
The procedure executes with its owner's privileges rather than the caller's, which is convenient and dangerous in equal measure.
Key Takeaways
- Transaction scope, not convenience, decides where a rule lives
- Set-based statements beat row loops in both plan quality and round trips
- Trap specific conditions, re-raise with context, and never hide a failure
- Functions should be deterministic and side-effect free so the optimiser can inline them
- Grant execute narrowly and treat dynamic identifiers as an allow-list problem