The optimizer handles derived tables (subqueries in the
FROM clause) as follows:
The optimizer postpones materialization of subqueries in the
FROMclause until their contents are needed during query execution, which improves performance.
EXPLAINqueries, delay of materialization may result in not having to do it at all. Consider a query that joins the result of a subquery in the
FROMclause to another table: If the optimizer processes that other table first and finds that it returns no rows, the join need not be carried out further and the optimizer can completely skip materializing the subquery.
During query execution, the optimizer may add an index to a derived table to speed up row retrieval from it.
EXPLAIN SELECT * FROM (SELECT * FROM t1) AS derived_t1;
The optimizer avoids materializing the subquery by delaying it
until the result is needed during
SELECT execution. In this case,
the query is not executed (because it occurs in an
EXPLAIN statement), so the
result is never needed.
Even for queries that are executed, delay of subquery
materialization may enable the optimizer to avoid
materialization entirely. Consider the following query, which
joins the result of a subquery in the
clause to another table:
SELECT * FROM t1 JOIN (SELECT t2.f1 FROM t2) AS derived_t2 ON t1.f2=derived_t2.f1 WHERE t1.f1 > 0;
If the optimization processes
t1 first and
WHERE clause produces an empty result,
the join must necessarily be empty and the subquery need not
For cases when a derived table requires materialization, the
optimizer may add an index to the materialized table to speed
up access to it. If such an index enables
ref access to the table, it
can greatly reduce amount of data read during query execution.
Consider the following query:
SELECT * FROM t1 JOIN (SELECT DISTINCT f1 FROM t2) AS derived_t2 ON t1.f1=derived_t2.f1;
The optimizer constructs an index over column
doing so would enable use of
ref access for the lowest
cost execution plan. After adding the index, the optimizer can
treat the materialized derived table the same as a regular
table with an index, and it benefits similarly from the
generated index. The overhead of index creation is negligible
compared to the cost of query execution without the index. If
ref access would result in
higher cost than some other access method, the optimizer
creates no index and loses nothing.