Scenario: You’re about to implement some major changes to the Oracle database that will adjust the database statistics.
Oracle provide the DBMS_STATS package to help administer stats. The package includes some procedures that can be used to export/import stats, plus restore them to a previous point in time.
When statistics are updated using DBMS_STATS.GATHER_*_STATS, it saves the previous version in the database (can be changed with DBMS_STATS.ALTER_STATS_HISTORY_RETENTION procedure). Also, see table DBA_TAB_STATS_HISTORY.
These versions are retained for a specific retention period, which you can check using the GET_STATS_HISTORY_RETENTION procedure:
SQL> set serveroutput on
v := DBMS_STATS.GET_STATS_HISTORY_RETENTION;
DBMS_OUTPUT.PUT_LINE(‘Stats history retention: ‘ || v || ‘ days.’);
Stats history retention x days.
PL/SQL procedure successfully completed.
You can also check the date of the oldest stats history:
SQL> set serveroutput on
v := DBMS_STATS.GET_STATS_HISTORY_AVAILABILITY;
DBMS_OUTPUT.PUT_LINE(‘Oldest stats history: ‘ || v);
Oldest stats history: 15-DEC-13 188.8.131.52688 PM
PL/SQL procedure successfully completed
To restore the statistics you can use one of the relevant procedures:
See here for parameters:
As an example, the RESTORE_SCHEMA_STATS procedure takes the following parameters:
ownname Schema owner,
force TRUE|FALSE Restore even if stats are locked, default TRUE,
no_invalidate TRUE|FALSE Invalidate cursors, default get_param(‘NO_INVALIDATE’).
If the stats are restored to a specific timestamp, it means that whatever statistics values were applicable to a specific table at a specific point in time, are applied to the tables. If the table’s statistics are not changed then there will be gaps in the history.
You can imagine this being like a roll-forward through the DBA_TAB_STATS_HISTORY table, until the timestamp specified.
WARNING: If the table’s statistics are not changed then there will be gaps in the history. In which case, you may not be able to restore previous statistics if the table stats have not changed within the last history window (default 31 days).
Some great examples are here: https://www.morganslibrary.org/reference/pkgs/dbms_stats.html
You should also note, that under an SAP system, the Oracle stats gatherer is called by BR*Connect, and note that it calls the GATHER_TABLE_STATS procedure for each table that is mentioned in table DBSTATC for tables that have stats enabled in DBSTATC.
If the table is not enabled to collect stats, then it may have stats delivered by SAP (see SAP note 1020260), in which case, there may not be any history.
Also see my blog post on SAP statistics and DBSTATC.