Stored procedures, functions, triggers and packages (PL/SQL, T-SQL, PL/pgSQL and MySQL stored programs) concentrate a lot of database time in a few places. They also hide it: a procedure appears as one call, while it runs thousands of statements inside. The core principle is the same in every engine: the SQL engine works in sets, so let it. Procedural loops that issue one statement per row multiply round trips, context switches, log writes and lock acquisitions.
9.1The patterns that cost the most
Pattern
Why it hurts
Fix
Row-by-row loops ("RBAR") that update or insert one row at a time
One statement execution, and often one round trip, per row
A single set-based INSERT ... SELECT, UPDATE with a join, or MERGE
A query inside a loop (the N+1 pattern)
N extra executions, each cheap, together expensive
Join once and loop over the result, or do the whole job in SQL
COUNT(*) to test whether something exists
Counts every match when one would do
EXISTS, or fetch the first row only
Dynamic SQL built by concatenating values
Hard parse or compile per call, plan cache pollution, SQL injection risk
Dynamic SQL with bind parameters
COMMIT inside a loop
A log flush, and a wait for it, on every commit (the commit waits in section 5.7)
Commit per batch, or once at the end, as the business rules allow
An exception handler per row
Expensive setup per row, and errors hidden from the caller
Validate in SQL first; use bulk error handling
Scalar functions called for each row of a query
Per-row execution and context switches; in some engines, plans that can't run in parallel
Inline the logic, or use the engine's function inlining and caching features (section 9.4)
Cursors where a set operation would do
Row-at-a-time processing
Set-based SQL; if a cursor is truly needed, the cheapest cursor type
Long transactions around slow work
Locks held while the code waits on something else
Short transactions; never wait on users or external services while holding locks
9.2Set-based rewrites
The rewrite is nearly always the same: find the loop, find the condition that drives it, and express the whole job as one statement. The engine notes show the pattern in each procedural language.
9.3Dynamic SQL, done safely
Dynamic SQL is fine. Dynamic SQL with values concatenated into the text is not: it compiles a new statement for each value and opens the door to SQL injection. Bind the values.
Identifiers (table and column names) can't be bound. Validate them against the data dictionary or a fixed list, and quote them with the engine's quoting function, listed in the engine note.
9.4Functions called from SQL
A function in a SELECT list or WHERE clause can run once per row, and it hides its own work from the optimizer.
Three things help in every engine: tell the engine what the function does (deterministic or not, reads data or not), let it inline or cache the function where it can, and best of all, express the logic in SQL.
9.5Parameter sensitivity in procedures
Code inside procedures is compiled once and reused, so the first parameter values seen can decide the plan for everyone. When data is skewed, one customer with two orders and one with two million share a plan that suits only one of them.
The remedies are the same everywhere: recompile infrequent, highly variable calls; let the engine keep more than one plan; or give very different cases their own code path or statement.
9.6Errors, logging and transactions
Bulk error handling. Divert bad rows instead of failing a whole batch: validate in SQL first, or use the engine's error handling for bulk loads.
Logging tables. Writing a log row per processed row, in the same transaction, doubles the work and the locking. Log per batch, or buffer messages and write them once. Log rows that must survive the caller's rollback need a transaction of their own.
Transaction design. Keep transactions short. Touch tables in a consistent order across procedures to avoid deadlocks. Never hold locks while waiting for a user, a file or a web service. For work queues, use reads that skip locked rows (section 4.2) so workers don't queue behind each other. Retry deadlock victims in the application.
9.7Instrument your code so time can be attributed
Monitoring can only tell you which feature is slow if the code says who it is. This costs almost nothing and pays off in every incident.
Set an application or module name on every connection, and an action for each unit of work. Every engine has a place for them, and monitoring tools pick them up.
9.8Profile procedure code
Every engine can show which statements inside a routine take the time, and most can show the totals for each routine.