PostgreSQL explain 排查数组操作导致的慢 SQL 复盘

PostgreSQL SQL 性能优化 About 6,678 words

场景

博客网站上,查询指定分类的文章列表时,响应非常慢,大约要4到5秒才能返回。

目前文章一共才2000篇,理论上即使是全表扫描也不会这么慢,一直没去深入排查,总以为是网络问题。

排查

分页列表

首先想到的分页查询的语句是不是罪魁祸首,但explain下来发现:因为有order by主键,所以走的主键索引。

lite_note=# explain select id, title, topics, substring(description, 0, 100) as description, pv, create_ts from post where status=0 and 'Java'=ANY(topics) order by id desc offset 0 rows fetch first 20 rows only;
                                         QUERY PLAN
---------------------------------------------------------------------------------------------
 Limit  (cost=0.41..736.47 rows=20 width=130)
   ->  Index Scan Backward using post_pkey on post  (cost=0.41..18475.53 rows=502 width=130)
         Filter: ((status = 0) AND ('Java'::text = ANY (topics)))
(3 rows)

不信邪,加了analyze真实执行看看实际消耗时间,也很快:2.256毫秒。

lite_note=# explain analyze select id, title, topics, substring(description, 0, 100) as description, pv, create_ts from post where status=0 and 'Java'=ANY(topics) order by id desc offset 0 rows fetch first 20 rows only;
                                                               QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------------------
 Limit  (cost=0.41..736.47 rows=20 width=130) (actual time=0.066..2.227 rows=20 loops=1)
   ->  Index Scan Backward using post_pkey on post  (cost=0.41..18475.53 rows=502 width=130) (actual time=0.065..2.221 rows=20 loops=1)
         Filter: ((status = 0) AND ('Java'::text = ANY (topics)))
         Rows Removed by Filter: 321
 Planning Time: 0.137 ms
 Execution Time: 2.256 ms
(6 rows)

列表总数

总以为count()会很快,毕竟表数据才2000条不到,再怎么count能花费多少时间呢,不情愿的explain。

惊呆了:幕后凶手竟然是count,花了整整4.6秒。

不敢想象更无法理解,不到2000条的数据表,会有慢SQL!又给我上了一课!

lite_note=# explain analyze select count(*) as count from post where status=0 and 'Java'=ANY(topics);
                                                   QUERY PLAN
-----------------------------------------------------------------------------------------------------------------
 Aggregate  (cost=84686.31..84686.32 rows=1 width=8) (actual time=4661.667..4661.669 rows=1 loops=1)
   ->  Seq Scan on post  (cost=0.00..84685.05 rows=502 width=0) (actual time=423.498..4661.527 rows=270 loops=1)
         Filter: ((status = 0) AND ('Java'::text = ANY (topics)))
         Rows Removed by Filter: 1712
 Planning Time: 0.875 ms
 Execution Time: 4661.705 ms
(6 rows)

解决

AI是真好用,直接把explain的输出丢给AI,直接告诉我=ANY不会走GIN索引,并且直接丢给我一个官方文档:

https://www.postgresql.org/docs/current/gin.html

在PostgreSQL官方邮件列表(pgsql-hackers)的讨论中,也确认了这一点:

123456 = ANY(integer_array_column)

不会使用已有GIN索引,而改为ARRAY[123456] <@ integer_array_column才能命中索引。开发者称这是:expected behavior

https://www.postgresql.org/message-id/CADkLM%3Dez70%3DKuNgZpPExWczFDK9dqE4woRP%2BQOJXrD_OrH%2BQ9A%40mail.gmail.com

只有指定的几个操作符可以在数组类型的GIN索引上命中索引。

@>

改成@>后,再次explain,直接起飞:42毫秒。

从4.66s → 42.6ms,提升了~100×。

好吧,简历上可以浓墨重彩的写上一笔:100倍性能优化。

lite_note=# explain analyze select count(*) as count from post where status=0 and topics @> ARRAY['Java'];
                                                             QUERY PLAN
------------------------------------------------------------------------------------------------------------------------------------
 Aggregate  (cost=1912.55..1912.56 rows=1 width=8) (actual time=42.523..42.525 rows=1 loops=1)
   ->  Bitmap Heap Scan on post  (cost=15.43..1911.30 rows=502 width=0) (actual time=7.482..42.468 rows=270 loops=1)
         Recheck Cond: (topics @> '{Java}'::text[])
         Filter: (status = 0)
         Heap Blocks: exact=260
         ->  Bitmap Index Scan on gin_index_topics  (cost=0.00..15.31 rows=502 width=0) (actual time=6.577..6.578 rows=802 loops=1)
               Index Cond: (topics @> '{Java}'::text[])
 Planning Time: 8.760 ms
 Execution Time: 42.594 ms
(9 rows)

explain 解析

触发了Bitmap Index Scan + Bitmap Heap Scan的索引路径(gin_index_topics),而不再是全表顺序扫。

数组上的@>/&&都是GIN可索引的操作符,这是Postgres文档里明确支持的组合;

= ANY()则不会用到GIN,常导致顺序扫;

Bitmap Index Scan 返回802候选行;

Bitmap Heap Scan读260个堆块并recheck条件;

优化

从explain上能看到:

status = 0的过滤发生在堆层(Filter: (status = 0));

这意味着索引阶段只用到了topics条件,status = 0还没有参与过滤。

创建 status 索引

CREATE INDEX IF NOT EXISTS idx_post_status ON post(status);

或者条件索引

CREATE INDEX idx_post_topics_gin_status0 ON post USING GIN (topics) WHERE status=0

再次 explain

从42.6 ms → 13.4 ms 再降了近3×。

lite_note=# CREATE INDEX IF NOT EXISTS idx_post_status ON post(status);
CREATE INDEX
lite_note=# explain analyze select count(*) as count from post where status=0 and topics @> ARRAY['Java'];
                                                             QUERY PLAN
------------------------------------------------------------------------------------------------------------------------------------
 Aggregate  (cost=1041.87..1041.88 rows=1 width=8) (actual time=13.358..13.359 rows=1 loops=1)
   ->  Bitmap Heap Scan on post  (cost=14.20..1041.20 rows=267 width=0) (actual time=6.699..13.332 rows=270 loops=1)
         Recheck Cond: (topics @> '{Java}'::text[])
         Filter: (status = 0)
         Heap Blocks: exact=260
         ->  Bitmap Index Scan on gin_index_topics  (cost=0.00..14.13 rows=267 width=0) (actual time=5.111..5.111 rows=802 loops=1)
               Index Cond: (topics @> '{Java}'::text[])
 Planning Time: 1.840 ms
 Execution Time: 13.410 ms
(9 rows)

解析 explain

Bitmap Index Scan (gin_index_topics)命中了802个候选行;

Bitmap Heap Scan读取260个堆块,在堆层做status=0的 Filter;

结果行数270,COUNT(*)聚合只做一次。

之所以没有出现BitmapAnd(把idx_post_status与gin_index_topics两个索引的位图做与运算),是因为优化器权衡后认为:在802→270的筛选规模下,直接在堆层过滤status=0的成本更低,不需要额外维护第二个位图(这也是常见、合理的决策)。

疑惑

为什么没有优化前分页列表查询很快,但count很慢?

查询之所以快,核心原因不是= ANY(topics)走了索引,而是整个计划走了主键索引扫描(Index Scan Backward using post_pkey)+ LIMIT,而不是全表扫描:

查询有ORDER BY id DESC OFFSET 0 FETCH FIRST 20 ROWS ONLY,优化器知道只要前20行,所以它直接用post_pkey(主键索引)按倒序扫描,遇到20行符合条件就停。

查询快是因为LIMIT + ORDER BY主键让优化器选择了“索引扫描 + 早停”,而不是全表扫描。

再看看优化后分页列表的耗时:从2.256 ms → 0.630 ms,提升了~4×。

lite_note=# explain analyze select id, title, topics, substring(description, 0, 100) as description, pv, create_ts from post where status=0 and topics @> ARRAY['Java'] order by id desc offset 0 rows fetch first 20 rows only;
                                                               QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------------------
 Limit  (cost=0.41..799.08 rows=20 width=131) (actual time=0.024..0.592 rows=20 loops=1)
   ->  Index Scan Backward using post_pkey on post  (cost=0.41..17690.99 rows=443 width=131) (actual time=0.022..0.588 rows=20 loops=1)
         Filter: ((topics @> '{Java}'::text[]) AND (status = 0))
         Rows Removed by Filter: 321
 Planning Time: 0.415 ms
 Execution Time: 0.630 ms
(6 rows)
Views: 20 · Posted: 2026-12-02

———         Thanks for Reading         ———

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓
Prev Post
Today In History
Browsing Refresh