Say I have a sequence of queries that progressively get more expensive. I can join all these with a union but I’m only interested in the top 10 results so I add a LIMIT. The query looks something like this:
(SELECT col1, col2 FROM table WHERE colx = 'x')
UNION
(SELECT col1, col2 FROM table WHERE colx LIKE '%x%')
UNION
(SELECT col1, col2 FROM table WHERE colx LIKE '%x%' AND unindexedcol LIKE '%y%')
LIMIT 10
I know that this is not guaranteed to be the top 10 from the first query as the MySQL documentation states
UNION by default produces an unordered
set of rows
but in practice it appears that the results are ordered select 1 followed by select 2 etc until the limit is reached.
So does MySQL execute the queries sequentially and stop when it hits the limit? If not then what is a better way to execute this style of query where only a subset of results are needed and prioritisation of less expensive queries is preferred to minimize execution time?
I have made a test to demonstrate MySQL does not optimize that kind of query:
First of all I execute this query:
Then I watch the values of @a1 and @a2 variables:
In my tests they are a1 = 81 and a2 = 467.
So the single selects of union query are not limited.