SELECT
s and Other Queries
EXPLAIN
Syntax (Get Information About a SELECT
)
SELECT
Queries
WHERE
Clauses
IS NULL
DISTINCT
LEFT JOIN
and RIGHT JOIN
ORDER BY
LIMIT
INSERT
Queries
UPDATE
Queries
DELETE
Queries
WHERE
Clauses
The WHERE
optimisations are put in the SELECT
part here because
they are mostly used with SELECT
, but the same optimisations apply for
WHERE
in DELETE
and UPDATE
statements.
Also note that this section is incomplete. MySQL does many optimisations, and we have not had time to document them all.
Some of the optimisations performed by MySQL are listed here:
((a AND b) AND c OR (((a AND b) AND (c AND d)))) -> (a AND b AND c) OR (a AND b AND c AND d)
(a<b AND b=c) AND a=5 -> b>5 AND b=c AND a=5
(B>=5 AND B=5) OR (B=6 AND 5=5) OR (B=7 AND 5=6) -> B=5 OR B=6
COUNT(*)
on a single table without a WHERE
is retrieved
directly from the table information for MyISAM
and HEAP
tables.
This is also done for any NOT NULL
expression when used with only one
table.
SELECT
statements are impossible and returns no rows.
HAVING
is merged with WHERE
if you don't use GROUP BY
or group functions (COUNT()
, MIN()
...).
WHERE
is constructed to get a fast
WHERE
evaluation for each sub-join and also to skip records as
soon as possible.
WHERE
clause on a UNIQUE
index, or a PRIMARY KEY
, where all index parts are used with constant
expressions and the index parts are defined as NOT NULL
.
mysql> SELECT * FROM t WHERE primary_key=1; mysql> SELECT * FROM t1,t2 -> WHERE t1.primary_key=1 AND t2.primary_key=t1.id;
ORDER BY
and in GROUP
BY
come from the same table, then this table is preferred first when
joining.
ORDER BY
clause and a different GROUP BY
clause, or if the ORDER BY
or GROUP BY
contains columns
from tables other than the first table in the join queue, a temporary
table is created.
SQL_SMALL_RESULT
, MySQL will use an in-memory
temporary table.
HAVING
clause
are skipped.
Some examples of queries that are very fast:
mysql> SELECT COUNT(*) FROM tbl_name; mysql> SELECT MIN(key_part1),MAX(key_part1) FROM tbl_name; mysql> SELECT MAX(key_part2) FROM tbl_name -> WHERE key_part_1=constant; mysql> SELECT ... FROM tbl_name -> ORDER BY key_part1,key_part2,... LIMIT 10; mysql> SELECT ... FROM tbl_name -> ORDER BY key_part1 DESC,key_part2 DESC,... LIMIT 10;
The following queries are resolved using only the index tree (assuming the indexed columns are numeric):
mysql> SELECT key_part1,key_part2 FROM tbl_name WHERE key_part1=val; mysql> SELECT COUNT(*) FROM tbl_name -> WHERE key_part1=val1 AND key_part2=val2; mysql> SELECT key_part2 FROM tbl_name GROUP BY key_part1;
The following queries use indexing to retrieve the rows in sorted order without a separate sorting pass:
mysql> SELECT ... FROM tbl_name -> ORDER BY key_part1,key_part2,... ; mysql> SELECT ... FROM tbl_name -> ORDER BY key_part1 DESC,key_part2 DESC,... ;