Speeding up sorting

The work_mem variable does not only speed up grouping. It can also have a very nice impact on simple things such as sorting, which is an essential mechanism mastered by every database system in the world.

The following query shows a simple operation using the default setting of 4 MB:

test=# SET work_mem TO default; 
SET
test=# EXPLAIN ANALYZE SELECT * FROM t_test ORDER BY name, id;                       QUERY PLAN -----------------------------------------------------------------  Sort (cost=24111.14..24611.14 rows=200000 width=9)       (actual time=219.298..235.008 rows=200000 loops=1)       Sort Key: name, id       Sort Method: external sort Disk: 3712kB       -> Seq Scan on t_test          (cost=0.00..3082.00 rows=200000 width=9)  (actual time=0.006..13.807 rows=200000 ...

Get Mastering PostgreSQL 10 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.