淺談Oracle 重建索引

      當咱們建立索引時,oracle會爲索引建立索引樹,表和索引樹經過rowid(僞列)來定位數據。當表裏的數據發生更新時,oracle會自動維護索引樹。可是在索引樹中沒有更新操做,只有刪除和插入操做。 html

       例如在某表id列上建立索引,某表id列上有值「101」,當我將「101」更新爲「110」時,oracle同時會來更新索引樹,可是oracle先將索引樹中的「101」標示爲刪除(實際並未刪除,只是標示一下),而後再將「110」寫到索引樹中。 oracle

       若是表更新比較頻繁,那麼在索引中刪除標示會愈來愈多,這時索引的查詢效率必然下降,因此咱們應該按期重建索引。來消除索引中這些刪除標記。 oop

       通常不會選擇先刪除索引,而後再從新建立索引,而是rebuild索引。在rebuild期間,用戶還可使用原來的索引,而且rebuild新的索引時也會利用原來的索引信息,這樣重建索引會塊一些。 ui

 

這個實驗來察看索引中的刪除標記,而且如何重建索引。 spa

試驗環境:oracle 8.1.7 3d

 

1、建立表、插入記錄和建立索引 orm

 

SQL> create table ind (id number,name varchar2(100)); htm

表已建立。 索引

SQL> create or replace procedure sp_insert_ind get

  2 is 

  3 begin 

  4 for i in 1..10000 loop 

  5 insert into ind values(i,to_char(i)||'aaaaaaaaaa'); 

  6 end loop; 

  7 end; 

  8 / 

過程已建立。 

SQL> exec sp_insert_ind 

PL/SQL 過程已成功完成。 

 

SQL> create index ind_id_idx on ind(id); 

索引已建立。 

 

2、收集索引信息 

 

--收集信息,沒有更新數據字典,因此沒有信息 

SQL> select lf_rows,lf_rows_len,del_lf_rows,del_lf_rows_len from index_stats; 

未選定行 

 

--更新數據字典 

SQL> ANALYZE INDEX ind_id_idx VALIDATE STRUCTURE; 

索引已分析 

 

--參數含義: 

--LF_ROWS Number of values currently in the index 

--LF_ROWS_LEN Sum in bytes of the length of all values 

--DEL_LF_ROWS Number of values deleted from the index 

--DEL_LF_ROWS_LEN Length of all deleted values 

SQL> select lf_rows,lf_rows_len,del_lf_rows,del_lf_rows_len from index_stats; 

   LF_ROWS LF_ROWS_LEN DEL_LF_ROWS DEL_LF_ROWS_LEN 

---------- ----------- ----------- --------------- 

     10000 149801 0 0 

 

--察看索引中已經標示爲刪除的行除以總共的行的數量,目前爲0 

SQL> SELECT (DEL_LF_ROWS_LEN/LF_ROWS_LEN) * 100 AS index_usage FROM index_stats; 

INDEX_USAGE 

----------- 

          0 

 

3、更新索引,而且從新察看信息 

 

--更新表中1000行記錄,這時會更新索引樹 

SQL> update ind set id=id+1 where id>9000; 

已更新1000行。 

 

SQL> ANALYZE INDEX ind_id_idx VALIDATE STRUCTURE; 

索引已分析 

 

--總共行的數量增長了1000行,而且標示爲刪除了1000行記錄 

SQL> select lf_rows,lf_rows_len,del_lf_rows,del_lf_rows_len from index_stats; 

   LF_ROWS LF_ROWS_LEN DEL_LF_ROWS DEL_LF_ROWS_LEN 

---------- ----------- ----------- --------------- 

     11000 164792 1000 14990 

 

--察看索引中已經標示爲刪除的行除以總共的行的數量,目前爲 9.09631536,這個值若是查過20,確定要重建索引了。 

SQL> SELECT (DEL_LF_ROWS_LEN/LF_ROWS_LEN) * 100 AS index_usage FROM index_stats; 

INDEX_USAGE 

----------- 

9.09631536 

 

4、重建索引 

 

--重建索引 

SQL> alter index ind_id_idx rebuild; 

索引已更改。 

SQL> select lf_rows,lf_rows_len,del_lf_rows,del_lf_rows_len from index_stats; 

未選定行 

 

---如下信息又基本回到從前 

SQL> ANALYZE INDEX ind_id_idx VALIDATE STRUCTURE; 

索引已分析 

SQL> select lf_rows,lf_rows_len,del_lf_rows,del_lf_rows_len from index_stats; 

   LF_ROWS LF_ROWS_LEN DEL_LF_ROWS DEL_LF_ROWS_LEN 

---------- ----------- ----------- --------------- 

     10000 149802 0 0 

SQL> SELECT (DEL_LF_ROWS_LEN/LF_ROWS_LEN) * 100 AS index_usage FROM index_stats; 

INDEX_USAGE 

----------- 

          0 

 

 如下來自百度文庫:http://wenku.baidu.com/view/bdacc60603d8ce2f0066232c.html 提供者:Yin_sky

相關文章
相關標籤/搜索