加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

PostgreSql索引的使用4--表达式索引和部分索引

发布时间:2020-12-13 17:18:48 所属栏目:百科 来源:网络整理
导读:表达式索引 就是利用function或者标量表达式将索引字段包裹起来定义使用。 表达式索引的定义很简单与一般索引一样: Create indexidx_name on table_name(function_name(column_name1)); 类似的写法。 例子1: createindex idx_mytest9_name3 on mytest9(upp

表达式索引就是利用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"

这两种索引使用的情况比较特殊,可能用的会比较少。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读