微課sql優化(2)-為什么需要收集統計信息
1、為什么需要收集統計信息
Cost-based optimizer (CBO),Based on object statistics,優化器統計信息描述數據庫中的對象的詳細信息,
查詢優化器使用這些統計信息為每個SQL語句選擇最佳執行計劃。
數據庫將優化器統計信息存儲在數據字典中。您可以使用數據字典視圖訪問這些統計信息。
由于數據庫中的對象可能會不斷更改,因此必須定期更新統計信息,以便準確描述這些對象。Oracle數據庫自動維護優化器統計信息。
11g:
Scheduled Maintenance Window Times
,
In 11g daily maintenance windows are provided. by default these are defined as :
Weeknights: Starts at 10 p.m. and ends at 2 a.m.
Weekends: Starts at 6 a.m. is 20 hours long.
10g:
With Oracle Database 10g the default maintenance window is configured to cover the following periods:
10 pm to 6 am every weekday
All weekend (Friday 10 pm to Monday 6 am)
可以使用該DBMS_STATS軟件包手動維護優化器統計信息。
2、哪些表需要收集統計信息
自動統計任務能滿足大部分數據庫的業務需求,但存在特殊情況需要手工收集統計信息,
1、業務表數據被delete、truncate、impdp/imp大批量數據變理時。
2、數據變更量超過10%時。
查詢哪些表需要收集統計信息
col table_name for a30
col object_type for a30
select owner, table_name, object_type, stale_stats, to_char(LAST_ANALYZED,'yyyy-mm-dd hh34:mi') last_analyzed
from dba_tab_statistics
where owner = 'HT'
and (stale_stats = 'YES' or last_analyzed is null);
3、練習題1、測試統計信息閾值: 變更量超過10%
create table ht.test as select * from dba_objects;
exec DBMS_STATS.GATHER_TABLE_STATS(ownname => 'HT',tabname => 'TEST',method_opt => 'for all columns size repeat',no_invalidate => FALSE,degree => 4,cascade => TRUE);
SQL> DELETE FROM ht.TEST WHERE ROWNUM<=(select count(1) from ht.TEST)*0.1;
8632 rows deleted.
SQL> commit;
Commit complete.
exec dbms_stats.flush_database_monitoring_info; --刷新變更信息
set line 200
col table_owner for a10
col table_name for a30
col pname for a20
col spname for a20
select table_owner,table_name,partition_name pname,subpartition_name spname,inserts,updates,deletes from dba_tab_modifications
where table_owner='HT';
TABLE_OWNE TABLE_NAME PNAME
SPNAME INSERTS
UPDATES DELETES
------
---
---
---
---- ---------------- ----------- --------------
--
--
----------
--
----------
--
--
--
----------
HT TEST
0 0 8632
col table_name for a30
col object_type for a30
COL last_analyzed for a20
select owner, table_name, object_type, stale_stats, to_char(LAST_ANALYZED,'yyyy-mm-dd hh34:mi') last_analyzed
from dba_tab_statistics
where owner = 'HT' AND TABLE_NAME='TEST';
OWNER TABLE_NAME OBJECT_TYPE STALE_STA LAST_ANALYZED
---------- ---------------------- ------------------------------ --------- --------------------
HT TEST TABLE NO 2017-08-18 21:26
DELETE FROM ht.TEST WHERE ROWNUM=1;
exec dbms_stats.flush_database_monitoring_info; --刷新變更信息
col table_name for a30
col object_type for a30
COL last_analyzed for a20
select owner, table_name, object_type, stale_stats, to_char(LAST_ANALYZED,'yyyy-mm-dd hh34:mi') last_analyzed
from dba_tab_statistics
where owner = 'HT' AND TABLE_NAME='TEST';
4、小結
哪些情況需要從新收集統計信息,
1、業務表數據被delete、truncate、impdp/imp大批量數據變更時。
2、數據變更量超過10%時,統計信息狀態標記為過期
。