The symptom
A sort in a plan means the engine collected rows and put them in order while the query ran. It appears as Sort in PostgreSQL and SQL Server, Using filesort in MySQL, SORT ORDER BY in Oracle and USE TEMP B-TREE FOR ORDER BY in SQLite. Sorting needs every input row before it can return the first one, uses memory in proportion to the input, and writes to disk when the memory runs out.
The sort that hurts most is the one behind "latest 20" queries: the engine reads and sorts thousands of rows to return a handful. An index that stores rows in the wanted order lets it read the 20 rows and stop. The query plan viewer flags sorts that take a large share of the query. The examples use a shop schema with 400,000 orders, 40,000 of them for customer 1.
Diagnose it
Find the sort and count its input
The query asks for one customer's 20 most recent orders. With no useful index, PostgreSQL reads all of the customer's rows and sorts them:
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT order_id, order_date, total FROM orders
WHERE customer_id = 1
ORDER BY order_date DESC LIMIT 20;
Limit (cost=8009.29..8011.62 rows=20 width=18) (actual rows=20.00 loops=1)
-> Gather Merge (cost=8009.29..12672.49 rows=40039 width=18) (actual rows=20.00 loops=1)
Workers Planned: 2
Workers Launched: 2
-> Sort (cost=7009.26..7050.97 rows=16683 width=18) (actual rows=16.33 loops=3)
Sort Key: order_date DESC
Sort Method: top-N heapsort Memory: 27kB
Worker 0: Sort Method: top-N heapsort Memory: 27kB
Worker 1: Sort Method: top-N heapsort Memory: 27kB
-> Parallel Seq Scan on orders (cost=0.00..6565.33 rows=16683 width=18) (actual rows=13333.33 loops=3)
Filter: (customer_id = 1)
Rows Removed by Filter: 120000
Sort Method says how the sort ran. top-N heapsort keeps only the best 20 rows in memory and is cheap in memory, but it still reads every input row. quicksort sorted everything in memory, and external merge went to disk, which is covered under sort and hash spills.
MySQL reports the sort in the Extra column:
EXPLAIN SELECT order_id, order_date, total FROM orders
WHERE customer_id = 1
ORDER BY order_date DESC LIMIT 20\G
type: ALL
key: NULL
rows: 399054
Extra: Using where; Using filesort
Oracle shows SORT ORDER BY STOPKEY when the sort only has to keep the first rows:
EXPLAIN PLAN FOR
SELECT order_id, order_date, total FROM orders
WHERE customer_id = 1
ORDER BY order_date DESC FETCH FIRST 20 ROWS ONLY;
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);
| Id | Operation | Name | Rows | Bytes |TempSpc| Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 20 | 360 | | 927 (1)| 00:00:01 |
|* 1 | COUNT STOPKEY | | | | | | |
| 2 | VIEW | | 40234 | 707K| | 927 (1)| 00:00:01 |
|* 3 | SORT ORDER BY STOPKEY| | 40234 | 903K| 1440K| 927 (1)| 00:00:01 |
|* 4 | TABLE ACCESS FULL | ORDERS | 40234 | 903K| | 650 (1)| 00:00:01 |
SQLite builds a temporary B-tree to do the ordering:
EXPLAIN QUERY PLAN
SELECT order_id, order_date, total FROM orders
WHERE customer_id = 1
ORDER BY order_date DESC LIMIT 20;
|--SCAN orders
`--USE TEMP B-TREE FOR ORDER BY
In SQL Server the operator is Sort、または Sort with the logical operation TopN Sort when the query has TOP:
SET STATISTICS IO ON;
SET STATISTICS XML ON;
GO
SELECT TOP (20) OrderId, OrderDate, Total FROM dbo.Orders
WHERE CustomerId = 1
ORDER BY OrderDate DESC;
Table 'Orders'. Scan count 8, logical reads 2709, physical reads 0
Decide whether the sort is the cost
Compare the rows going into the sort with the rows the query returns. Sorting 40,000 rows to return 20 is waste an index can remove. Sorting 200 rows is nothing. In a plan with timings, subtract the time of the sort's input from the time of the sort itself; often the scan below is the slow part and the sort only looks expensive because it sits on top of it.
Fix it
Create an index that returns the rows in order
Put the equality columns from the WHERE clause first, then the ORDER BY columns. Within one customer the index is then already in date order, and the engine reads 20 entries from the end:
CREATE INDEX orders_customer_date_idx ON orders (customer_id, order_date);
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT order_id, order_date, total FROM orders
WHERE customer_id = 1
ORDER BY order_date DESC LIMIT 20;
Limit (cost=0.42..9.91 rows=20 width=18) (actual rows=20.00 loops=1)
-> Index Scan Backward using orders_customer_date_idx on orders (cost=0.42..19000.55 rows=40040 width=18) (actual rows=20.00 loops=1)
Index Cond: (customer_id = 1)
Index Searches: 1
CREATE INDEX orders_customer_date_idx ON orders (customer_id, order_date);
EXPLAIN SELECT order_id, order_date, total FROM orders
WHERE customer_id = 1
ORDER BY order_date DESC LIMIT 20\G
type: ref
key: orders_customer_date_idx
rows: 81566
Extra: Backward index scan
CREATE INDEX IX_Orders_Customer_Date ON dbo.Orders (CustomerId, OrderDate) INCLUDE (Total);
GO
SELECT TOP (20) OrderId, OrderDate, Total FROM dbo.Orders
WHERE CustomerId = 1
ORDER BY OrderDate DESC;
Table 'Orders'. Scan count 1, logical reads 3, physical reads 0
CREATE INDEX orders_customer_date_idx ON orders (customer_id, order_date);
EXPLAIN PLAN FOR
SELECT order_id, order_date, total FROM orders
WHERE customer_id = 1
ORDER BY order_date DESC FETCH FIRST 20 ROWS ONLY;
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 2 | 36 | 5 (0)| 00:00:01 |
|* 1 | COUNT STOPKEY | | | | | |
| 2 | VIEW | | 2 | 36 | 5 (0)| 00:00:01 |
| 3 | TABLE ACCESS BY INDEX ROWID | ORDERS | 40234 | 903K| 5 (0)| 00:00:01 |
|* 4 | INDEX RANGE SCAN DESCENDING| ORDERS_CUSTOMER_DATE_IDX | 2 | | 3 (0)| 00:00:01 |
CREATE INDEX orders_customer_date_idx ON orders (customer_id, order_date);
EXPLAIN QUERY PLAN
SELECT order_id, order_date, total FROM orders
WHERE customer_id = 1
ORDER BY order_date DESC LIMIT 20;
`--SEARCH orders USING INDEX orders_customer_date_idx (customer_id=?)
An index can be read in either direction, so an ascending index serves ORDER BY order_date DESC. Direction only matters when the ORDER BY mixes ascending and descending columns; then the index has to mix them the same way, as described under descending indexes.
Sort fewer or narrower rows
When no index can supply the order (the sort key is computed, or the filter is a range on a different column), make the sort smaller. Filter before sorting, and select only the columns you need: a sort carries every selected column with each row, so SELECT * through a sort moves far more data than three columns do.
Drop an ORDER BY nobody needs
Check that the order is used. An ORDER BY inside a subquery or view that the outer query re-sorts or aggregates is work for nothing, as is one feeding an application that sorts again in the grid.
When to leave it alone
Leave a sort that handles few rows, runs in memory and takes a small part of the query time. A report that sorts its whole result once is doing what it was asked. Every index added to avoid a sort is paid for on every write to the table, so add one for queries that run often, not for a sort that costs 20 milliseconds once a day.
The checklist
Work through it in order. Each step gives you the evidence for the next one.
- Find the sort operator and note how many rows enter it and how many the query returns.
- Check the sort method: in memory, top-N, or on disk.
- Compare the sort's own time with the time of the step below it.
- Create an index with the equality filter columns first and the ORDER BY columns after.
- If no index fits, reduce the rows and columns that reach the sort.
- Re-capture the plan and confirm the sort is gone or smaller.
Questions that come up
What does Using filesort mean in MySQL?
It means MySQL sorts the rows itself instead of reading them in order from an index. Despite the name it does not necessarily use a file: small sorts run in memory inside the sort buffer. It is a cost to look at when many rows are sorted.
How do I get rid of a Sort operator?
Give the engine an index whose column order matches the query: the columns compared with = in the WHERE clause first, then the ORDER BY columns in the same order. The rows then come out of the index already sorted and the plan no longer needs to sort.
Can an ascending index be used for ORDER BY ... DESC?
Yes. Engines read an index backwards as easily as forwards, so a single-column or same-direction ORDER BY is served by an ascending index. Only a mix such as ORDER BY a ASC, b DESC needs an index declared with the same mix.
Why does the plan sort when there is no ORDER BY?
GROUP BY, DISTINCT, UNION, window functions and merge joins can all sort their input. The sort belongs to whichever of those sits above it in the plan. An index on the grouping or join columns can remove it in the same way.
Is top-N heapsort a problem?
Usually not for memory, because it keeps only the rows it will return. It still reads every candidate row, so the cost is in the scan underneath. An index that provides the order lets the query stop after the first N rows.