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类型,也就无法使用索引。

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

posted @ 2024-08-26 21:39  余为民同志  阅读(7)  评论(0编辑  收藏  举报