I want to understand the following.
Assume that I have a complicated query with let's say a join of 5 tables a group by summations and order by.
Letting aside any optimizations to the query itself e.g. indexes etc.
Is there any significant performance benefit using LIMIT
? I assume that all the query (and results) must be processed before LIMIT is applied, so using a LIMIT to retrieve a subset of the results, does this offer any significant/noticable improvement?
Mysql – Does using LIMIT improve the performance and is it noticeable
join;MySQLperformance
Related Question
- Mysql – Indexes involved in intervals collision detection
- MySQL 5.1 -> 5.6 problem, select distinct order by limit query stops using index
- Sql-server – Performance of a=0 and b=0 and … z=0 vs a+b+c+d=0
- Mysql – Order by reduces performance of a grouped result set
- Mysql – Index optimization for IN, BETWEEN, ORDER BY and LIMIT query
- Mysql – Duplicate results in thesql query when try to sort by with limit and offset
- Mysql – Will performance and speed improve when retrieving data from a .txt file instead of the Database
Best Answer
If you want to take advantage of
LIMIT
to improve performance, you needLIMIT
beforeJOIN
These principles can go a long way if you can orchestrate them.
I learned these concepts by watching this YouTube Video (listen carefully through the French accent)
I used those concepts to answer a very tough StackOverflow question about getting the top 40 articles from some tables : May 12, 2011 : Fetching a Single Row from Join Table.
In my answer to that question (May 16, 2011), I wrote the following query and tested it thoroughly:
Please notice the line in the query with the
LIMIT
This subquery is buried three levels deep. This allowed me to get the last 40 articles using
LIMIT
. Then, I performed the necessary JOINs afterwards.LESSONS LEARNED
LIMIT
inside subqueries may not always be the answer because of the cardinality of indexes, the data content, and the result set size from theLIMIT
. If you have all your "ducks in a row" (Have the four principles in mind for your query), you can get surprisingly good results.LIMIT
by gathering keys only.