ORDER BY and GROUP BY Using an Index (Avoid Filesort)
When the index is already in the order you ask for, the database skips the sort. How to remove "Using filesort" and "Using temporary" from EXPLAIN.
In this chapter
ORDER BY and GROUP BY can use the leaf order
More on Indexes: how queries use them
- Why an Index Lookup Is Still Slow: Key Lookups Explained
- Covering Index in SQL Explained with Examples
- Composite Index and the Leftmost Prefix Rule Explained
- Index Range Scan Explained: BETWEEN, > and < on a B-Tree
- B-Tree vs Hash Index: Which to Use and Why
- Why Is MySQL Not Using My Index? Common Reasons
Keep learning
Overview
ORDER BY customer_id, created_at ✓ Same direction as the index. Read forwards. ORDER BY customer_id DESC, created_at DESC ✓ Exactly the reverse. Read backwards. An index can be walked either way. ORDER BY customer_id, created_at DESC ✕ Directions are mixed. The index has to be created as (customer_id, created_at DESC) to match. ORDER BY created_at ✕ The index starts with customer_id, so created_at alone is not in order. chapters · indexes ORDER BY and GROUP BY can use the leaf order A sort is a separate pass over the rows. An index that is already in the requested order makes that pass unnecessary.
1. Pick a query, see whether it needs a sort
The index is (customer_id, created_at): sorted by customer, and by date inside each customer. The numbers show the order the entries are read in.
2. ASC, DESC and mixed directions
Index (customer_id, created_at), both ascending Sort needed? MySQL before version 8.0 accepted DESC in an index definition but ignored it. From 8.0 the direction is stored, and PostgreSQL, SQL Server and Oracle always honoured it.
3. The range that breaks the order
Sorted ✓ One shop is one block, and inside it the dates are in order. Sort needed ✕ A range of shops spans several blocks. Shop 3's dates start over from the beginning, so the combined rows are out of order. If you expected the index order but see a sort in EXPLAIN, rewrite the ORDER BY to match the full index definition. If the sort goes away, the index was not usable for your original ordering. If it stays, the optimizer simply thought sorting was cheaper.
4. GROUP BY and DISTINCT read the same order
SELECT DISTINCT country FROM users and SELECT country FROM users GROUP BY country run the same way, so everything below applies to both. Grouping is cheap when equal values sit next to each other: the engine walks the index, keeps one counter, and starts a new one when the value changes. When equal values are scattered, it has to keep a running total for every group in a temporary table. Which index lets the engine count while it walks? GROUP BY customer_id (customer_id, created_at) ✓ Each customer is one block. Count while walking, no temporary table. (shop_id, customer_id) ✓ The equality column comes before the group column. Shop 2 is one block and the customers inside it are in order. WHERE created_at >= ? GROUP BY customer_id (created_at, customer_id) ✕ Entries come out in date order, so one customer's rows are scattered. The engine needs a temporary table. Same query ◐ Groups stream, but the engine reads the whole index and tests every date. Good for a wide date range, wasteful for a narrow one. SELECT customer_id, AVG(amount) … GROUP BY customer_id (customer_id, amount) ✓ The aggregated column goes last, so the leaf has everything and the table is never visited. Without amount in the index, every entry costs a table read. The rule is the same one as for sorting: equality columns first, then the grouping columns in the order of the GROUP BY, then any column you aggregate. A range condition on a column before the grouping columns scatters the groups, so it breaks the streaming. In EXPLAIN, MySQL shows Using temporary when it has to build the scratch table, and PostgreSQL shows HashAggregate instead of GroupAggregate over an index scan. The planner can still pick the scratch table when it thinks that is cheaper. ! A sort is cheap only while it fits in memory When the rows to sort are more than sort_buffer_size (MySQL, 256KB by default) or work_mem (PostgreSQL, 4MB by default), the engine writes sorted chunks to disk and merges them. A LIMIT does not fix that: every matching row is still read and fed to the sort, even though a top-N heap only keeps N of them. If the matching set is large, build the index that returns rows in order. Spilled sorts are covered in temp files.
More courses
- Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
- Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
- React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
- System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
- NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
- Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
- Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
- AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
- Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
- TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
- CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
- Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
- Docker — What an image is, why layers cache, and how containers find each other on a network.
- Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
- Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
- AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
- Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.