top of page

Oracle Optimizer Statistics Management with DBMS_STATS: A Step-by-Step Guide

OmerNarman
Sep 17
6 min read

Updated: Oct 24

The Oracle optimizer chooses an execution plan by estimating how many rows each step will return. Those estimates come from optimizer statistics: row counts, column distinct values, histograms and so on. When statistics are missing, stale or misleading, the optimizer makes bad estimates, and bad estimates make bad plans.


This post is a practical routine for managing statistics with DBMS_STATS, from checking the automatic job to rolling back a bad gather.



What Statistics Exist

  • Table statistics: number of rows, blocks and average row length.

  • Column statistics: number of distinct values, nulls, low and high values, and optionally histograms for skewed data.

  • Index statistics: levels, leaf blocks, distinct keys and clustering factor.

  • System statistics: CPU and I/O characteristics of the server.

  • Dictionary and fixed object statistics: for the data dictionary and the X$ tables behind the V$ views.



Step 1: Check the Automatic Statistics Job

By default Oracle gathers statistics automatically in the nightly maintenance windows, for objects whose statistics are missing or stale. First confirm the job is enabled and actually finishing.


SQL

SELECT client_name, status FROM dba_autotask_client

WHERE client_name = 'auto optimizer stats collection';

SELECT window_name, TO_CHAR(job_start_time,'YYYY-MM-DD HH24:MI') AS started,

job_status, job_duration

FROM dba_autotask_job_history

WHERE client_name = 'auto optimizer stats collection'

ORDER BY job_start_time DESC

FETCH FIRST 10 ROWS ONLY;


What to expect: STATUS ENABLED, and recent runs with JOB_STATUS SUCCEEDED. If you see STOPPED, the window closed before the job finished, and some objects were not gathered. A window that is too short is a common hidden cause of stale statistics.



Step 2: Check the Global Preferences

DBMS_STATS uses preferences for every gather that does not override them. Know the defaults before you change anything. The recommended values for most systems are the defaults themselves.


SQL

SELECT 'ESTIMATE_PERCENT' AS pref, DBMS_STATS.GET_PREFS('ESTIMATE_PERCENT') AS value FROM dual UNION ALL

SELECT 'METHOD_OPT', DBMS_STATS.GET_PREFS('METHOD_OPT') FROM dual UNION ALL

SELECT 'STALE_PERCENT', DBMS_STATS.GET_PREFS('STALE_PERCENT') FROM dual UNION ALL

SELECT 'GRANULARITY', DBMS_STATS.GET_PREFS('GRANULARITY') FROM dual UNION ALL

SELECT 'INCREMENTAL', DBMS_STATS.GET_PREFS('INCREMENTAL') FROM dual UNION ALL

SELECT 'DEGREE', DBMS_STATS.GET_PREFS('DEGREE') FROM dual;


What to expect: ESTIMATE_PERCENT = DBMS_STATS.AUTO_SAMPLE_SIZE, METHOD_OPT = FOR ALL COLUMNS SIZE AUTO and STALE_PERCENT = 10. AUTO_SAMPLE_SIZE uses a fast algorithm that is as accurate as a full compute for distinct values, so you should almost never set a fixed percentage.



Step 3: Find Stale and Missing Statistics

Oracle tracks DML on each table. When more than STALE_PERCENT (default 10%) of the rows have changed, the statistics are marked stale. Flush the in-memory monitoring data first so the view is up to date.


SQL

EXEC DBMS_STATS.FLUSH_DATABASE_MONITORING_INFO;

-- Stale statistics

SELECT owner, table_name, partition_name, num_rows,

TO_CHAR(last_analyzed,'YYYY-MM-DD') AS last_analyzed, stale_stats

FROM dba_tab_statistics

WHERE owner = 'SALES' AND stale_stats = 'YES'

ORDER BY last_analyzed;

-- Missing statistics

SELECT owner, table_name FROM dba_tab_statistics

WHERE owner = 'SALES' AND last_analyzed IS NULL AND object_type = 'TABLE';

-- How much has changed since the last gather?

SELECT table_name, inserts, updates, deletes, truncated, timestamp

FROM dba_tab_modifications

WHERE table_owner = 'SALES'

ORDER BY inserts + updates + deletes DESC;


What to expect: A list of tables to gather. DBA_TAB_MODIFICATIONS shows the DML counts since the last gather, which helps you understand why a table is stale.



Step 4: Gather Statistics for a Table

Use the defaults and let Oracle decide the sample size and histograms. CASCADE gathers index statistics too (the default AUTO_CASCADE already does). Gathering also invalidates dependent cursors gradually, so plans change over a period instead of all at once.


SQL

BEGIN

DBMS_STATS.GATHER_TABLE_STATS(

ownname => 'SALES',

tabname => 'ORDERS',

degree => 4);

END;

/

SELECT num_rows, blocks, TO_CHAR(last_analyzed,'YYYY-MM-DD HH24:MI') AS last_analyzed

FROM dba_tab_statistics

WHERE owner = 'SALES' AND table_name = 'ORDERS' AND object_type = 'TABLE';


What to expect: NUM_ROWS close to the real row count and LAST_ANALYZED set to now.


Tip: Gather statistics right after large data loads in batch jobs, as the last step of the load. Waiting for the nightly job means the queries that run in between use statistics that describe an empty or half-loaded table.


Step 5: Gather Statistics for a Whole Schema

For a schema, gather only what needs it. GATHER AUTO gathers stale and missing objects, which is far faster than gathering everything.


SQL

BEGIN

DBMS_STATS.GATHER_SCHEMA_STATS(

ownname => 'SALES',

options => 'GATHER AUTO',

degree => 8);

END;

/


What this does: Only tables with stale or missing statistics are gathered, using the current preferences. Use options => 'GATHER' only when you really need to regather everything, for example after a migration.



Step 6: Set Table-Level Preferences

Some tables need different settings. Set them as preferences on the table, rather than in every script. Then the nightly job and every manual gather use the same settings automatically.


SQL

-- Large partitioned table: incremental global statistics

EXEC DBMS_STATS.SET_TABLE_PREFS('SALES','ORDERS_HIST','INCREMENTAL','TRUE');

-- Busy table where 10% change is too much: consider stale at 2%

EXEC DBMS_STATS.SET_TABLE_PREFS('SALES','ORDERS','STALE_PERCENT','2');

-- Skewed column that needs a histogram, no histograms on other columns

EXEC DBMS_STATS.SET_TABLE_PREFS('SALES','ORDERS','METHOD_OPT', -

'FOR ALL COLUMNS SIZE 1 FOR COLUMNS SIZE 254 STATUS');

SELECT preference_name, preference_value

FROM dba_tab_stat_prefs

WHERE owner = 'SALES' AND table_name IN ('ORDERS','ORDERS_HIST');


What this does: INCREMENTAL makes Oracle keep a synopsis per partition, so global statistics are calculated from the partitions that changed, not by scanning the whole table. STALE_PERCENT 2 makes the table stale sooner. The METHOD_OPT preference creates a histogram only on STATUS, where values are skewed.



Step 7: Test New Statistics Safely as Pending

Gathering statistics on a critical table can change many plans at once. Pending statistics let you gather them without publishing them, test your key queries with them in one session, and publish them only when you are satisfied.


SQL

-- 1. Do not publish new statistics on this table automatically

EXEC DBMS_STATS.SET_TABLE_PREFS('SALES','ORDERS','PUBLISH','FALSE');

-- 2. Gather: the result is stored as pending

EXEC DBMS_STATS.GATHER_TABLE_STATS('SALES','ORDERS');

SELECT table_name, num_rows, last_analyzed FROM dba_tab_pending_stats

WHERE owner = 'SALES';

-- 3. Test in your session only

ALTER SESSION SET optimizer_use_pending_statistics = TRUE;

-- run the key queries and compare their plans and timings

-- 4a. Good: publish them

EXEC DBMS_STATS.PUBLISH_PENDING_STATS('SALES','ORDERS');

-- 4b. Bad: throw them away

-- EXEC DBMS_STATS.DELETE_PENDING_STATS('SALES','ORDERS');

-- 5. Return to normal behaviour

EXEC DBMS_STATS.SET_TABLE_PREFS('SALES','ORDERS','PUBLISH','TRUE');


What this does: Other sessions keep using the current statistics while you test. Only your session, with OPTIMIZER_USE_PENDING_STATISTICS=TRUE, sees the pending ones.



Step 8: Lock Statistics on Volatile Tables

Some tables are empty at night and full during the day, such as staging or queue tables. If the nightly job gathers them when they are empty, the optimizer thinks they have no rows all day. The fix is to gather once when the table is representative, then lock the statistics.


SQL

-- During the day, when the table has a typical number of rows

EXEC DBMS_STATS.GATHER_TABLE_STATS('SALES','ORDER_QUEUE');

EXEC DBMS_STATS.LOCK_TABLE_STATS('SALES','ORDER_QUEUE');

SELECT table_name, stattype_locked FROM dba_tab_statistics

WHERE owner = 'SALES' AND table_name = 'ORDER_QUEUE';

-- To regather later: unlock, gather, lock again

-- EXEC DBMS_STATS.UNLOCK_TABLE_STATS('SALES','ORDER_QUEUE');


What to expect: STATTYPE_LOCKED = ALL. The automatic job skips locked tables, and manual gathers fail with ORA-20005 unless you pass force => TRUE.



Step 9: Restore Previous Statistics After a Bad Gather

Every time statistics change, Oracle saves the previous version for the statistics history retention (31 days by default). If plans went bad right after a gather, you can put the old statistics back in seconds.


SQL

-- When were statistics changed?

SELECT table_name, TO_CHAR(stats_update_time,'YYYY-MM-DD HH24:MI:SS') AS changed

FROM dba_tab_stats_history

WHERE owner = 'SALES' AND table_name = 'ORDERS'

ORDER BY stats_update_time DESC;

-- Restore the statistics as they were before the bad gather

BEGIN

DBMS_STATS.RESTORE_TABLE_STATS(

ownname => 'SALES',

tabname => 'ORDERS',

as_of_timestamp => TIMESTAMP '2026-09-16 13:45:00',

no_invalidate => FALSE);

END;

/

SELECT DBMS_STATS.GET_STATS_HISTORY_RETENTION FROM dual;


What this does: RESTORE_TABLE_STATS puts back the statistics that were in place at 13:45. NO_INVALIDATE => FALSE invalidates dependent cursors immediately, so the next executions are parsed with the restored statistics. Consider locking the statistics afterwards until you know why the gather went wrong.



Step 10: Keep Dictionary and Fixed Object Statistics Current

Slow data dictionary queries (slow Data Pump, slow Enterprise Manager pages, slow DBA scripts) are often caused by missing dictionary or fixed object statistics. Gather fixed object statistics during a representative workload, not right after startup, and gather them again after upgrades or major changes.


SQL

EXEC DBMS_STATS.GATHER_DICTIONARY_STATS;

-- During normal workload, so the X$ tables have representative content

EXEC DBMS_STATS.GATHER_FIXED_OBJECTS_STATS;

SELECT COUNT(*) AS fixed_tables_without_stats

FROM dba_tab_statistics

WHERE object_type = 'FIXED TABLE' AND last_analyzed IS NULL;



Step 11: Back Up Statistics Before Major Changes

Before an upgrade, a big release or a migration, export the statistics to a table. Then you can bring them back at any time, even after the history retention has passed, or copy them to a test system to reproduce production plans.


SQL

EXEC DBMS_STATS.CREATE_STAT_TABLE('DBA_ADMIN','STATS_BACKUP');

EXEC DBMS_STATS.EXPORT_SCHEMA_STATS('SALES','STATS_BACKUP',statid => 'BEFORE_REL_42',statown => 'DBA_ADMIN');

-- To restore later:

-- EXEC DBMS_STATS.IMPORT_SCHEMA_STATS('SALES','STATS_BACKUP',statid => 'BEFORE_REL_42',statown => 'DBA_ADMIN');



Summary

Let the automatic job do most of the work, and make sure it finishes. Use AUTO_SAMPLE_SIZE and the default METHOD_OPT, set exceptions as table preferences, gather right after big loads, use pending statistics to test risky changes, lock statistics on volatile tables, and remember that RESTORE_TABLE_STATS can undo a bad gather in seconds. Stable statistics are one of the best ways to get stable performance.

Recent Posts

See All

Comments


bottom of page