表达式索引就是利用function或者标量表达式将索引字段包裹起来定义使用。
表达式索引的定义很简单与一般索引一样:
Create indexidx_name on table_name(function_name(column_name1));
类似的写法。
例子1:
createindex idx_mytest9_name3 on mytest9(upper(name_3));
执行sql:
Explainanalyze Select * from mytest9 wherename_3 = 'name_31';
执行计划:
"QUERYPLAN"
"SeqScan on mytest9 (cost=0.00..209.00rows=1 width=34) (actual time=0.008..2.036 rows=1 loops=1)"
" Filter: ((name_3)::text ='name_31'::text)"
" Rows Removed by Filter: 9999"
"Totalruntime: 2.051 ms"
可以看出并没有使用索引。
执行sql2:
explainanalyze select * from mytest9 where upper(name_3) = 'name_31';
执行计划:
"QUERYPLAN"
"BitmapHeap Scan on mytest9 (cost=4.68..81.70rows=50 width=34) (actual time=0.071..0.071 rows=0 loops=1)"
" Recheck Cond: (upper((name_3)::text) ='name_31'::text)"
" ->Bitmap Index Scan on idx_mytest9_name3(cost=0.00..4.66 rows=50 width=0) (actual time=0.065..0.065 rows=0loops=1)"
" Index Cond: (upper((name_3)::text) ='name_31'::text)"
"Totalruntime: 0.148 ms"
这样的写法就走索引扫描了,而且只有当upper(name_3)时才会使用。
部分索引就是对一个索引字段部分值范围走索引,直接例子。
例子2:
createindex idx_mytest12_id_part on mytest12 (id)
where id>= 100 and id <=1000;
即在100 – 1000的范围内是走索引扫描的,其余的值则走全表扫描。
执行sql1:
explainanalyze select * from mytest12 where id = 10
执行计划:
"QUERYPLAN"
"SeqScan on mytest12 (cost=0.00..209.00rows=1 width=34) (actual time=0.020..2.073 rows=1 loops=1)"
" Filter: (id = 10)"
" Rows Removed by Filter: 9999"
"Totalruntime: 2.101 ms"
执行sql2:
explainanalyze select * from mytest12 where id = 100;
执行计划:
"QUERYPLAN"
"IndexScan using idx_mytest12_id_part on mytest12(cost=0.28..8.29 rows=1 width=34) (actual time=0.018..0.019 rows=1loops=1)"
" Index Cond: (id = 100)"
"Totalruntime: 0.051 ms"
这两种索引使用的情况比较特殊,可能用的会比较少。
原文链接:https://www.f2er.com/postgresql/195189.html