Here's what happens:
1) I run some query that is not optimized very well - it executes in 16 seconds (averaged stable number after 10 test runs); the execution plan says - dynamic sampling used for this statement (level=2)
, so it does not have stats for this query to use.
2) I run exec DBMS_STATS.GATHER_DATABASE_STATS
3) I run the same query again - it executes in 46 seconds (again average number) and doesn't get any lower; this time the execution plan does not say - dynamic sampling used for this statement (level=2)
, so it has stats for this query to use.
4) I pretend to freak out because the query is performing longer than without the stats, so I try to revert the issue by running
exec DBMS_STATS.DELETE_DATABASE_STATS;
exec DBMS_STATS.DELETE_DATABASE_STATS(NULL, NULL, NULL, DBMS_STATS.AUTO_INVALIDATE, 'ALL', TRUE);
or for older versions of Oracle SQL server:
exec DBMS_STATS.DELETE_DATABASE_STATS(NULL, NULL, NULL, DBMS_STATS.AUTO_INVALIDATE, TRUE);
5) I run the same query again - no luck. Although the execution plan says - dynamic sampling used for this statement'(level=2)
again, still the query executes in 46 seconds and no less. The execution plan differs both from 1 and 3; so clearly Oracle hasn't cleared some stats away.
6) I give up and run Oracle's Restore Database tool. After that, I'm at point 1. again and can reproduce this scenario reliably again and again.
All the tests are done through Oracle SQL Developer connected to a local Oracle Database 11gR2 Express Edition for Windows x64 (on Windows 10) instance, running on SSD, i7 CPU, 16GB RAM. There are no other systems using this database during the tests.
The question is: how to fully revert the Oracle Database from the harm done by recklessly executing exec DBMS_STATS.GATHER_DATABASE_STATS
, if I don't want to fully restore the database from a backup?
Am I missing some parameters for DELETE_DATABASE_STATS
or is there something else going on and the database gets somehow rearranged after running the stats once, so the execution planner cannot revert to the very first plan any more?