天天看點

PostgreSQL 11 preview - Incremental Sort(排序優化)

标簽

PostgreSQL , 增量排序

https://github.com/digoal/blog/blob/master/201803/20180323_04.md#%E8%83%8C%E6%99%AF 背景

當我們需要對資料進行排序時,通常加速的方法是建索引,走索引就快了對吧。

PostgreSQL排序的能力還是很強大的:

《PostgreSQL 11 preview - 并行排序、并行索引 (性能線性暴增) 單執行個體100億TOP-K僅40秒》

通常情況下,如果要讓排序用上索引,那麼索引必須與排序字段一緻才行。

那麼這種情況能不能用到索引呢?

create index idx on tbl(a1,a2);       select * from tbl order by a1,a2,a3,a4;           

PostgreSQL增加了一種排序方法Incremental Sort,即使索引隻包含了一部分,也能用它來排序,隻要包含的部分是排序鍵的前序列即可。

換句話說說a1,a2已經在索引中有序了,隻是a3,a4需要排,是以可以根據索引順序取出,然後對A3,A4來排序。

更加适合A1,A2較少唯一值的場景。

patch中提到的執行計劃如下

https://www.postgresql.org/message-id/flat/CAPpHfds1waRZ=NOmueYq0sx1ZSCnt+5QJvizT8ndT2=etZEeAQ@mail.gmail.com#CAPpHfds1waRZ=NOmueYq0sx1ZSCnt+5QJvizT8ndT2=etZEeAQ@mail.gmail.com
SELECT * FROM s_1 ORDER BY a, b                                                                          QUERY       PLAN       -------------------------------------------------------------------------------------------------------------------------------------------------        Limit  (cost=1588080.84..1588080.84 rows=1 width=20) (actualtime=5874.527..5874.527 rows=0 loops=1)          ->  Incremental Sort  (cost=119371.51..1488081.45 rows=9999939 width=20) (actual time=202.842..5653.224 rows=10000000 loops=1)                Sort Key: s_1.a, s_1.b                Presorted Key: s_1.a                Sort Method: external merge  Disk: 29408kB                Sort Groups: 11                ->  Index Scan using s_1_a_idx on s_1  (cost=0.43..323385.52rows=9999939 width=20) (actual time=0.051..1494.105 rows=10000000 loops=1)        Planning time: 0.269 ms        Execution time: 5877.367 ms       (9 rows)           

非驅動列索引優化其他例子

《PostgreSQL Oracle 相容性之 - INDEX SKIP SCAN (遞歸查詢變态優化) 非驅動列索引掃描優化》

https://github.com/digoal/blog/blob/master/201803/20180323_04.md#%E5%8F%82%E8%80%83 參考

繼續閱讀