sql优化-错误强制类型转换导致索引失效

使用GaussDB数据库进行测试

创建下面表,仅有一个字段ainteger类型。声明其为主键,数据库会默认为其建立索引。

create table t1(
    a int PRIMARY KEY
);

使用\d+查看表结构:

gaussdb=# \d+ t1
                          Table "public.t1"
 Column |  Type   | Modifiers | Storage | Stats target | Description
--------+---------+-----------+---------+--------------+-------------
 a      | integer | not null  | plain   |              |
Indexes:
    "t1_pkey" PRIMARY KEY, btree (a) TABLESPACE pg_default
Has OIDs: no
Options: orientation=row, compression=no

查看select * from t1 where a = 1;执行计划:

gaussdb=# explain select * from t1 where a = 1;
                              QUERY PLAN
-----------------------------------------------------------------------
 [Bypass]
 Index Only Scan using t1_pkey on t1  (cost=0.00..8.27 rows=1 width=4)
   Index Cond: (a = 1)
(3 rows)

可以看到该语句顺利使用B树索引:Index Only Scan

查看select * from t1 where a::text = 1;执行计划:

gaussdb=# explain select * from t1 where a::text = 1;
                     QUERY PLAN
----------------------------------------------------
 Seq Scan on t1  (cost=0.00..52.04 rows=12 width=4)
   Filter: (((a)::text)::bigint = 1)
(2 rows)

可以看到该语句从使用B树索引,改为顺序扫描:Seq Scan。因为::text将a类型强转为text类型,也就无法使用索引。

::是类型转换操作符,用于将一个表达式的值转换为另一种数据类型。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值