怎樣建立最佳索引?
1、明確地創建索引
create index index_name on table_name(field_name)
tablespace tablespace_name
pctfree 5
initrans 2
maxtrans 255
storage
(
minextents 1
maxextents 16382
pctincrease 0
);
2、創建基於函數的索引
常用與UPPER、LOWER、TO_CHAR(date)等函數分類上,例:
create index idx_func on emp(UPPER(ename)) tablespace tablespace_name;
3、創建位圖索引
對基數較小,且基數相對穩定的列建立索引時,首先應該考慮位圖索引,例:
create bitmap index idx_bitm on class (classno) tablespace tablespace_name;
4、明確地創建唯一索引
可以用create unique index語句來創建唯一索引,例:
create unique index dept_unique_idx on dept(dept_no) tablespace idx_1;
5、創建與約束相關的索引
可以用using index字句,爲與unique和primary key約束相關的索引,例:
alter table table_name
add constraint PK_primary_keyname primary key(field_name)
using index tablespace tablespace_name;
如何創建局部區索引?
1)基礎表必須是分區表
2)分區數量與基礎表相同
3)每個索引分區的子分區數量與相應的基礎表分區相同
4)基礎表的自分區中的行的索引項,被存儲在該索引的相應的自分區中,例如
create index TG_CDR04_SERV_ID_IDX on TG_CDR04(SERV_ID)
Pctfree 5
Tablespace TBS_AK01_IDX
Storage(
MaxExtents 32768
PctIncrease 0
FreeLists 1
FreeList Groups 1
)
local
/
如何創建範圍分區的全局索引?
基礎表可以是全局表和分區表
create index idx_start_date on tg_cdr01(start_date)
global partition by range(start_date)
(partition p01_idx vlaues less than ('0106')
partition p01_idx vlaues less than ('0111')
...
partition p01_idx vlaues less than ('0401'))
/
如何重建現存的索引?
重建現存的索引的當前時刻不會影響查詢
重建索引可以刪除額外的數據塊
提高索引查詢效率
alter index idx_name rebuild nologging;
對於分區索引
alter index idx_name rebuild partition partition_name nologging;
刪除索引的原因?
1)不再需要的索引
2)索引沒有針對其相關的表所發佈的查詢提供所期望的性能改善
3)應用沒有用該索引來查詢數據
4)該索引無效,必須在重建之前刪除該索引
5)該索引已經變的太碎了,必須在重建之前刪除該索引
語句:
drop index idx_name;
drop index idx_name partition partition_name;
建立索引的代價?
基礎表維護時,系統要同時維護索引,不合理的索引將嚴重影響系統資源,
主要表現在CPU和I/O上。
插入、更新、刪除數據產生大量db file sequential read鎖等待。