Oracle 對某列的部分數據創建索引
--- 說明:案例來自《 收獲,不止SQL 優化 》
請問:Oracle 可以針對某列的部分數據創建索引嗎?比如 t1 表 id 列的數據有 1,2,3,4,5 ??梢灾会槍?/span> 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",共同學習,共同成長?。?!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。