超詳細(xì)的Oracle數(shù)據(jù)庫(kù)索引創(chuàng)建及索引重建變更規(guī)范
很多時(shí)候我們都需要對(duì)某些大表去建索引或者重建,如果不正當(dāng)操作就很有可能會(huì)影響到生產(chǎn)環(huán)境,針對(duì)這個(gè)方面我寫了一些關(guān)于數(shù)據(jù)庫(kù)索引創(chuàng)建及索引重建變更的規(guī)范,僅供參考。
一、索引創(chuàng)建前檢查
1. 檢查表段大?。?/p>
- select segment_name, bytes/1024/1024 MB from user_segments where segment_name='<表名>';
2. 檢查表列不同值分布情況:
- select a.table_name,
- a.column_name,
- a.num_distinct,
- round(a.num_distinct * 100 / b.num_rows) "distinct percent%"
- from user_tab_columns a, user_tables b
- where a.table_name = b.table_name
- and a.table_name = 'ORDER_RELEASE_STATUS';
這里可以看到一般不同值分布占全表記錄數(shù),如果percent%達(dá)到15%以上就可以建立索引提高效率
二、索引創(chuàng)建
因?yàn)橹皵?shù)據(jù)庫(kù)規(guī)范沒建立,居然有一張表建立了255個(gè)字段,且索引建了50多個(gè)...
1. 創(chuàng)建單列索引:
- create index index_name on table(col1) tablespace tbs_name [nologging] [online] [parallel n];
- alter index index_name noparallel ;
2. 創(chuàng)建復(fù)合索引:
- create index index_name on table(col1,col2,…) tablespace tbs_name [nologging] [online][parallel n];
- alter index index_name noparallel ;
3. 創(chuàng)建索引:
- create unique index index_name on table(col1,col2,…) tablespace tbs_name [nologging][online][parallel n];
- alter index index_name noparallel ;
4. 創(chuàng)建分區(qū)索引:
Local 索引:
- 小表:
- create index index_name on table(col1) local;
- 大表:
- 1)create index index_name on table(col1) local unusable;
- 2)alter index index_name rebuild partition p_name [parallel n];
- alter index index_name noparallel ;
- 3)execute dbms_stats.gather_index_stats(ownname=> '',indname=> '',)
Global 索引:
- create [global] index index_name on table(col);
5. 刪掉創(chuàng)建的索引
- drop index index_name;
三、索引重建
1. 重建普通索引:
- alter index index_name rebuild tablespace w_data [online][ parallel n][ nologging];
- alter index index_name noparallel ;
2. 重建分區(qū)索引:
- alter index index_name rebuild partition partition_name tablespace tbs_name[online][parallel n][nologging];
- alter index index_name noparallel ;
四、數(shù)據(jù)庫(kù)索引檢查
1. 普通索引檢查
- select index_name,table_name,status,tablespace_name from user_indexes;
status 為 valid 表示索引狀態(tài)正常。
2. 分區(qū)索引檢查
- select index_name,partition_name,status,tablespace_name from user_ind_partitions;
status 為 usable 表示索引狀態(tài)正常。
最后提一點(diǎn),大家在建索引后一定要注意觀察數(shù)據(jù)庫(kù) SQL 執(zhí)行計(jì)劃是否 OK,執(zhí)行效率是否提高,然后監(jiān)控下應(yīng)用是否正常,不能創(chuàng)建完就拍拍屁股走人,后面會(huì)分享更多devops和DBA方面的內(nèi)容,感興趣的朋友可以關(guān)注下。