How to restore table statistics (STATS)?

When using DBMS_STATS to gather table statics Oracle backups up the statistics before overwriting it.
The following example shows how dbms_stats.gather_*_stats works and how to restore statistics

Example:
— stats was gathered on a table
SQL> exec dbms_Stats.gather_table_stats('SCOTT', 'TEST');

PL/SQL procedure successfully completed.

— verified stats by checking last_analyzed date
SQL> select to_char(last_analyzed, 'DD-MON-YYYY HH24:MI:SS') from user_tables where table_name = 'TEST';

TO_CHAR(LAST_ANALYZE
——————–
06-OCT-2010 00:08:05

— Some updates/inserts/deletes occurred on the table, gather table stats again
SQL> exec dbms_Stats.gather_table_stats('SCOTT', 'TEST');

— show last analyzed date
SQL> select to_char(last_analyzed, 'DD-MON-YYYY HH24:MI:SS') from user_tables where table_name = 'TEST';

TO_CHAR(LAST_ANALYZE
——————–
06-OCT-2010 00:08:48

— Check historical stats present for the table
SQL> select table_name, to_char(stats_update_time, 'DD-MON-YYYY HH24:MI:SS') from dba_tab_stats_history where owner = 'SCOTT';

TABLE_NAME TO_CHAR(STATS_UPDATE
—————————— ——————–
TEST 06-OCT-2010 00:08:05
TEST 06-OCT-2010 00:08:48

— restore stats to time it was before
SQL> exec DBMS_STATS.RESTORE_TABLE_STATS (ownname=>'SCOTT', tabname=>'TEST', as_of_timestamp=>TO_DATE('06-OCT-2010 00:08:48', 'DD-MON-YYYY HH24:MI:SS'));

PL/SQL procedure successfully completed.

— verify stats was restored by checking date
SQL> select to_char(last_analyzed, 'DD-MON-YYYY HH24:MI:SS') from user_tables where table_name = 'TEST';

TO_CHAR(LAST_ANALYZE
——————–
06-OCT-2010 00:08:05

See the oldest STATs data available
How to change STATS retention

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s