Does MySQL close the ORDER BY clause?

Given this SQL:

SELECT * FROM mytable ORDER BY mycolumn, RAND()

Assuming it mycolumncontains only unique values โ€‹โ€‹(and therefore contains enough information to execute ORDER BY), does MySQL short-circuit the operation and skip evaluating the rest?

+3
source share
2 answers

I think this is the answer. Mysql uses different plans and cannot perform lazy evaluations (o "hort-circuit").

mysql> explain select * from avatar  order by id;
+----+-------------+--------+-------+---------------+---------+---------+------+-------+-------+
| id | select_type | table  | type  | possible_keys | key     | key_len | ref  | rows  | Extra |
+----+-------------+--------+-------+---------------+---------+---------+------+-------+-------+
|  1 | SIMPLE      | avatar | index | NULL          | PRIMARY | 8       | NULL | 28777 |       |
+----+-------------+--------+-------+---------------+---------+---------+------+-------+-------+
1 row in set (0.00 sec)

mysql> explain select * from avatar  order by id, name;
+----+-------------+--------+------+---------------+------+---------+------+-------+----------------+
| id | select_type | table  | type | possible_keys | key  | key_len | ref  | rows  | Extra          |
+----+-------------+--------+------+---------------+------+---------+------+-------+----------------+
|  1 | SIMPLE      | avatar | ALL  | NULL          | NULL | NULL    | NULL | 28777 | Using filesort |
+----+-------------+--------+------+---------------+------+---------+------+-------+----------------+
1 row in set (0.00 sec)
mysql> explain select * from avatar  order by id, RAND();
+----+-------------+--------+------+---------------+------+---------+------+-------+---------------------------------+
| id | select_type | table  | type | possible_keys | key  | key_len | ref  | rows  | Extra                           |
+----+-------------+--------+------+---------------+------+---------+------+-------+---------------------------------+
|  1 | SIMPLE      | avatar | ALL  | NULL          | NULL | NULL    | NULL | 28782 | Using temporary; Using filesort |
+----+-------------+--------+------+---------------+------+---------+------+-------+---------------------------------+
1 row in set (0.00 sec)
+2
source

Experience shows that this is not so, even if it mycolumnis the primary key.

0
source

Source: https://habr.com/ru/post/1741184/


All Articles