SQL优化技巧 - 排序方向不同导致索引失效
· 阅读需 3 分钟
Copyright © 2023 PawSQL
问题定义
ORDER BY 子句中的所有表达式必须按统一的 ASC 或 DESC 方向排序,以便利用索引;如果ORDER BY 语句对多个不同条件使用不同方向的排序无法使用索引。
譬如在TPCH的lineitem
的表上创建索引:
create index l_partkey_suppkey_idx on lineitem(l_partkey, l_suppkey);
- 正向索引扫描,正确利用索引,避免排序
explain analyze select * from lineitem l order by l.L_PARTKEY, l.L_SUPPKEY limit 1;
-> Limit: 1 row(s) (cost=0.00 rows=1) (actual time=0.065..0.065 rows=1 loops=1)
-> Index scan on l using LINEITEM_FK2 (cost=0.00 rows=1) (actual time=0.063..0.063 rows=1 loops=1)
- 反向索引扫描,正确利用索引,避免排序
explain analyze select * from lineitem l order by l.L_PARTKEY desc, l.L_SUPPKEY desc limit 1;
-> Limit: 1 row(s) (cost=0.00 rows=1) (actual time=0.033..0.033 rows=1 loops=1)
-> Index scan on l using LINEITEM_FK2 (reverse) (cost=0.00 rows=1) (actual time=0.032..0.032 rows=1 loops=1)
- 无法利用索引,全表扫描
explain analyze select * from lineitem l order by l.L_PARTKEY desc, l.L_SUPPKEY limit 1;
-> Limit: 1 row(s) (cost=33963.20 rows=1) (actual time=246.462..246.462 rows=1 loops=1)
-> Sort: l.L_PARTKEY DESC, l.L_SUPPKEY, limit input to 1 row(s) per chunk (cost=33963.20 rows=330097) (actual time=246.460..246.460 rows=1 loops=1)
-> Table scan on l (cost=33963.20 rows=330097) (actual time=0.109..186.665 rows=330122 loops=1)