Optimizing Subqueries


Development is ongoing, so no optimization tip is reliable for the long term. Some interesting tricks that you might want to play with are:

The above tricks may cause programs to go faster or slower. Using MariaDB facilities like the BENCHMARK() function, you can get an idea about what helps in your own situation. Don't worry too much about transforming to joins except for compatibility with older versions.

Some optimizations that MariaDB itself will make are:

  1. MySQL will execute non-correlated subqueries only once, (use EXPLAIN to make sure that a given subquery really is non-correlated),
  2. MySQL will rewrite IN/ALL/ANY/SOME subqueries in an attempt to take advantage of the possibility that the select-list columns in the subquery are indexed,
  3. MySQL will replace subqueries of the form
    ... IN (SELECT indexed_column FROM single_table ...)
    

    with an index-lookup function, which EXPLAIN will describe as a special join type,

  4. MySQL will enhance expressions of the form
    value {ALL|ANY|SOME} {> | < | >= | <=} (non-correlated subquery)
    

    with an expression involving MIN or MAX (unless NULLs or empty sets are involved). For example,

    WHERE 5 > ALL (SELECT x FROM t)
    

    might be treated as

    WHERE 5 > (SELECT MAX(x) FROM t)
    

There is a chapter titled How MariaDB Transforms Subqueries in the MariaDB Internals Manual, which you can find by downloading the MariaDB source package and looking for a file named internals.texi.

Retornar