PostgreSQL数据库中如何保证LIKE语句的效率( 三 )


为了更精准的收集统计信息 , 我们也可以在初始化或者创建数据库时将Collate设置为”C” , 这也是Postgresql数据中常用的优化手段 。我们来测试一下将Collate设置为”C”的效果:
testdb01=# create database testdb02 with TEMPLATE template0  LC_COLLATE=’C’  LC_CTYPE =’C’ owner highgo;
CREATE DATABASE
 
 
testdb02=# \l+ testdb02
                                           List of databases
   Name   | Owner  | Encoding | Collate | Ctype | Access privileges | Size  | Tablespace | Description
———-+——–+———-+———+——-+——————-+——-+————+————-
testdb02 | highgo | UTF8     | C       | C     |                   | 59 MB | pg_default |
(1 row)
 
 
testdb02=# create index idx_testliketb01_username on testliketb01(username);
CREATE INDEX
testdb02=# analyze testliketb01 ;
ANALYZE
testdb02=# analyze testliketb01 ;
ANALYZE
testdb02=# analyze testliketb01 ;
ANALYZE
testdb02=#  explain analyze select * from testliketb01 where username like ‘王%’;
                                                                   QUERY PLAN                                                                    
————————————————————————————————————————————————-
Bitmap Heap Scan on testliketb01  (cost=2680.26..9410.67 rows=126033 width=52) (actual time=35.262..99.052 rows=124992 loops=1)
   Filter: ((username)::text ~~ ‘王%’::text)
   Heap Blocks: exact=5155
   ->  Bitmap Index Scan on idx_testliketb01_username  (cost=0.00..2648.75 rows=126033 width=0) (actual time=33.920..33.920 rows=124992 loops=1)
         Index Cond: (((username)::text >= ‘王’::text) AND ((username)::text < ‘玌’::text))
Planning Time: 0.276 ms
Execution Time: 111.578 ms
(7 rows)
 
结论:创建数据库时将Collate设置为”C” , 即便索引为普通索引 , LIKE语句也可以使用索引提升查询效率 。
优化建议:
1、初始化数据库或者创建数据库时将Collate设置为”C” 。