How MySQL Executes ORDER BY: Index vs Sorting Algorithms Explained
MySQL's ORDER BY can either use an ordered index to return rows directly or apply one of two sorting algorithms—original and the MySQL 4.1 enhanced version—to sort data in memory, with the newer method reducing I/O by avoiding a second table read at the cost of higher memory usage.
MySQL implements ORDER BY using two approaches.
(1) Retrieve rows in order directly from an ordered index, requiring no additional sorting.
(2) Apply MySQL's sorting algorithm to the result set and then return the sorted rows.
When no suitable index exists, MySQL resorts to sorting.
Current sorting is performed by two algorithms:
(1) Extract the rows that satisfy the filter and the sorting column together with their row pointers, sort them in the sort buffer, then fetch the remaining columns from the table using the pointers.
(2) Extract the sorting column and required other columns in one pass, store the non‑sorted columns in a memory area, sort only the sorting column in the sort buffer, and finally combine the sorted pointers with the stored columns to produce the result set.
The first algorithm has been available since early MySQL versions; the second was introduced in MySQL 4.1. The latter reduces a second table access after sorting, saving I/O at the cost of higher memory usage—a classic space‑for‑time trade‑off.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java High-Performance Architecture
Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
