Overview
PL/SQL is Oracle’s procedural extension to SQL. Code runs inside the database, close to the data, in procedures, functions, packages and triggers. Its performance rule is simple: minimise context switches between the PL/SQL and SQL engines by working in sets (stored-routines).
Core concepts
- Blocks:
DECLARE ... BEGIN ... EXCEPTION ... END;. Named blocks are stored schema objects. - Packages group related procedures and types with a specification and a body, hide internals, hold session state and load into memory once. Prefer packages to loose procedures.
- Bulk operations:
BULK COLLECT INTOto fetch many rows at once andFORALLto send many DML operations in one switch; use theLIMITclause for large fetches to bound memory. - Exceptions: named (
NO_DATA_FOUND,DUP_VAL_ON_INDEX) and user-defined; useRAISE_APPLICATION_ERROR(-20001, ...)for application errors; do not swallow errors withWHEN OTHERS THEN NULL. - Definer vs invoker rights (
AUTHID DEFINER | CURRENT_USER): decide whose privileges apply (oracle-security). - Static SQL binds variables automatically; for dynamic SQL use
EXECUTE IMMEDIATE ... USINGandDBMS_ASSERTfor identifiers to avoid injection. - Compile warnings:
ALTER SESSION SET PLSQL_WARNINGS = 'ENABLE:ALL'; unit-test with utPLSQL.
Worked example
Inserting 100,000 rows three ways on the Free container (single run, DBMS_UTILITY.GET_TIME):
-- 1. row by row
FOR i IN 1..100000 LOOP INSERT INTO t_a VALUES (i, 'row '||i); END LOOP; COMMIT; -- 1.61 s
-- 2. bulk with FORALL (after filling collections in PL/SQL)
FORALL i IN 1..ids.COUNT INSERT INTO t_b VALUES (ids(i), vs(i)); COMMIT; -- 0.30 s
-- 3. one SQL statement
INSERT INTO t_b SELECT LEVEL, 'row '||LEVEL FROM dual CONNECT BY LEVEL <= 100000; COMMIT; -- 0.08 sRow-by-row is about 20 times slower than a set-based INSERT ... SELECT because each iteration switches engines. FORALL sits in between. Use set SQL first, FORALL/BULK COLLECT when you need procedural logic per row.
Pitfalls and production notes
- Do not commit inside a loop per row; it adds a
log file syncwait each time and breaks atomicity (oracle-redo-undo). - Avoid
SELECT COUNT(*)to test for existence; useEXISTSor handleNO_DATA_FOUND. - Autonomous transactions (
PRAGMA AUTONOMOUS_TRANSACTION) are for logging and audit, not for business logic. - Keep business logic in version-controlled files and deploy with migrations (safe-schema-migrations);
CREATE OR REPLACEinvalidates dependents. - Triggers should be small; large logic in triggers causes mutating-table errors (
ORA-04091) and hidden costs. - SQL Server’s equivalent is T-SQL; PostgreSQL’s is PL/pgSQL.
Practice questions
- Why is
FORALLfaster than aFORloop withINSERT? - When would you use
AUTHID CURRENT_USER? - What problem does
LIMITsolve inBULK COLLECT?
References
- Oracle Database PL/SQL Language Reference; PL/SQL Performance and Optimization
Related
stored-routines · oracle-redo-undo · oracle-security · safe-schema-migrations