小编Sim*_*tti的帖子

对值为 NULL 的布尔值进行查询时出现意外的 Seq 扫描

我有一个名为auto_reviewwhere column type is的数据库列boolean。该字段有一个索引,使用 ActiveRecord ORM 创建。

CREATE INDEX index_table_on_auto_renew ON table USING btree (auto_renew);
Run Code Online (Sandbox Code Playgroud)

当我查询布尔值的字段时,PG 按预期使用索引。

EXPLAIN for: SELECT "table".* FROM "table"  WHERE "table"."auto_renew" = 'f'
                                          QUERY PLAN
----------------------------------------------------------------------------------------------
 Bitmap Heap Scan on table  (cost=51.65..826.50 rows=28039 width=186)
   Filter: (NOT auto_renew)
   ->  Bitmap Index Scan on index_domains_on_auto_renew  (cost=0.00..44.64 rows=2185 width=0)
         Index Cond: (auto_renew = false)
(4 rows)
Run Code Online (Sandbox Code Playgroud)

当值为 时NULL,使用顺序扫描。

EXPLAIN for: SELECT "table".* FROM "table"  WHERE "table"."auto_renew" IS NULL
                           QUERY PLAN
----------------------------------------------------------------
 Seq Scan …
Run Code Online (Sandbox Code Playgroud)

postgresql index postgresql-8.3 postgresql-9.1

11
推荐指数
1
解决办法
3871
查看次数