We recently moved our database from MariaDB to AWS Amazon Aurora RDS (MySQL). We observed something strange in a set of queries. We have two queries that are very quick, but when together as nested subquery it takes ages to finish.
Here id
is the primary key of the table
SELECT * FROM users where id in(SELECT max(id) FROM users where id = 1);
SELECT * FROM users where id in(SELECT id FROM users where id = 1);
SELECT max(id) FROM users where id = 1;
execution time is ~130ms
SELECT id FROM users where id = 1;
execution time is ~130ms
We believe it has to do something with the type of value returned by max
that is causing the indexing to be ignored when running the outer query from results of the sub query.
All the above queries are simplified for illustration of the problem. The original queries have more clauses as well as 100s of millions of rows. The issue did not exist prior to the migration and worked fine in MariaDB.
— RESULTS FROM MariaDB —
2
Answers
MySQL seems to optimize less efficient compared to MariaDB (int this case).
When doing this in MySQL (see: DBFIDDLE1), the execution plans look like:
MAX
:MAX
:While MariaDB (see: DBFIDDLE2 does have a better looking plan when using MAX:
EDIT: Because of time (some lack of it 😉) I now add some info
When looking at the EXECUTION PLAN from MariaDB, which has 1 extra step, I tried to do the same in MySQL. Above query has an even bigger execution plan, but tests show that it performs better. (for explain plans, see: DBFIDDLE1a)
One step more does not mean that things get slower.
MySQL takes about 2-3 seconds on the query using the MAX, and MariaDB does execute the same in under 10 msecs. But this is performance, and time may vary on different systems.
Is strange. Since it is looking only at rows where id = 1, then "max" is obviously "1". So is the min. And the average.
Perhaps you wanted:
Is there an index on
id
? Perhaps thePRIMARY KEY
? If not, then that might explain the sluggishness.This can be done much faster (against assuming an index):
Does that give you what you want?
To discuss this further, please provide
SHOW CREATE TABLE users