Oracle 對某列的部分資料建立索引

chenoracle發表於2020-05-23

Oracle 對某列的部分資料建立索引

--- 說明:案例來自《 收穫,不止SQL 優化

請問:Oracle 可以針對某列的部分資料建立索引嗎?比如 t1 id 列的資料有 1,2,3,4,5 。可以只針對 id=3 的資料建立索引嗎?

可以通過函式索引實現只針對id=3 的資料建立索引,例如 :

Create index i_t1_id on t(case when id=3 then 3 end);

請問:請舉一個具體案例,並說明在該場景下使用部分索引效能更好?

案例如下:

---建立測試表t

SQL >   create   table  t ( id   int   , status varchar2 ( 2 ));

--建立普通索引

SQL >   create   index  id_normal on  t ( status );

-- 插入資料

SQL >   insert   into  t select   rownum   , 'Y'   from  dual connect   by   rownum <= 100000 ;

SQL >   insert   into  t select   1   , 'N'   from  dual ;

SQL >   commit ;

---資料分佈

SQL >   select   count (*), status from  t group   by  status ;

--- 收集統計資訊

SQL >   analyze   table  t compute   statistics   for   table   for   all   indexes   for   all   indexed   columns ;

--- 查詢表 t ,檢視執行計劃

SQL >   set  linesize 1000

SQL >   set  autotrace traceonly

SQL >   select   *   from  t where  status = 'N' ;

-- 看索引 資訊

SQL >   set  autotrace off

SQL >   analyze   index  id_normal validate   structure ;

SQL >   select   name , btree_space , lf_rows , height from  index_stats ;

備註 INDEX_STATS  儲存的是最近一次   ANALYZE INDEX ... VALIDATE STRUCTURE  語句的結果,最多隻有 當前會話的 一條資料

--- 建立函式索引的情況

SQL >   drop   index  id_normal ;

SQL >   create   index  id_status on   t ( Case   when  status =   'N'   then   'N'   end );

SQL >   analyze   table  t compute   statistics   for   table   for   all   indexes   for   all   indexed   columns ;

--- 再次檢視執行計劃

SQL >   set  autotrace traceonly

SQL >   select   *   from  t where   ( case   when  status = 'N'   then   'N'   end )= 'N' ;

--觀察id_status索引的情況

SQL >   set  autotrace off

SQL >   analyze   index  id_status validate   structure ;

SQL >   select   name , btree_space , lf_rows , height from  index_stats ;

--- 在對比下之前普通索引的值

結論: 普通索引改成函式索引後,索引當前分配的空間 (BTREE_SPACE) 20230168 降到 7996 , 邏輯讀consistent gets 5 降到 2 ,索引葉子數 (LF_ROWS) 100001 降到 1 ,索引高度 (HEIGHT) 3 降到 1 ,效能有所提升。

歡迎關注我的微信公眾號"IT小Chen",共同學習,共同成長!!!

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29785807/viewspace-2693912/,如需轉載,請註明出處,否則將追究法律責任。

相關文章