PostgreSQL ORDER BY Performance Optimization
Why ORDER BY Slows Queries
Sorting large datasets requires memory and may cause disk-based sorting if work_mem is insufficient.
Use Index for Sorting
Create an index matching the ORDER BY column.
CREATE INDEX idx_users_created_at
ON users(created_at);
Combine ORDER BY and LIMIT
Using LIMIT reduces sorting overhead significantly.
Increase work_mem Carefully
SET work_mem = '64MB';