首页 > 解决方案 > PostgreSQL 性能,使用 ILIKE 仅占两个百分比而不是根本不使用

问题描述

我正在使用 ILIKE 根据用户输入搜索行的标题。当用户没有输入任何内容(空字符串)时,所有行都应该返回。

如果您在查询 SELECT 语句时使用它与完全不使用它,是否存在性能差异ILIKE '%%'?换句话说,是否可以只查询 ILIKE 为空,或者如果没有搜索过滤器文本,我应该在查询中删除它吗?

标签: sqlpostgresqlquery-optimization

解决方案


在 PostgreSQL (13.1) 上,这两个查询是不等价的:

test=# select count(*) from test_ilike where test_string ilike '%%';
 count  
--------
 100000
(1 row)

Time: 87,211 ms
test=# select count(*) from test_ilike where test_string ilike '';
 count 
-------
     0
(1 row)

Time: 85,521 ms

test=# explain analyze select count(*) from test_ilike where test_string ilike '%%';
                                                      QUERY PLAN                                                       
-----------------------------------------------------------------------------------------------------------------------
 Aggregate  (cost=2333.97..2333.99 rows=1 width=8) (actual time=86.859..86.860 rows=1 loops=1)
   ->  Seq Scan on test_ilike  (cost=0.00..2084.00 rows=99990 width=0) (actual time=0.022..81.497 rows=100000 loops=1)
         Filter: (test_string ~~* '%%'::text)
 Planning Time: 0.313 ms
 Execution Time: 86.893 ms
(5 rows)
Time: 87,582 ms
test=# explain analyze select count(*) from test_ilike where test_string ilike '';
                                                  QUERY PLAN                                                   
---------------------------------------------------------------------------------------------------------------
 Aggregate  (cost=2084.00..2084.01 rows=1 width=8) (actual time=83.223..83.224 rows=1 loops=1)
   ->  Seq Scan on test_ilike  (cost=0.00..2084.00 rows=1 width=0) (actual time=83.219..83.219 rows=0 loops=1)
         Filter: (test_string ~~* ''::text)
         Rows Removed by Filter: 100000
 Planning Time: 0.104 ms
 Execution Time: 83.257 ms
(6 rows)

Time: 83,728 ms


推荐阅读