If you searched for PL/SQL “tunning,” the standard term is performance tuning. The first step is to find out what is slow, not to rewrite the code. A procedure that takes minutes might spend most of that time waiting for a lock, running one expensive query, or issuing thousands of small SQL statements. Each problem calls for a different fix.
These 20 PL/SQL performance tuning techniques start with diagnosis, then cover changes to SQL, procedural code, and transaction design. Apply the techniques that address your measured bottleneck rather than treating the list as a set of mandatory changes.
Start your PL/SQL “tunning” work with measurements
1. Establish a baseline with representative data
Measure elapsed time and rows processed for a specific procedure, job, or request. Where available, capture database CPU time, logical reads, physical reads, and waits. Record the input parameters, data volume, and level of concurrency so you can reproduce the test. A procedure might finish quickly for an account with ten records but struggle for one with a million. Test both typical inputs and the larger cases that cause operational problems, and note whether the run used a cold or warm cache.
2. Profile PL/SQL to find expensive call paths
Use DBMS_HPROF to examine the PL/SQL call hierarchy or DBMS_PROFILER to investigate time spent at the line level. Look at both time and call counts. A small helper that executes once per row can cost more overall than a visibly complex procedure that runs only once. Also distinguish time spent in a routine from time spent in its descendants. A slow parent routine may need no changes if one child accounts for nearly all the time.
3. Trace SQL and waits when profiling is not enough
If a procedure spends most of its time in SQL, use a targeted SQL trace and summarize it with TKPROF. Examine parse, execute, and fetch counts, then compare their CPU and elapsed times. Wait information can help distinguish I/O or blocking from CPU-intensive work. Keep tracing limited to a representative session and time window. On shared systems, coordinate with your DBA, especially before collecting bind values that could expose sensitive data.
4. Inspect the executed plan, not just an estimated plan
Use DBMS_XPLAN.DISPLAY_CURSOR to inspect the plan of the cursor that actually ran. When runtime plan statistics are collected, compare estimated rows with actual rows at key operations. Account for the number of starts: a step that returns few rows per execution can still be expensive if it runs repeatedly. Large estimate errors may point to skew, correlated predicates, or unrepresentative statistics. Investigate the cause before adding hints to compensate for it.
Reduce SQL calls from PL/SQL
5. Replace row-by-row operations with set-based SQL
If a loop applies the same rule to every qualifying row, try expressing the rule in a single UPDATE, DELETE, MERGE, or INSERT … SELECT. For example, instead of fetching overdue invoices and updating each one separately, update all invoices that meet the same conditions in one statement. This removes repeated calls between the PL/SQL and SQL engines and gives the optimizer access to the full operation. Before deploying, verify that trigger behavior, error handling, and business outcomes still meet requirements.
6. Use FORALL when per-row preparation is necessary
Some jobs must validate or transform each record in PL/SQL before issuing DML. In that case, prepare the values in collections and use FORALL to submit executions of the same DML statement in bulk. If partial success is allowed, consider SAVE EXCEPTIONS and associate each reported failure with its source record. Decide how failed items will be retried before changing the implementation. Bulk binding improves how work is submitted; it should not silently change which failures stop the job.
7. Fetch with BULK COLLECT in bounded batches
Use BULK COLLECT when downstream processing benefits from having multiple rows in a collection. For large result sets, fetch from an explicit cursor with a LIMIT rather than loading everything into session memory. Process the fetched batch and stop when a fetch returns an empty collection, so the last partial batch is not skipped. Test a few batch sizes with realistic row widths and concurrent sessions. Bigger batches are not automatically faster, especially when many workers run at once.
8. Eliminate repeated lookups inside loops
Look for loops that repeatedly query customer attributes, configuration values, or reference codes. If the lookup belongs to the source query, try joining it there. If the same value applies throughout the procedure, fetch it once before the loop. For a small lookup set that must be used procedurally, a local collection may be appropriate. Preserve the original behavior for missing or duplicate matches: a query expecting one row and a join that returns many rows are not interchangeable.
Make SQL statements do less work
9. Use bind variables in dynamic SQL
Use static SQL if the statement structure is known at compile time. When dynamic SQL is necessary, bind data values instead of concatenating them into the statement text. This allows executions with different values to share SQL text and can reduce parsing overhead. You cannot bind identifiers such as table names as though they were values. For those, choose from a validated set of supported identifiers. If performance varies with bind values, compare the plans and row counts for common and unusual inputs.
10. Write predicates that preserve useful access paths
A function applied to an indexed column can prevent a conventional index range scan. For example, rather than comparing the truncated value of a timestamp column to a calendar date, consider filtering from the start of the day up to, but not including, the start of the following day. Calculate boundaries according to the business time zone and column type. If the expression itself is part of the required access pattern, evaluate a function-based index and verify its use in the executed plan.
11. Match parameter types to column types
Implicit conversion can produce incorrect comparisons or make an existing index less useful if Oracle converts the column rather than the input. Pass numbers and dates as typed values instead of relying on strings and session settings. In PL/SQL, declarations based on %TYPE can help keep variables aligned with their columns. When an external interface supplies strings, validate and convert them at the boundary. Check the plan predicates to see where conversions occur rather than assuming the database converts the side you intended.
12. Design indexes around measured query patterns
Choose indexes based on the predicates, joins, and ordering operations that matter to the workload. For a composite index, evaluate column order against the queries it should support rather than applying a rule about selectivity in isolation. Compare read performance with the cost of maintaining the index during inserts, updates, and deletes. If the query reads much of the table, a full scan may be the better plan. The objective is to reduce total work, not to make every query use an index.
13. Review optimizer statistics after major data changes
Bulk loads, archival jobs, and uneven growth can leave the optimizer working with statistics that no longer represent the data. Review the affected objects and coordinate any refresh with your DBA. For skewed columns or columns that are often filtered together, evaluate whether histograms or extended statistics address a measured estimate problem. Compare execution plans for several representative queries after changes. A statistics refresh can improve one statement and alter plans elsewhere, so test the workload beyond the procedure that prompted the change.
14. Return only the rows and columns you need
Filter in SQL instead of fetching a broad result and discarding most of it in PL/SQL. Select the columns the routine will actually use, particularly when a table includes large text or binary values. If the requirement is to check whether a match exists, avoid counting every matching row just to test whether the count is greater than zero. Where row-limiting syntax is appropriate, add an explicit sort with a tie-breaker if the application needs a predictable choice of row.
Tune hot PL/SQL paths and transaction behavior
15. Avoid calling PL/SQL functions for every row in SQL
A query that invokes a PL/SQL function for each qualifying row can incur frequent transitions between the SQL and PL/SQL engines. The cost can be higher if the function issues another query each time. Look for a join, a SQL expression, or a set-based summary that produces the same result. Test null handling, date and number formatting, and other edge cases when moving logic. A rewrite is only an improvement if it preserves the behavior the callers rely on.
16. Cache stable, frequently reused results selectively
Consider the PL/SQL function result cache when a function is expensive, is frequently called with the same arguments, and depends on data that changes infrequently. Do not cache a result that relies on session settings, user identity, or application context unless all relevant inputs are explicitly represented and the design is safe. Measure after deployment-like data changes, not just after warming the cache. If entries are invalidated frequently or inputs rarely repeat, caching may add overhead without much benefit.
17. Move invariant calculations out of loops
Compute values once when they do not change across iterations. Examples include parsing a fixed configuration value, calculating a constant date boundary, or building a fixed string. Use the profiler to decide which calculations are worth moving. Be careful with values that only appear constant: reading the clock once at the start of a job has different semantics from reading it for every row. Make the change only if the business rule calls for a single reference time.
18. Commit at meaningful transaction boundaries
Committing after every row can add wait time and leave partially completed business operations. Define the transaction around work that must succeed or fail together. For long jobs that permit partial progress, choose restartable batches and record which work completed so a retry does not duplicate changes. Test the trade-offs among commit overhead, lock duration, undo usage, and recovery effort. A bulk fetch or DML batch size does not have to be the same as the commit interval.
19. Investigate lock contention under realistic concurrency
A procedure that runs quickly by itself may stall when several sessions update the same rows. Identify the blocking session and the tables or keys involved. Check whether all workers update a shared status record, hold locks while doing unrelated work, or touch the same resources in different orders. Depending on the cause, partitioning work among workers, shortening a transaction without breaking atomicity, or standardizing update order may help. Verify the change with multiple sessions and check that error recovery still works.
20. Evaluate compiler settings after fixing the bottleneck
For a routine that remains CPU-bound in PL/SQL, review PLSQL_OPTIMIZE_LEVEL and test whether native compilation helps on your Oracle release. Use the same input data and compilation settings when comparing runs, changing one setting at a time. Compiler options are unlikely to solve a slow SQL plan, repeated database calls, or lock contention. Keep any setting change only if the improvement is repeatable and your deployment process can apply and verify the intended configuration.
Verify the improvement before shipping the change
Rerun the baseline after each meaningful change. Compare elapsed time and the metric that explains it: fewer SQL executions for a set-based rewrite, fewer logical reads for a better access path, or less lock wait time for a concurrency fix. Check output, error behavior, and restartability as well as speed. Then run a representative workload to see whether the change helps overall or simply shifts cost to another session or statement.
If you can investigate only one routine, pick the one with the largest impact on users or batch deadlines. Find where its time goes, make the smallest change that addresses that cost, and keep the before-and-after measurements. Those results give you a baseline for the next round of tuning.