A SQL statement can have perfectly valid syntax and still end up with a poor execution plan because the optimizer started with an inaccurate row estimate. Statistics may be missing, the data may have changed significantly after a load, or the predicates may contain relationships that ordinary single-column statistics do not describe well.
Oracle Dynamic Statistics gives the optimizer another source of information. During optimization, Oracle can execute recursive SQL and sample table blocks to improve selectivity and cardinality estimates before the final execution plan is selected. Before Oracle Database 12c, this feature was known as Dynamic Sampling.
For a DBA, the useful part is not simply knowing that Dynamic Statistics exists. The important part is understanding what to do when an execution plan contains a note such as:
dynamic statistics used: dynamic sampling (level=2)
That message should not immediately lead to increasing OPTIMIZER_DYNAMIC_SAMPLING. It is better treated as evidence that the optimizer used additional information while producing that cursor. The next task is to understand why that additional information was useful.
Start with the Execution Plan
If the SQL is already available in the shared pool, I prefer looking at the plan of the cursor that actually executed rather than generating another plan with EXPLAIN PLAN. The executed cursor reflects the optimizer environment and child cursor that were really used.
SELECT * FROM TABLE( DBMS_XPLAN.DISPLAY_CURSOR( sql_id => '&sql_id', cursor_child_no => &child_no, format => 'ALLSTATS LAST' ) );
There are two useful things to look for here. First, compare estimated rows with actual rows when runtime statistics are available. If Oracle estimated a few hundred rows from an operation but execution processed several million, the poor join method or access path seen later in the plan may only be a consequence of that earlier cardinality error.
Second, read the Note section at the bottom of the plan. If Oracle reports that Dynamic Statistics were used, then sampling participated in optimizing that cursor. This is more meaningful than looking at V$SQL.PARSE_CALLS. A high parse count tells us that a statement was parsed frequently. It does not prove that Dynamic Statistics were used.
One detail matters with ALLSTATS LAST. Actual row counts are useful only when runtime plan statistics were collected, for example through /*+ GATHER_PLAN_STATISTICS */ or an appropriate statistics setting. Without them, the plan itself is still useful, but the E-Rows versus A-Rows comparison may not be available.
What Dynamic Statistics Are Trying to Improve
Consider a simple predicate where Oracle estimates that only 500 rows will be returned, while the actual result is closer to 3 million rows. A nested loop with index access may look perfectly reasonable while costing 500 rows. The same plan can become very expensive when millions of rows actually flow through it.
That is why cardinality errors matter beyond a single table access. An incorrect estimate can influence join order, nested loops versus hash joins, index selection, full scans, parallel execution decisions and the amount of work expected farther up the execution plan.
SELECT order_id, customer_id, status FROM orders WHERE status = 'PENDING';
Dynamic Statistics allows Oracle to sample current table data during optimization instead of relying only on persistent optimizer statistics. The trade-off is additional work during parsing. For a large reporting query that may run for several minutes, some additional optimization work may be reasonable if it prevents a poor join order. For a very short OLTP statement that is constantly hard parsed, repeated sampling deserves more attention.
So I would not classify Dynamic Statistics simply as good or bad for performance. Its purpose is to improve optimizer estimates. Whether the additional work is worthwhile depends on the statement and workload.
Understanding the Dynamic Statistics Levels
The database setting can be checked easily:
SELECT name, value FROM v$parameter WHERE name = 'optimizer_dynamic_sampling';
OPTIMIZER_DYNAMIC_SAMPLING supports levels 0 through 11. Level 0 disables Dynamic Statistics. Level 2 is the normal default documented by Oracle and, at that level, the standard trigger is the presence of at least one table without optimizer statistics.
Levels 3 and 4 broaden the circumstances where sampling is considered. Level 3 can help with expressions in predicates, while level 4 extends the conditions further for more complex predicates. Levels 5 through 10 use progressively larger samples while retaining the conditions associated with level 4.
Level 11 is different. It enables adaptive dynamic sampling, where Oracle decides whether sampling is required and how much sampling should be performed. Describing level 11 simply as "maximum sampling of every table" is therefore misleading.
There is another reason not to interpret the level too mechanically. Oracle can use Dynamic Statistics when optimizer statistics are missing, stale or otherwise insufficient, and other optimizer behaviour such as parallel execution can influence when sampling is considered. The configured level tells us part of the story, but not necessarily every reason Dynamic Statistics appeared in a particular plan.
Check What Statistics Oracle Already Has
Once Dynamic Statistics are confirmed in the execution plan, the next useful check is what persistent statistics Oracle already has for the affected object.
SELECT owner, table_name, partition_name, num_rows, last_analyzed, stale_stats, stattype_locked FROM dba_tab_statistics WHERE owner = 'APP' AND table_name = 'ORDERS' ORDER BY partition_name NULLS FIRST;
This tells us more than simply checking LAST_ANALYZED. We can see whether statistics exist, whether Oracle considers them stale, whether statistics are locked and, on partitioned objects, whether individual partitions may have a different statistics state from the table as a whole.
Even fresh statistics do not guarantee an accurate cardinality estimate for every SQL statement. The optimizer still has to estimate the effect of the predicates used by that particular query.
Learning - Fresh Statistics Can Still Produce a Poor Estimate
A common example is correlation between columns. Consider a query filtering on both country and city:
WHERE country = 'Singapore' AND city = 'Singapore'
Statistics on COUNTRY and CITY describe the columns individually. They do not necessarily describe the relationship between them. If the optimizer estimates both predicates independently, the combined selectivity can be very different from the real data distribution.
Oracle extended statistics, including column-group statistics, are intended for situations where multiple columns used together need to be treated as a unit for cardinality estimation. Expression statistics address a related problem where the SQL applies functions or expressions that ordinary column statistics do not describe adequately.
This is why LAST_ANALYZED should not become the end of the investigation. A table analyzed recently can still produce poor estimates because of data skew, correlated columns, expressions, uneven partition distributions or substantial data changes since statistics were gathered.
As a Diagnostic Test - one must use Higher Sampling
If the evidence points toward a cardinality problem, testing a different Dynamic Statistics level can help confirm whether more sampling improves the optimizer's understanding of the data. I would prefer doing that at session or statement level before considering any database-wide change.
ALTER SESSION SET optimizer_dynamic_sampling = 4; SELECT /*+ dynamic_sampling(o 4) */ o.order_id, o.status FROM orders o WHERE o.status = 'PENDING';
The interesting result is not just whether the plan changes. Compare the cardinality estimate before and after the test. If additional sampling moves the estimate much closer to the actual row count and that leads to a better plan, it is evidence that the original optimizer information was not sufficient for this query.
That still does not mean a permanent DYNAMIC_SAMPLING hint is the correct fix. Missing statistics may need to be gathered. Data skew may require reviewing histograms. Correlated predicates may justify extended statistics. A reporting table may simply need statistics gathered after its batch load.
Where to check ? Batch Loads Are a Good Place to Look
Consider a reporting table that is substantially refreshed before users begin querying it. Statistics may have accurately represented yesterday's population, but after a large morning load the table can look very different while the stored statistics still describe the older data.
Dynamic Statistics may help some statements because Oracle gets an opportunity to inspect current table blocks during optimization. That can reduce the impact of stale or inadequate information, but it does not make the statistics workflow correct.
Where the load materially changes the data, statistics gathering may belong in the post-load process. A simple example is:
BEGIN DBMS_STATS.GATHER_TABLE_STATS( ownname => 'APP', tabname => 'ORDERS', estimate_percent => DBMS_STATS.AUTO_SAMPLE_SIZE, method_opt => 'FOR ALL COLUMNS SIZE AUTO', cascade => DBMS_STATS.AUTO_CASCADE ); END; /
This should not be copied blindly for every large object. A large partitioned warehouse table may be better handled through partition-level or incremental statistics. The right approach depends on how much data changes, which partitions are modified, how large the object is and how quickly application queries begin after the load.
The broader operational point is that statistics maintenance should match the way data changes. If a major load occurs at 07:00 while useful statistics are gathered much later, Dynamic Statistics may be compensating for a gap that could be addressed more directly.
What the plan note really tells the DBA
The note becomes much more interesting when it appears together with other evidence: large differences between estimated and actual rows, unstable plans, a recently changed data population, missing object statistics, complex predicates or repeated hard parsing.
A practical investigation can therefore stay relatively simple:
Poor or changed plan
↓
Compare estimated and actual rows
↓
Check the plan Note
↓
Inspect object and partition statistics
↓
Examine the predicates and data distribution
↓
Test whether better statistics
or
controlled sampling corrects the estimate
Dynamic Statistics can rescue an estimate at parse time. The more useful DBA outcome is understanding why that additional sampling was required and deciding whether the database needs better persistent statistics, a different statistics strategy, or simply no change at all.
A Practical Way to Read Dynamic Statistics
When I see dynamic statistics used while investigating an execution plan, I would not treat the message as an error and I would not immediately change the database parameter. The note tells us that Oracle used additional sampling while optimizing that cursor. The useful work is establishing why.
Check whether statistics exist and whether they still represent the current data. Compare estimated rows with actual rows where possible. Look at the predicates instead of focusing only on the final join method. If related columns are involved, consider whether extended statistics are relevant. For tables changed by large batch loads, check whether statistics maintenance follows the load process closely enough.
Dynamic Statistics can improve a plan by giving Oracle better information during optimization. For DBA troubleshooting, the more valuable question is often why the optimizer needed that additional information and whether the cause should be fixed permanently or simply accepted as valid optimizer behaviour for that workload.
Oracle Official Documentation References
The following Oracle documentation is useful for validating and exploring the behaviour discussed in this article:
- Oracle AI Database 26 - Configuring Options for Optimizer Statistics Gathering
Covers Dynamic Statistics, sampling levels,OPTIMIZER_DYNAMIC_SAMPLING, adaptive dynamic sampling and the conditions under which Oracle may perform sampling - Oracle AI Database 26 - DBMS_XPLAN
Official PL/SQL package reference forDISPLAY_CURSOR, execution-plan formatting and runtime plan statistics. - Oracle AI Database 26 - Managing Extended Statistics
Explains column-group and expression statistics and how they can improve cardinality estimates where ordinary single-column statistics are not sufficient
And if you have not checked it this way before, would you try these checks the next time you see that note in the plan? 😉
Happy troubleshooting, and may your estimates be accurate. 🤘🏻

No comments:
Post a Comment