Why MySQL LIMIT Can Reverse ORDER BY in LEFT JOIN Queries
The author discovers a puzzling MySQL bug where moving the LIMIT clause outside a nested SELECT causes the final result set to be ordered incorrectly, explains how ORDER BY inside subqueries is ignored during LEFT JOIN processing, and recommends placing ORDER BY and LIMIT at the outermost query level.
I wrote a rather stupid bug today and documented it to avoid repeating the mistake.
When writing a paginated query that orders records by timestamp descending, the original SQL was:
select
record.a,
y.c
from
(
select
a,b
from
x
order by timestamp desc
limit 0,10
) record
left join y
on record.b = y.d;Later, new requirements added WHERE conditions, so the LIMIT 0,10 was moved outside the subquery, but the ORDER BY remained inside. The result unexpectedly became ascending instead of descending.
Rolling back to the original query and moving only the LIMIT to the outermost level revealed that the timestamp ordering became ascending, indicating the problem lies in the placement of LIMIT.
Removing LIMIT altogether made the timestamps appear unordered, suggesting MySQL may reorder rows based on the joined table's indexed columns when no LIMIT is present.
Further investigation showed that MySQL's ORDER BY clause inside a subquery does not guarantee ordering of the final result of a LEFT JOIN, because the outer query cannot see the inner ordering.
Additionally, without LIMIT, MySQL may optimize the join by not iterating over the left table in its original order, similar to Java's reordering optimizations.
Therefore, the simplest and most reliable solution is to place both ORDER BY and LIMIT clauses at the outermost query level; this does not significantly affect performance as long as appropriate indexes exist.
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 Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
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.
