7.2. Optimizing SELECT and Other Statements

MySQL 5.0

7.2. Optimizing SELECT and Other Statements

First, one factor affects all statements: The more complex your permissions setup, the more overhead you have. Using simpler permissions when you issue statements enables MySQL to reduce permission-checking overhead when clients execute statements. For example, if you do not grant any table-level or column-level privileges, the server need not ever check the contents of the and tables. Similarly, if you place no resource limits on any accounts, the server does not have to perform resource counting. If you have a very high statement-processing load, it may be worth the time to use a simplified grant structure to reduce permission-checking overhead.

If your problem is with a specific MySQL expression or function, you can perform a timing test by invoking the function using the mysql client program. Its syntax is ,). The return value is always zero, but mysql prints a line displaying approximately how long the statement took to execute. For example:

mysql> 
+------------------------+
| BENCHMARK(1000000,1+1) |
+------------------------+
|                      0 |
+------------------------+
1 row in set (0.32 sec)

This result was obtained on a Pentium II 400MHz system. It shows that MySQL can execute 1,000,000 simple addition expressions in 0.32 seconds on that system.

All MySQL functions should be highly optimized, but there may be some exceptions. is an excellent tool for finding out if some function is a problem for your queries.

7.2.1. Optimizing Queries with EXPLAIN

EXPLAIN 

Or:

EXPLAIN [EXTENDED] SELECT 

The statement can be used either as a synonym for or as a way to obtain information about how MySQL executes a statement:

  • is synonymous with or .

  • When you precede a statement with the keyword , MySQL displays information from the optimizer about the query execution plan. That is, MySQL explains how it would process the , including information about how tables are joined and in which order.

This section describes the second use of for obtaining query execution plan information. For a description of the and statements, see Section 13.3.1, “ Syntax”, and Section 13.5.4.3, “ Syntax”.

With the help of , you can see where you should add indexes to tables to get a faster that uses indexes to find rows. You can also use to check whether the optimizer joins the tables in an optimal order. To force the optimizer to use a join order corresponding to the order in which the tables are named in the statement, begin the statement with rather than just .

If you have a problem with indexes not being used when you believe that they should be, you should run to update table statistics such as cardinality of keys, that can affect the choices the optimizer makes. See Section 13.5.2.1, “ Syntax”.

returns a row of information for each table used in the statement. The tables are listed in the output in the order that MySQL would read them while processing the query. MySQL resolves all joins using a single-sweep multi-join method. This means that MySQL reads a row from the first table, and then finds a matching row in the second table, the third table, and so on. When all tables are processed, MySQL outputs the selected columns and backtracks through the table list until a table is found for which there are more matching rows. The next row is read from this table and the process continues with the next table.

When the keyword is used, produces extra information that can be viewed by issuing a statement following the statement. This information displays how the optimizer qualifies table and column names in the statement, what the looks like after the application of rewriting and optimization rules, and possibly other notes about the optimization process.

Each output row from provides information about one table, and each row contains the following columns:

  • The identifier. This is the sequential number of the within the query.

  • The type of , which can be any of those shown in the following table:

    Simple (not using or subqueries)
    Outermost
    Second or later statement in a
    Second or later statement in a , dependent on outer query
    Result of a .
    First in subquery
    First in subquery, dependent on outer query
    Derived table (subquery in clause)

    typically signifies the use of a correlated subquery. See Section 13.2.8.7, “Correlated Subqueries”.

  • The table to which the row of output refers.

  • The join type. The different join types are listed here, ordered from the best type to the worst:

    • The table has only one row (= system table). This is a special case of the join type.

    • The table has at most one matching row, which is read at the start of the query. Because there is only one row, values from the column in this row can be regarded as constants by the rest of the optimizer. tables are very fast because they are read only once.

      is used when you compare all parts of a or index to constant values. In the following queries, can be used as a table:

      SELECT * FROM  WHERE =1;
      
      SELECT * FROM 
        WHERE =1 AND =2;
      
    • One row is read from this table for each combination of rows from the previous tables. Other than the and types, this is the best possible join type. It is used when all parts of an index are used by the join and the index is a or index.

      can be used for indexed columns that are compared using the operator. The comparison value can be a constant or an expression that uses columns from tables that are read before this table. In the following examples, MySQL can use an join to process :

      SELECT * FROM ,
        WHERE .=.;
      
      SELECT * FROM ,
        WHERE .=.
        AND .=1;
      
    • All rows with matching index values are read from this table for each combination of rows from the previous tables. is used if the join uses only a leftmost prefix of the key or if the key is not a or index (in other words, if the join cannot select a single row based on the key value). If the key that is used matches only a few rows, this is a good join type.

      can be used for indexed columns that are compared using the or operator. In the following examples, MySQL can use a join to process :

      SELECT * FROM  WHERE =;
      
      SELECT * FROM ,
        WHERE .=.;
      
      SELECT * FROM ,
        WHERE .=.
        AND .=1;
      
    • This join type is like , but with the addition that MySQL does an extra search for rows that contain values. This join type optimization is used most often in resolving subqueries. In the following examples, MySQL can use a join to process :

      SELECT * FROM 
        WHERE = OR  IS NULL;
      

      See Section 7.2.7, “ Optimization”.

    • This join type indicates that the Index Merge optimization is used. In this case, the column in the output row contains a list of indexes used, and contains a list of the longest key parts for the indexes used. For more information, see Section 7.2.6, “Index Merge Optimization”.

    • This type replaces for some subqueries of the following form:

       IN (SELECT  FROM  WHERE )
      

      is just an index lookup function that replaces the subquery completely for better efficiency.

    • This join type is similar to . It replaces subqueries, but it works for non-unique indexes in subqueries of the following form:

       IN (SELECT  FROM  WHERE )
      
    • Only rows that are in a given range are retrieved, using an index to select the rows. The column in the output row indicates which index is used. The contains the longest key part that was used. The column is for this type.

      can be used when a key column is compared to a constant using any of the , , , , , , , , , or operators:

      SELECT * FROM 
        WHERE  = 10;
      
      SELECT * FROM 
        WHERE  BETWEEN 10 and 20;
      
      SELECT * FROM 
        WHERE  IN (10,20,30);
      
      SELECT * FROM 
        WHERE = 10 AND  IN (10,20,30);
      
    • This join type is the same as , except that only the index tree is scanned. This usually is faster than because the index file usually is smaller than the data file.

      MySQL can use this join type when the query uses only columns that are part of a single index.

    • A full table scan is done for each combination of rows from the previous tables. This is normally not good if the table is the first table not marked , and usually very bad in all other cases. Normally, you can avoid by adding indexes that allow row retrieval from the table based on constant values or column values from earlier tables.

  • The column indicates which indexes MySQL can choose from use to find the rows in this table. Note that this column is totally independent of the order of the tables as displayed in the output from . That means that some of the keys in might not be usable in practice with the generated table order.

    If this column is , there are no relevant indexes. In this case, you may be able to improve the performance of your query by examining the clause to check whether it refers to some column or columns that would be suitable for indexing. If so, create an appropriate index and check the query with again. See Section 13.1.2, “ Syntax”.

    To see what indexes a table has, use .

  • The column indicates the key (index) that MySQL actually decided to use. The key is if no index was chosen. To force MySQL to use or ignore an index listed in the column, use , , or in your query. See Section 13.2.7, “ Syntax”.

    For and tables, running helps the optimizer choose better indexes. For tables, myisamchk --analyze does the same. See Section 13.5.2.1, “ Syntax”, and Section 5.10.4, “Table Maintenance and Crash Recovery”.

  • The column indicates the length of the key that MySQL decided to use. The length is if the column says . Note that the value of enables you to determine how many parts of a multiple-part key MySQL actually uses.

  • The column shows which columns or constants are compared to the index named in the column to select rows from the table.

  • The column indicates the number of rows MySQL believes it must examine to execute the query.

  • This column contains additional information about how MySQL resolves the query. Here is an explanation of the values that can appear in this column:

    • MySQL is looking for distinct values, so it stops searching for more rows for the current row combination after it has found the first matching row.

    • MySQL was able to do a optimization on the query and does not examine more rows in this table for the previous row combination after it finds one row that matches the criteria. Here is an example of the type of query that can be optimized this way:

      SELECT * FROM t1 LEFT JOIN t2 ON t1.id=t2.id
        WHERE t2.id IS NULL;
      

      Assume that is defined as . In this case, MySQL scans and looks up the rows in using the values of . If MySQL finds a matching row in , it knows that can never be , and does not scan through the rest of the rows in that have the same value. In other words, for each row in , MySQL needs to do only a single lookup in , regardless of how many rows actually match in .

    • )

      MySQL found no good index to use, but found that some of indexes might be used after column values from preceding tables are known. For each row combination in the preceding tables, MySQL checks whether it is possible to use a or access method to retrieve rows. This is not very fast, but is faster than performing a join with no index at all. The applicability criteria are as described in Section 7.2.5, “Range Optimization”, and Section 7.2.6, “Index Merge Optimization”, with the exception that all column values for the preceding table are known and considered to be constants.

    • MySQL must do an extra pass to find out how to retrieve the rows in sorted order. The sort is done by going through all rows according to the join type and storing the sort key and pointer to the row for all rows that match the clause. The keys then are sorted and the rows are retrieved in sorted order. See Section 7.2.12, “ Optimization”.

    • The column information is retrieved from the table using only information in the index tree without having to do an additional seek to read the actual row. This strategy can be used when the query uses only columns that are part of a single index.

    • To resolve the query, MySQL needs to create a temporary table to hold the result. This typically happens if the query contains and clauses that list columns differently.

    • A clause is used to restrict which rows to match against the next table or send to the client. Unless you specifically intend to fetch or examine all rows from the table, you may have something wrong in your query if the value is not and the table join type is or .

      If you want to make your queries as fast as possible, you should look out for values of and .

    • , ,

      These indicate how index scans are merged for the join type. See Section 7.2.6, “Index Merge Optimization”, for more information.

    • Similar to the way of accessing a table, indicates that MySQL found an index that can be used to retrieve all columns of a or query without any extra disk access to the actual table. Additionally, the index is used in the most efficient way so that for each group, only a few index entries are read. For details, see Section 7.2.13, “ Optimization”.

    • This item applies to tables only. It means that MySQL Cluster is using condition pushdown to improve the efficiency of a direct comparison () between a non-indexed column and a constant. In such cases, the condition is “pushed down” to the cluster's data nodes where it is evaluated in all partitions simultaneously. This eliminates the need to send non-matching rows over the network, and can speed up such queries by a factor of 5 to 10 times over cases where condition pushdown could be but is not used.

      Suppose that you have a Cluster table defined as follows:

      CREATE TABLE t1 (
          a INT, 
          b INT, 
          KEY(a)
      ) ENGINE=NDBCLUSTER;
      

      In this case, condition pushdown can be used with a query such as this one:

      SELECT a,b FROM t1 WHERE b = 10;
      

      This can be seen in the output of , as shown here:

      mysql> 
      *************************** 1. row ***************************
                 id: 1
        select_type: SIMPLE
              table: t1
               type: ALL
      possible_keys: NULL
                key: NULL
            key_len: NULL
                ref: NULL
               rows: 10
              Extra: Using where with pushed condition
      

      Condition pushdown cannot be used with either of these two queries:

      SELECT a,b FROM t1 WHERE a = 10;
      SELECT a,b FROM t1 WHERE b + 1 = 10;
      

      With regard to the first of these two queries, condition pushdown is not applicable because an index exists on column . In the case of the second query, a condition pushdown cannot be employed because the comparison involving the non-indexed column is an indirect one. (However, it would apply if you were to reduce to in the clause.)

      However, a condition pushdown may also be employed when an indexed column column is compared with a constant using a or operator:

      mysql> 
      *************************** 1. row ***************************
                 id: 1
        select_type: SIMPLE
              table: t1
               type: range
      possible_keys: a
                key: a
            key_len: 5
                ref: NULL
               rows: 2
              Extra: Using where with pushed condition
      

      With regard to condition pushdown, keep in mind that:

      • Condition pushdown is relevant to MySQL Cluster only, and does not occur when executing queries against tables using any other storage engine.

      • Condition pushdown capability is not used by default. To enable it, you can start mysqld with the option, or execute the following statement:

        SET engine_condition_pushdown=On;
        

        Note: Condition pushdown is not supported for columns of any of the or types.

      Condition pushdown, , and were all introduced in MySQL 5.0 Cluster.

You can get a good indication of how good a join is by taking the product of the values in the column of the output. This should tell you roughly how many rows MySQL must examine to execute the query. If you restrict queries with the system variable, this row product also is used to determine which multiple-table statements to execute and which to abort. See Section 7.5.2, “Tuning Server Parameters”.

The following example shows how a multiple-table join can be optimized progressively based on the information provided by .

Suppose that you have the statement shown here and that you plan to examine it using :

EXPLAIN SELECT tt.TicketNumber, tt.TimeIn,
               tt.ProjectReference, tt.EstimatedShipDate,
               tt.ActualShipDate, tt.ClientID,
               tt.ServiceCodes, tt.RepetitiveID,
               tt.CurrentProcess, tt.CurrentDPPerson,
               tt.RecordVolume, tt.DPPrinted, et.COUNTRY,
               et_1.COUNTRY, do.CUSTNAME
        FROM tt, et, et AS et_1, do
        WHERE tt.SubmitTime IS NULL
          AND tt.ActualPC = et.EMPLOYID
          AND tt.AssignedPC = et_1.EMPLOYID
          AND tt.ClientID = do.CUSTNMBR;

For this example, make the following assumptions:

  • The columns being compared have been declared as follows:

    Table Column Data Type
  • The tables have the following indexes:

    Table Index
    (primary key)
    (primary key)
  • The values are not evenly distributed.

Initially, before any optimizations have been performed, the statement produces the following information:

table type possible_keys key  key_len ref  rows  Extra
et    ALL  PRIMARY       NULL NULL    NULL 74
do    ALL  PRIMARY       NULL NULL    NULL 2135
et_1  ALL  PRIMARY       NULL NULL    NULL 74
tt    ALL  AssignedPC,   NULL NULL    NULL 3872
           ClientID,
           ActualPC
      range checked for each record (key map: 35)

Because is for each table, this output indicates that MySQL is generating a Cartesian product of all the tables; that is, every combination of rows. This takes quite a long time, because the product of the number of rows in each table must be examined. For the case at hand, this product is 74 × 2135 × 74 × 3872 = 45,268,558,720 rows. If the tables were bigger, you can only imagine how long it would take.

One problem here is that MySQL can use indexes on columns more efficiently if they are declared as the same type and size. In this context, and are considered the same if they are declared as the same size. is declared as and is , so there is a length mismatch.

To fix this disparity between column lengths, use to lengthen from 10 characters to 15 characters:

mysql> 

Now and are both . Executing the statement again produces this result:

table type   possible_keys key     key_len ref         rows    Extra
tt    ALL    AssignedPC,   NULL    NULL    NULL        3872    Using
             ClientID,                                         where
             ActualPC
do    ALL    PRIMARY       NULL    NULL    NULL        2135
      range checked for each record (key map: 1)
et_1  ALL    PRIMARY       NULL    NULL    NULL        74
      range checked for each record (key map: 1)
et    eq_ref PRIMARY       PRIMARY 15      tt.ActualPC 1

This is not perfect, but is much better: The product of the values is less by a factor of 74. This version executes in a couple of seconds.

A second alteration can be made to eliminate the column length mismatches for the and comparisons:

mysql> 
    ->                

After that modification, produces the output shown here:

table type   possible_keys key      key_len ref           rows Extra
et    ALL    PRIMARY       NULL     NULL    NULL          74
tt    ref    AssignedPC,   ActualPC 15      et.EMPLOYID   52   Using
             ClientID,                                         where
             ActualPC
et_1  eq_ref PRIMARY       PRIMARY  15      tt.AssignedPC 1
do    eq_ref PRIMARY       PRIMARY  15      tt.ClientID   1

At this point, the query is optimized almost as well as possible. The remaining problem is that, by default, MySQL assumes that values in the column are evenly distributed, and that is not the case for the table. Fortunately, it is easy to tell MySQL to analyze the key distribution:

mysql> 

With the additional index information, the join is perfect and produces this result:

table type   possible_keys key     key_len ref           rows Extra
tt    ALL    AssignedPC    NULL    NULL    NULL          3872 Using
             ClientID,                                        where
             ActualPC
et    eq_ref PRIMARY       PRIMARY 15      tt.ActualPC   1
et_1  eq_ref PRIMARY       PRIMARY 15      tt.AssignedPC 1
do    eq_ref PRIMARY       PRIMARY 15      tt.ClientID   1

Note that the column in the output from is an educated guess from the MySQL join optimizer. You should check whether the numbers are even close to the truth by comparing the product with the actual number of rows that the query returns. If the numbers are quite different, you might get better performance by using in your statement and trying to list the tables in a different order in the clause.

7.2.2. Estimating Query Performance

In most cases, you can estimate query performance by counting disk seeks. For small tables, you can usually find a row in one disk seek (because the index is probably cached). For bigger tables, you can estimate that, using B-tree indexes, you need this many seeks to find a row: ) / log( / 3 × 2 / ( + )) + 1.

In MySQL, an index block is usually 1,024 bytes and the data pointer is usually four bytes. For a 500,000-row table with an index length of three bytes (the size of ), the formula indicates = seeks.

This index would require storage of about 500,000 × 7 × 3/2 = 5.2MB (assuming a typical index buffer fill ratio of 2/3), so you probably have much of the index in memory and so need only one or two calls to read data to find the row.

For writes, however, you need four seek requests to find where to place a new index value and normally two seeks to update the index and write the row.

Note that the preceding discussion does not mean that your application performance slowly degenerates by log . As long as everything is cached by the OS or the MySQL server, things become only marginally slower as the table gets bigger. After the data gets too big to be cached, things start to go much slower until your applications are bound only by disk seeks (which increase by log ). To avoid this, increase the key cache size as the data grows. For tables, the key cache size is controlled by the system variable. See Section 7.5.2, “Tuning Server Parameters”.

7.2.3. Speed of SELECT Queries

In general, when you want to make a slow query faster, the first thing to check is whether you can add an index. All references between different tables should usually be done with indexes. You can use the statement to determine which indexes are used for a . See Section 7.2.1, “Optimizing Queries with , and Section 7.4.5, “How MySQL Uses Indexes”.

Some general tips for speeding up queries on tables:

  • To help MySQL better optimize queries, use or run myisamchk --analyze on a table after it has been loaded with data. This updates a value for each index part that indicates the average number of rows that have the same value. (For unique indexes, this is always 1.) MySQL uses this to decide which index to choose when you join two tables based on a non-constant expression. You can check the result from the table analysis by using and examining the value. myisamchk --description --verbose shows index distribution information.

  • To sort an index and data according to an index, use myisamchk --sort-index --sort-records=1 (assuming that you want to sort on index 1). This is a good way to make queries faster if you have a unique index from which you want to read all rows in order according to the index. The first time you sort a large table this way, it may take a long time.

7.2.4. WHERE Clause Optimization

This section discusses optimizations that can be made for processing clauses. The examples use statements, but the same optimizations apply for clauses in and statements.

Work on the MySQL optimizer is ongoing, so this section is incomplete. MySQL performs a great many optimizations, not all of which are documented here.

Some of the optimizations performed by MySQL follow:

  • Removal of unnecessary parentheses:

       ((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)
    
  • Constant folding:

       (a<b AND b=c) AND a=5
    -> b>5 AND b=c AND a=5
    
  • Constant condition removal (needed because of constant folding):

       (B>=5 AND B=5) OR (B=6 AND 5=5) OR (B=7 AND 5=6)
    -> B=5 OR B=6
    
  • Constant expressions used by indexes are evaluated only once.

  • on a single table without a is retrieved directly from the table information for and tables. This is also done for any expression when used with only one table.

  • Early detection of invalid constant expressions. MySQL quickly detects that some statements are impossible and returns no rows.

  • is merged with if you do not use or aggregate functions (, , and so on).

  • For each table in a join, a simpler is constructed to get a fast evaluation for the table and also to skip rows as soon as possible.

  • All constant tables are read first before any other tables in the query. A constant table is any of the following:

    • An empty table or a table with one row.

    • A table that is used with a clause on a or a index, where all index parts are compared to constant expressions and are defined as .

    All of the following tables are used as constant tables:

    SELECT * FROM t WHERE =1;
    SELECT * FROM t1,t2
      WHERE t1.=1 AND t2.=t1.id;
    
  • The best join combination for joining the tables is found by trying all possibilities. If all columns in and clauses come from the same table, that table is preferred first when joining.

  • If there is an clause and a different clause, or if the or contains columns from tables other than the first table in the join queue, a temporary table is created.

  • If you use the option, MySQL uses an in-memory temporary table.

  • Each table index is queried, and the best index is used unless the optimizer believes that it is more efficient to use a table scan. At one time, a scan was used based on whether the best index spanned more than 30% of the table, but a fixed percentage no longer determines the choice between using an index or a scan. The optimizer now is more complex and bases its estimate on additional factors such as table size, number of rows, and I/O block size.

  • In some cases, MySQL can read rows from the index without even consulting the data file. If all columns used from the index are numeric, only the index tree is used to resolve the query.

  • Before each row is output, those that do not match the clause are skipped.

Some examples of queries that are very fast:

SELECT COUNT(*) FROM ;

SELECT MIN(),MAX() FROM ;

SELECT MAX() FROM 
  WHERE =;

SELECT ... FROM 
  ORDER BY ,,... LIMIT 10;

SELECT ... FROM 
  ORDER BY  DESC,  DESC, ... LIMIT 10;

MySQL resolves the following queries using only the index tree, assuming that the indexed columns are numeric:

SELECT , FROM  WHERE =;

SELECT COUNT(*) FROM 
  WHERE = AND =;

SELECT  FROM  GROUP BY ;

The following queries use indexing to retrieve the rows in sorted order without a separate sorting pass:

SELECT ... FROM 
  ORDER BY ,,... ;

SELECT ... FROM 
  ORDER BY  DESC,  DESC, ... ;

7.2.5. Range Optimization

The access method uses a single index to retrieve a subset of table rows that are contained within one or several index value intervals. It can be used for a single-part or multiple-part index. The following sections give a detailed description of how intervals are extracted from the clause.

7.2.5.1. The Range Access Method for Single-Part Indexes

For a single-part index, index value intervals can be conveniently represented by corresponding conditions in the clause, so we speak of range conditions rather than “intervals.

The definition of a range condition for a single-part index is as follows:

  • For both and indexes, comparison of a key part with a constant value is a range condition when using the , , , , or operators.

  • For indexes, comparison of a key part with a constant value is a range condition when using the , , , , , , or operators, or ' (where ' does not start with a wildcard).

  • For all types of indexes, multiple range conditions combined with or form a range condition.

Constant value” in the preceding descriptions means one of the following:

  • A constant from the query string

  • A column of a or table from the same join

  • The result of an uncorrelated subquery

  • Any expression composed entirely from subexpressions of the preceding types

Here are some examples of queries with range conditions in the clause:

SELECT * FROM t1
  WHERE  > 1 
  AND  < 10;

SELECT * FROM t1 
  WHERE  = 1 
  OR  IN (15,18,20);

SELECT * FROM t1 
  WHERE  LIKE 'ab%' 
  OR  BETWEEN 'bar' AND 'foo';

Note that some non-constant values may be converted to constants during the constant propagation phase.

MySQL tries to extract range conditions from the clause for each of the possible indexes. During the extraction process, conditions that cannot be used for constructing the range condition are dropped, conditions that produce overlapping ranges are combined, and conditions that produce empty ranges are removed.

Consider the following statement, where is an indexed column and is not indexed:

SELECT * FROM t1 WHERE
  (key1 < 'abc' AND (key1 LIKE 'abcde%' OR key1 LIKE '%b')) OR
  (key1 < 'bar' AND nonkey = 4) OR
  (key1 < 'uux' AND key1 > 'z');

The extraction process for key is as follows:

  1. Start with original clause:

    (key1 < 'abc' AND (key1 LIKE 'abcde%' OR key1 LIKE '%b')) OR
    (key1 < 'bar' AND nonkey = 4) OR
    (key1 < 'uux' AND key1 > 'z')
    
  2. Remove and because they cannot be used for a range scan. The correct way to remove them is to replace them with , so that we do not miss any matching rows when doing the range scan. Having replaced them with , we get:

    (key1 < 'abc' AND (key1 LIKE 'abcde%' OR TRUE)) OR
    (key1 < 'bar' AND TRUE) OR
    (key1 < 'uux' AND key1 > 'z')
    
  3. Collapse conditions that are always true or false:

    • is always true

    • is always false

    Replacing these conditions with constants, we get:

    (key1 < 'abc' AND TRUE) OR (key1 < 'bar' AND TRUE) OR (FALSE)
    

    Removing unnecessary and constants, we obtain:

    (key1 < 'abc') OR (key1 < 'bar')
    
  4. Combining overlapping intervals into one yields the final condition to be used for the range scan:

    (key1 < 'bar')
    

In general (and as demonstrated by the preceding example), the condition used for a range scan is less restrictive than the clause. MySQL performs an additional check to filter out rows that satisfy the range condition but not the full clause.

The range condition extraction algorithm can handle nested / constructs of arbitrary depth, and its output does not depend on the order in which conditions appear in clause.

7.2.5.2. The Range Access Method for Multiple-Part Indexes

Range conditions on a multiple-part index are an extension of range conditions for a single-part index. A range condition on a multiple-part index restricts index rows to lie within one or several key tuple intervals. Key tuple intervals are defined over a set of key tuples, using ordering from the index.

For example, consider a multiple-part index defined as , , ), and the following set of key tuples listed in key order:

    
  NULL       1          'abc'
  NULL       1          'xyz'
  NULL       2          'foo'
   1         1          'abc'
   1         1          'xyz'
   1         2          'abc'
   2         1          'aaa'

The condition = 1 defines this interval:

(1,-inf,-inf) <= (,,) < (1,+inf,+inf)

The interval covers the 4th, 5th, and 6th tuples in the preceding data set and can be used by the range access method.

By contrast, the condition = 'abc' does not define a single interval and cannot be used by the range access method.

The following descriptions indicate how range conditions work for multiple-part indexes in greater detail.

  • For indexes, each interval containing identical values can be used. This means that the interval can be produced only for conditions in the following form:

          
    AND   
    AND ...
    AND   ;
    

    Here, , , … are constants, is one of the , , or comparison operators, and the conditions cover all index parts. (That is, there are conditions, one for each part of an -part index.) For example, the following is a range condition for a three-part index:

     = 1 AND  IS NULL AND  = 'foo'
    

    For the definition of what is considered to be a constant, see Section 7.2.5.1, “The Range Access Method for Single-Part Indexes”.

  • For a index, an interval might be usable for conditions combined with , where each condition compares a key part with a constant value using , , , , , , , , , , or ' (where ' does not start with a wildcard). An interval can be used as long as it is possible to determine a single key tuple containing all rows that match the condition (or two intervals if or is used). For example, for this condition:

     = 'foo' AND  >= 10 AND  > 10
    

    The single interval is:

    ('foo',10,10) < (,,) < ('foo',+inf,+inf)
    

    It is possible that the created interval contains more rows than the initial condition. For example, the preceding interval includes the value , which does not satisfy the original condition.

  • If conditions that cover sets of rows contained within intervals are combined with , they form a condition that covers a set of rows contained within the union of their intervals. If the conditions are combined with , they form a condition that covers a set of rows contained within the intersection of their intervals. For example, for this condition on a two-part index:

    ( = 1 AND  < 2) OR ( > 5)
    

    The intervals are:

    (1,-inf) < (,) < (1,2)
    (5,-inf) < (,)
    

    In this example, the interval on the first line uses one key part for the left bound and two key parts for the right bound. The interval on the second line uses only one key part. The column in the output indicates the maximum length of the key prefix used.

    In some cases, may indicate that a key part was used, but that might be not what you would expect. Suppose that and can be . Then the column displays two key part lengths for the following condition:

     >= 1 AND  < 2
    

    But, in fact, the condition is converted to this:

     >= 1 AND  IS NOT NULL
    

Section 7.2.5.1, “The Range Access Method for Single-Part Indexes”, describes how optimizations are performed to combine or eliminate intervals for range conditions on a single-part index. Analogous steps are performed for range conditions on multiple-part indexes.

7.2.6. Index Merge Optimization

The Index Merge method is used to retrieve rows with several scans and to merge their results into one. The merge can produce unions, intersections, or unions-of-intersections of its underlying scans.

Note: If you have upgraded from a previous version of MySQL, you should be aware that this type of join optimization is first introduced in MySQL 5.0, and represents a significant change in behavior with regard to indexes. (Formerly, MySQL was able to use at most only one index for each referenced table.)

In output, the Index Merge method appears as in the column. In this case, the column contains a list of indexes used, and contains a list of the longest key parts for those indexes.

Examples:

SELECT * FROM  WHERE  = 10 OR  = 20;

SELECT * FROM 
  WHERE ( = 10 OR  = 20) AND =30;

SELECT * FROM t1, t2
  WHERE (t1. IN (1,2) OR t1. LIKE '%')
  AND t2.=t1.;

SELECT * FROM t1, t2
  WHERE t1.=1
  AND (t2.=t1. OR t2.=t1.);

The Index Merge method has several access algorithms (seen in the field of output):

The following sections describe these methods in greater detail.

Note: The Index Merge optimization algorithm has the following known deficiencies:

  • If a range scan is possible on some key, an Index Merge is not considered. For example, consider this query:

    SELECT * FROM t1 WHERE (goodkey1 < 10 OR goodkey2 < 20) AND badkey < 30;
    

    For this query, two plans are possible:

    • An Index Merge scan using the condition.

    • A range scan using the condition.

    However, the optimizer considers only the second plan. If that is not what you want, you can make the optimizer consider Index Merge by using or . The following queries are executed using Index Merge:

    SELECT * FROM t1 FORCE INDEX(index_for_goodkey1,index_for_goodkey2)
      WHERE (goodkey1 < 10 OR goodkey2 < 20) AND badkey < 30;
    
    SELECT * FROM t1 IGNORE INDEX(index_for_badkey)
      WHERE (goodkey1 < 10 OR goodkey2 < 20) AND badkey < 30;
    
  • If your query has a complex clause with deep / nesting and MySQL doesn't choose the optimal plan, try distributing terms using the following identity laws:

    ( AND ) OR  = ( OR ) AND ( OR )
    ( OR ) AND  = ( AND ) OR ( AND )
    
  • Index Merge is not applicable to fulltext indexes. We plan to extend it to cover these in a future MySQL release.

The choice between different possible variants of the Index Merge access method and other access methods is based on cost estimates of various available options.

7.2.6.1. The Index Merge Intersection Access Algorithm

This access algorithm can be employed when a clause was converted to several range conditions on different keys combined with , and each condition is one of the following:

  • In this form, where the index has exactly parts (that is, all index parts are covered):

    = AND = ... AND =
    
  • Any range condition over a primary key of an or table.

Examples:

SELECT * FROM  WHERE  < 10 AND =20;

SELECT * FROM 
  WHERE (=1 AND =2) AND =2;

The Index Merge intersection algorithm performs simultaneous scans on all used indexes and produces the intersection of row sequences that it receives from the merged index scans.

If all columns used in the query are covered by the used indexes, full table rows are not retrieved ( output contains in field in this case). Here is an example of such a query:

SELECT COUNT(*) FROM t1 WHERE key1=1 AND key2=1;

If the used indexes don't cover all columns used in the query, full rows are retrieved only when the range conditions for all used keys are satisfied.

If one of the merged conditions is a condition over a primary key of an or table, it is not used for row retrieval, but is used to filter out rows retrieved using other conditions.

7.2.6.2. The Index Merge Union Access Algorithm

The applicability criteria for this algorithm are similar to those for the Index Merge method intersection algorithm. The algorithm can be employed when the table's clause was converted to several range conditions on different keys combined with , and each condition is one of the following:

  • In this form, where the index has exactly parts (that is, all index parts are covered):

    = AND = ... AND =
    
  • Any range condition over a primary key of an or table.

  • A condition for which the Index Merge method intersection algorithm is applicable.

Examples:

SELECT * FROM t1 WHERE =1 OR =2 OR =3;

SELECT * FROM  WHERE (=1 AND =2) OR
  (='foo' AND ='bar') AND =5;

7.2.6.3. The Index Merge Sort-Union Access Algorithm

This access algorithm is employed when the clause was converted to several range conditions combined by , but for which the Index Merge method union algorithm is not applicable.

Examples:

SELECT * FROM  WHERE  < 10 OR  < 20;

SELECT * FROM 
  WHERE ( > 10 OR  = 20) AND =30;

The difference between the sort-union algorithm and the union algorithm is that the sort-union algorithm must first fetch row IDs for all rows and sort them before returning any rows.

7.2.7. IS NULL Optimization

MySQL can perform the same optimization on that it can use for . For example, MySQL can use indexes and ranges to search for with .

Examples:

SELECT * FROM  WHERE  IS NULL;

SELECT * FROM  WHERE  <=> NULL;

SELECT * FROM 
  WHERE = OR = OR  IS NULL;

If a clause includes a condition for a column that is declared as , that expression is optimized away. This optimization does not occur in cases when the column might produce anyway; for example, if it comes from a table on the right side of a .

MySQL can also optimize the combination = AND IS NULL, a form that is common in resolved subqueries. shows when this optimization is used.

This optimization can handle one for any key part.

Some examples of queries that are optimized, assuming that there is an index on columns and of table :

SELECT * FROM t1 WHERE t1.a= OR t1.a IS NULL;

SELECT * FROM t1, t2 WHERE t1.a=t2.a OR t2.a IS NULL;

SELECT * FROM t1, t2
  WHERE (t1.a=t2.a OR t2.a IS NULL) AND t2.b=t1.b;

SELECT * FROM t1, t2
  WHERE t1.a=t2.a AND (t2.b=t1.b OR t2.b IS NULL);

SELECT * FROM t1, t2
  WHERE (t1.a=t2.a AND t2.a IS NULL AND ...)
  OR (t1.a=t2.a AND t2.a IS NULL AND ...);

works by first doing a read on the reference key, and then a separate search for rows with a key value.

Note that the optimization can handle only one level. In the following query, MySQL uses key lookups only on the expression and is not able to use the key part on :

SELECT * FROM t1, t2
  WHERE (t1.a=t2.a AND t2.a IS NULL)
  OR (t1.b=t2.b AND t2.b IS NULL);

7.2.8. DISTINCT Optimization

combined with needs a temporary table in many cases.

Because may use , you should be aware of how MySQL works with columns in or clauses that are not part of the selected columns. See Section 12.10.3, “ and with Hidden Fields”.

In most cases, a clause can be considered as a special case of . For example, the following two queries are equivalent:

SELECT DISTINCT c1, c2, c3 FROM t1 WHERE c1 > ;

SELECT c1, c2, c3 FROM t1 WHERE c1 >  GROUP BY c1, c2, c3;

Due to this equivalence, the optimizations applicable to queries can be also applied to queries with a clause. Thus, for more details on the optimization possibilities for queries, see Section 7.2.13, “ Optimization”.

When combining with , MySQL stops as soon as it finds unique rows.

If you do not use columns from all tables named in a query, MySQL stops scanning any unused tables as soon as it finds the first match. In the following case, assuming that is used before (which you can check with ), MySQL stops reading from (for any particular row in ) when it finds the first row in :

SELECT DISTINCT t1.a FROM t1, t2 where t1.a=t2.a;

7.2.9. LEFT JOIN and RIGHT JOIN Optimization

MySQL implements an LEFT JOIN join_condition as follows:

  • Table is set to depend on table and all tables on which depends.

  • Table is set to depend on all tables (except ) that are used in the condition.

  • The condition is used to decide how to retrieve rows from table . (In other words, any condition in the clause is not used.)

  • All standard join optimizations are performed, with the exception that a table is always read after all tables on which it depends. If there is a circular dependence, MySQL issues an error.

  • All standard optimizations are performed.

  • If there is a row in that matches the clause, but there is no row in that matches the condition, an extra row is generated with all columns set to .

  • If you use to find rows that do not exist in some table and you have the following test: IS NULL in the part, where is a column that is declared as , MySQL stops searching for more rows (for a particular key combination) after it has found one row that matches the condition.

The implementation of is analogous to that of with the roles of the tables reversed.

The join optimizer calculates the order in which tables should be joined. The table read order forced by or helps the join optimizer do its work much more quickly, because there are fewer table permutations to check. Note that this means that if you do a query of the following type, MySQL does a full scan on because the forces it to be read before :

SELECT *
  FROM a JOIN b LEFT JOIN c ON (c.key=a.key) LEFT JOIN d ON (d.key=a.key)
  WHERE b.key=d.key;

The fix in this case is reverse the order in which and are listed in the clause:

SELECT *
  FROM b JOIN a LEFT JOIN c ON (c.key=a.key) LEFT JOIN d ON (d.key=a.key)
  WHERE b.key=d.key;

For a , if the condition is always false for the generated row, the is changed to a normal join. For example, the clause would be false in the following query if were :

SELECT * FROM t1 LEFT JOIN t2 ON (column1) WHERE t2.column2=5;

Therefore, it is safe to convert the query to a normal join:

SELECT * FROM t1, t2 WHERE t2.column2=5 AND t1.column1=t2.column1;

This can be made faster because MySQL can use table before table if doing so would result in a better query plan. To force a specific table order, use .

7.2.10. Nested Join Optimization

As of MySQL 5.0.1, the syntax for expressing joins allows nested joins. The following discussion refers to the join syntax described in Section 13.2.7.1, “ Syntax”.

The syntax of is extended in comparison with the SQL Standard. The latter accepts only , not a list of them inside a pair of parentheses. This is a conservative extension if we consider each comma in a list of items as equivalent to an inner join. For example:

SELECT * FROM t1 LEFT JOIN (t2, t3, t4)
                 ON (t2.a=t1.a AND t3.b=t1.b AND t4.c=t1.c)

is equivalent to:

SELECT * FROM t1 LEFT JOIN (t2 CROSS JOIN t3 CROSS JOIN t4)
                 ON (t2.a=t1.a AND t3.b=t1.b AND t4.c=t1.c)

In MySQL, is a syntactic equivalent to (they can replace each other). In standard SQL, they are not equivalent. is used with an clause; is used otherwise.

In versions of MySQL prior to 5.0.1, parentheses in were just omitted and all join operations were grouped to the left. In general, parentheses can be ignored in join expressions containing only inner join operations.

After removing parentheses and grouping operations to the left, the join expression:

t1 LEFT JOIN (t2 LEFT JOIN t3 ON t2.b=t3.b OR t2.b IS NULL)
   ON t1.a=t2.a

transforms into the expression:

(t1 LEFT JOIN t2 ON t1.a=t2.a) LEFT JOIN t3
    ON t2.b=t3.b OR t2.b IS NULL

Yet, the two expressions are not equivalent. To see this, suppose that the tables , , and have the following state:

  • Table contains rows ,

  • Table contains row

  • Table contains row

In this case, the first expression returns a result set including the rows , , whereas the second expression returns the rows , :

mysql> 
    -> 
    ->      
    ->      
    ->      
+------+------+------+------+
| a    | a    | b    | b    |
+------+------+------+------+
|    1 |    1 |  101 |  101 |
|    2 | NULL | NULL | NULL |
+------+------+------+------+

mysql> 
    -> 
    ->      
    ->      
+------+------+------+------+
| a    | a    | b    | b    |
+------+------+------+------+
|    1 |    1 |  101 |  101 |
|    2 | NULL | NULL |  101 |
+------+------+------+------+

In the following example, an outer join operation is used together with an inner join operation:

t1 LEFT JOIN (t2, t3) ON t1.a=t2.a

That expression cannot be transformed into the following expression:

t1 LEFT JOIN t2 ON t1.a=t2.a, t3.

For the given table states, the two expressions return different sets of rows:

mysql> 
    -> 
+------+------+------+------+
| a    | a    | b    | b    |
+------+------+------+------+
|    1 |    1 |  101 |  101 |
|    2 | NULL | NULL | NULL |
+------+------+------+------+

mysql> 
    -> 
+------+------+------+------+
| a    | a    | b    | b    |
+------+------+------+------+
|    1 |    1 |  101 |  101 |
|    2 | NULL | NULL |  101 |
+------+------+------+------+

Therefore, if we omit parentheses in a join expression with outer join operators, we might change the result set for the original expression.

More exactly, we cannot ignore parentheses in the right operand of the left outer join operation and in the left operand of a right join operation. In other words, we cannot ignore parentheses for the inner table expressions of outer join operations. Parentheses for the other operand (operand for the outer table) can be ignored.

The following expression:

(t1,t2) LEFT JOIN t3 ON P(t2.b,t3.b)

is equivalent to this expression:

t1, t2 LEFT JOIN t3 ON P(t2.b,t3.b)

for any tables and any condition over attributes and .

Whenever the order of execution of the join operations in a join expression () is not from left to right, we talk about nested joins. Consider the following queries:

SELECT * FROM t1 LEFT JOIN (t2 LEFT JOIN t3 ON t2.b=t3.b) ON t1.a=t2.a
  WHERE t1.a > 1

SELECT * FROM t1 LEFT JOIN (t2, t3) ON t1.a=t2.a
  WHERE (t2.b=t3.b OR t2.b IS NULL) AND t1.a > 1

Those queries are considered to contain these nested joins:

t2 LEFT JOIN t3 ON t2.b=t3.b
t2, t3

The nested join is formed in the first query with a left join operation, whereas in the second query it is formed with an inner join operation.

In the first query, the parentheses can be omitted: The grammatical structure of the join expression will dictate the same order of execution for join operations. For the second query, the parentheses cannot be omitted, although the join expression here can be interpreted unambiguously without them. (In our extended syntax the parentheses in of the second query are required, although theoretically the query could be parsed without them: We still would have unambiguous syntactical structure for the query because and would play the role of the left and right delimiters for the expression .)

The preceding examples demonstrate these points:

  • For join expressions involving only inner joins (and not outer joins), parentheses can be removed. You can remove parentheses and evaluate left to right (or, in fact, you can evaluate the tables in any order).

  • The same is not true, in general, for outer joins or for outer joins mixed with inner joins. Removal of parentheses may change the result.

Queries with nested outer joins are executed in the same pipeline manner as queries with inner joins. More exactly, a variation of the nested-loop join algorithm is exploited. Recall by what algorithmic schema the nested-loop join executes a query. Suppose that we have a join query over 3 tables of the form:

SELECT * FROM T1 INNER JOIN T2 ON P1(T1,T2)
                 INNER JOIN T3 ON P2(T2,T3)
  WHERE P(T1,T2,T3).

Here, and are some join conditions (on expressions), whereas is a condition over columns of tables .

The nested-loop join algorithm would execute this query in the following manner:

FOR each row t1 in T1 {
  FOR each row t2 in T2 such that P1(t1,t2) {
    FOR each row t3 in T3 such that P2(t2,t3) {
      IF P(t1,t2,t3) {
         t:=t1||t2||t3; OUTPUT t;
      }
    }
  }
}

The notation means “a row constructed by concatenating the columns of rows , , and .” In some of the following examples, where a row name appears means that is used for each column of that row. For example, means “a row constructed by concatenating the columns of rows and , and for each column of .

Now let's consider a query with nested outer joins:

SELECT * FROM T1 LEFT JOIN
              (T2 LEFT JOIN T3 ON P2(T2,T3))
              ON P1(T1,T2)
  WHERE P(T1,T2,T3).

For this query, we modify the nested-loop pattern to get:

FOR each row t1 in T1 {
  BOOL f1:=FALSE;
  FOR each row t2 in T2 such that P1(t1,t2) {
    BOOL f2:=FALSE;
    FOR each row t3 in T3 such that P2(t2,t3) {
      IF P(t1,t2,t3) {
        t:=t1||t2||t3; OUTPUT t;
      }
      f2=TRUE;
      f1=TRUE;
    }
    IF (!f2) {
      IF P(t1,t2,NULL) {
        t:=t1||t2||NULL; OUTPUT t;
      }
      f1=TRUE;
    }
  }
  IF (!f1) {
    IF P(t1,NULL,NULL) {
      t:=t1||NULL||NULL; OUTPUT t;
    }
  }
}

In general, for any nested loop for the first inner table in an outer join operation, a flag is introduced that is turned off before the loop and is checked after the loop. The flag is turned on when for the current row from the outer table a match from the table representing the inner operand is found. If at the end of the loop cycle the flag is still off, no match has been found for the current row of the outer table. In this case, the row is complemented by values for the columns of the inner tables. The result row is passed to the final check for the output or into the next nested loop, but only if the row satisfies the join condition of all embedded outer joins.

In our example, the outer join table expressed by the following expression is embedded:

(T2 LEFT JOIN T3 ON P2(T2,T3))

Note that for the query with inner joins, the optimizer could choose a different order of nested loops, such as this one:

FOR each row t3 in T3 {
  FOR each row t2 in T2 such that P2(t2,t3) {
    FOR each row t1 in T1 such that P1(t1,t2) {
      IF P(t1,t2,t3) {
         t:=t1||t2||t3; OUTPUT t;
      }
    }
  }
}

For the queries with outer joins, the optimizer can choose only such an order where loops for outer tables precede loops for inner tables. Thus, for our query with outer joins, only one nesting order is possible. For the following query, the optimizer will evaluate two different nestings:

SELECT * T1 LEFT JOIN (T2,T3) ON P1(T1,T2) AND P2(T1,T3)
  WHERE P(T1,T2,T3)

The nestings are these:

FOR each row t1 in T1 {
  BOOL f1:=FALSE;
  FOR each row t2 in T2 such that P1(t1,t2) {
    FOR each row t3 in T3 such that P2(t1,t3) {
      IF P(t1,t2,t3) {
        t:=t1||t2||t3; OUTPUT t;
      }
      f1:=TRUE
    }
  }
  IF (!f1) {
    IF P(t1,NULL,NULL) {
      t:=t1||NULL||NULL; OUTPUT t;
    }
  }
}

and:

FOR each row t1 in T1 {
  BOOL f1:=FALSE;
  FOR each row t3 in T3 such that P2(t1,t3) {
    FOR each row t2 in T2 such that P1(t1,t2) {
      IF P(t1,t2,t3) {
        t:=t1||t2||t3; OUTPUT t;
      }
      f1:=TRUE
    }
  }
  IF (!f1) {
    IF P(t1,NULL,NULL) {
      t:=t1||NULL||NULL; OUTPUT t;
    }
  }
}

In both nestings, must be processed in the outer loop because it is used in an outer join. and are used in an inner join, so that join must be processed in the inner loop. However, because the join is an inner join, and can be processed in either order.

When discussing the nested-loop algorithm for inner joins, we omitted some details whose impact on the performance of query execution may be huge. We did not mention so-called “pushed-down” conditions. Suppose that our condition can be represented by a conjunctive formula:

P(T1,T2,T2) = C1(T1) AND C2(T2) AND C3(T3).

In this case, MySQL actually uses the following nested-loop schema for the execution of the query with inner joins:

FOR each row t1 in T1 such that C1(t1) {
  FOR each row t2 in T2 such that P1(t1,t2) AND C2(t2)  {
    FOR each row t3 in T3 such that P2(t2,t3) AND C3(t3) {
      IF P(t1,t2,t3) {
         t:=t1||t2||t3; OUTPUT t;
      }
    }
  }
}

You see that each of the conjuncts , , are pushed out of the most inner loop to the most outer loop where it can be evaluated. If is a very restrictive condition, this condition pushdown may greatly reduce the number of rows from table passed to the inner loops. As a result, the execution time for the query may improve immensely.

For a query with outer joins, the condition is to be checked only after it has been found that the current row from the outer table has a match in the inner tables. Thus, the optimization of pushing conditions out of the inner nested loops cannot be applied directly to queries with outer joins. Here we have to introduce conditional pushed-down predicates guarded by the flags that are turned on when a match has been encountered.

For our example with outer joins with:

P(T1,T2,T3)=C1(T1) AND C(T2) AND C3(T3)

the nested-loop schema using guarded pushed-down conditions looks like this:

FOR each row t1 in T1 such that C1(t1) {
  BOOL f1:=FALSE;
  FOR each row t2 in T2
      such that P1(t1,t2) AND (f1?C2(t2):TRUE) {
    BOOL f2:=FALSE;
    FOR each row t3 in T3
        such that P2(t2,t3) AND (f1&&f2?C3(t3):TRUE) {
      IF (f1&&f2?TRUE:(C2(t2) AND C3(t3))) {
        t:=t1||t2||t3; OUTPUT t;
      }
      f2=TRUE;
      f1=TRUE;
    }
    IF (!f2) {
      IF (f1?TRUE:C2(t2) && P(t1,t2,NULL)) {
        t:=t1||t2||NULL; OUTPUT t;
      }
      f1=TRUE;
    }
  }
  IF (!f1 && P(t1,NULL,NULL)) {
      t:=t1||NULL||NULL; OUTPUT t;
  }
}

In general, pushed-down predicates can be extracted from join conditions such as and . In this case, a pushed-down predicate is guarded also by a flag that prevents checking the predicate for the -complemented row generated by the corresponding outer join operation.

Note that access by key from one inner table to another in the same nested join is prohibited if it is induced by a predicate from the condition. (We could use conditional key access in this case, but this technique is not employed yet in MySQL 5.0.)

7.2.11. Outer Join Simplification

Table expressions in the clause of a query are simplified in many cases.

At the parser stage, queries with right outer joins operations are converted to equivalent queries containing only left join operations. In the general case, the conversion is performed according to the following rule:

(T1, ...) RIGHT JOIN (T2,...) ON P(T1,...,T2,...) =
(T2, ...) LEFT JOIN (T1,...) ON P(T1,...,T2,...)

All inner join expressions of the form are replaced by the list , being joined as a conjunct to the condition (or to the join condition of the embedding join, if there is any).

When the optimizer evaluates plans for join queries with outer join operation, it takes into consideration only the plans where, for each such operation, the outer tables are accessed before the inner tables. The optimizer options are limited because only such plans enables us to execute queries with outer joins operations by the nested loop schema.

Suppose that we have a query of the form:

SELECT * T1 LEFT JOIN T2 ON P1(T1,T2)
  WHERE P(T1,T2) AND R(T2)

with narrowing greatly the number of matching rows from table . If we executed the query as it is, the optimizer would have no other choice besides to access table before table that may lead to a very inefficient execution plan.

Fortunately, MySQL converts such a query into a query without an outer join operation if the condition is null-rejected. A condition is called null-rejected for an outer join operation if it evaluates to or to for any -complemented row built for the operation.

Thus, for this outer join:

T1 LEFT JOIN T2 ON T1.A=T2.A

Conditions such as these are null-rejected:

T2.B IS NOT NULL,
T2.B > 3,
T2.C <= T1.C,
T2.B < 2 OR T2.C > 1

Conditions such as these are not null-rejected:

T2.B IS NULL,
T1.B < 3 OR T2.B IS NOT NULL,
T1.B < 3 OR T2.B > 3

The general rules for checking whether a condition is null-rejected for an outer join operation are simple. A condition is null-rejected in the following cases:

  • If it is of the form , where is an attribute of any of the inner tables

  • If it is a predicate containing a reference to an inner table that evaluates to when one of its arguments is

  • If it is a conjunction containing a null-rejected condition as a conjunct

  • If it is a disjunction of null-rejected conditions

A condition can be null-rejected for one outer join operation in a query and not null-rejected for another. In the query:

SELECT * FROM T1 LEFT JOIN T2 ON T2.A=T1.A
                 LEFT JOIN T3 ON T3.B=T1.B
  WHERE T3.C > 0

the condition is null-rejected for the second outer join operation but is not null-rejected for the first one.

If the condition is null-rejected for an outer join operation in a query, the outer join operation is replaced by an inner join operation.

For example, the preceding query is replaced with the query:

SELECT * FROM T1 LEFT JOIN T2 ON T2.A=T1.A
                 INNER JOIN T3 ON T3.B=T1.B
  WHERE T3.C > 0

For the original query, the optimizer would evaluate plans compatible with only one access order . For the replacing query, it additionally considers the access sequence .

A conversion of one outer join operation may trigger a conversion of another. Thus, the query:

SELECT * FROM T1 LEFT JOIN T2 ON T2.A=T1.A
                 LEFT JOIN T3 ON T3.B=T2.B
  WHERE T3.C > 0

will be first converted to the query:

SELECT * FROM T1 LEFT JOIN T2 ON T2.A=T1.A
                 INNER JOIN T3 ON T3.B=T2.B
  WHERE T3.C > 0

which is equivalent to the query:

SELECT * FROM (T1 LEFT JOIN T2 ON T2.A=T1.A), T3
  WHERE T3.C > 0 AND T3.B=T2.B

Now the remaining outer join operation can be replaced by an inner join, too, because the condition is null-rejected and we get a query without outer joins at all:

SELECT * FROM (T1 INNER JOIN T2 ON T2.A=T1.A), T3
  WHERE T3.C > 0 AND T3.B=T2.B

Sometimes we succeed in replacing an embedded outer join operation, but cannot convert the embedding outer join. The following query:

SELECT * FROM T1 LEFT JOIN
              (T2 LEFT JOIN T3 ON T3.B=T2.B)
              ON T2.A=T1.A
  WHERE T3.C > 0

is converted to:

SELECT * FROM T1 LEFT JOIN
              (T2 INNER JOIN T3 ON T3.B=T2.B)
              ON T2.A=T1.A
  WHERE T3.C > 0,

That can be rewritten only to the form still containing the embedding outer join operation:

SELECT * FROM T1 LEFT JOIN
              (T2,T3)
              ON (T2.A=T1.A AND T3.B=T2.B)
  WHERE T3.C > 0.

When trying to convert an embedded outer join operation in a query, we must take into account the join condition for the embedding outer join together with the condition. In the query:

SELECT * FROM T1 LEFT JOIN
              (T2 LEFT JOIN T3 ON T3.B=T2.B)
              ON T2.A=T1.A AND T3.C=T1.C
  WHERE T3.D > 0 OR T1.D > 0

the condition is not null-rejected for the embedded outer join, but the join condition of the embedding outer join is null-rejected. So the query can be converted to:

SELECT * FROM T1 LEFT JOIN
              (T2, T3)
              ON T2.A=T1.A AND T3.C=T1.C AND T3.B=T2.B
  WHERE T3.D > 0 OR T1.D > 0

The algorithm that converts outer join operations into inner joins was implemented in full measure, as it has been described here, in MySQL 5.0.1. MySQL 4.1 performs only some simple conversions.

7.2.12. ORDER BY Optimization

In some cases, MySQL can use an index to satisfy an clause without doing any extra sorting.

The index can also be used even if the does not match the index exactly, as long as all of the unused portions of the index and all the extra columns are constants in the clause. The following queries use the index to resolve the part:

SELECT * FROM t1 
  ORDER BY ,,... ;
    
SELECT * FROM t1 
  WHERE = 
  ORDER BY ;
    
SELECT * FROM t1 
  ORDER BY  DESC,  DESC;
    
SELECT * FROM t1
  WHERE =1 
  ORDER BY  DESC,  DESC;

In some cases, MySQL cannot use indexes to resolve the , although it still uses indexes to find the rows that match the clause. These cases include the following:

  • You use on different keys:

    SELECT * FROM t1 ORDER BY , ;
    
  • You use on non-consecutive parts of a key:

    SELECT * FROM t1 WHERE = ORDER BY ;
    
  • You mix and :

    SELECT * FROM t1 ORDER BY  DESC,  ASC;
    
  • The key used to fetch the rows is not the same as the one used in the :

    SELECT * FROM t1 WHERE = ORDER BY ;
    
  • You are joining many tables, and the columns in the are not all from the first non-constant table that is used to retrieve rows. (This is the first table in the output that does not have a join type.)

  • You have different and expressions.

  • The type of table index used does not store rows in order. For example, this is true for a index in a table.

With , you can check whether MySQL can use indexes to resolve the query. It cannot if you see in the column. See Section 7.2.1, “Optimizing Queries with .

A optimization is used that records not only the sort key value and row position, but the columns required for the query as well. This avoids reading the rows twice. The algorithm works like this:

  1. Read the rows that match the clause.

  2. For each row, record a tuple of values consisting of the sort key value and row position, and also the columns required for the query.

  3. Sort the tuples by sort key value

  4. Retrieve the rows in sorted order, but read the required columns directly from the sorted tuples rather than by accessing the table a second time.

This algorithm represents a significant improvement over that used in some older versions of MySQL.

To avoid a slowdown, this optimization is used only if the total size of the extra columns in the sort tuple does not exceed the value of the system variable. (A symptom of setting the value of this variable too high is that you should see high disk activity and low CPU activity.)

If you want to increase speed, check whether you can get MySQL to use indexes rather than an extra sorting phase. If this is not possible, you can try the following strategies:

  • Increase the size of the variable.

  • Increase the size of the variable.

  • Change to point to a dedicated filesystem with large amounts of empty space. This option accepts several paths that are used in round-robin fashion. Paths should be separated by colon characters (‘’) on Unix and semicolon characters (‘’) on Windows, NetWare, and OS/2. You can use this feature to spread the load across several directories. Note: The paths should be for directories in filesystems that are located on different physical disks, not different partitions on the same disk.

By default, MySQL sorts all , , ... queries as if you specified , , ... in the query as well. If you include an clause explicitly that contains the same column list, MySQL optimizes it away without any speed penalty, although the sorting still occurs. If a query includes but you want to avoid the overhead of sorting the result, you can suppress sorting by specifying . For example:

INSERT INTO foo
SELECT a, COUNT(*) FROM bar GROUP BY a ORDER BY NULL;

7.2.13. GROUP BY Optimization

The most general way to satisfy a clause is to scan the whole table and create a new temporary table where all rows from each group are consecutive, and then use this temporary table to discover groups and apply aggregate functions (if any). In some cases, MySQL is able to do much better than that and to avoid creation of temporary tables by using index access.

The most important preconditions for using indexes for are that all columns reference attributes from the same index, and that the index stores its keys in order (for example, this is a index and not a index). Whether use of temporary tables can be replaced by index access also depends on which parts of an index are used in a query, the conditions specified for these parts, and the selected aggregate functions.

There are two ways to execute a query via index access, as detailed in the following sections. In the first method, the grouping operation is applied together with all range predicates (if any). The second method first performs a range scan, and then groups the resulting tuples.

7.2.13.1. Loose index scan

The most efficient way to process is when the index is used to directly retrieve the group fields. With this access method, MySQL uses the property of some index types that the keys are ordered (for example, ). This property enables use of lookup groups in an index without having to consider all keys in the index that satisfy all conditions. This access method considers only a fraction of the keys in an index, so it is called a loose index scan. When there is no clause, a loose index scan reads as many keys as the number of groups, which may be a much smaller number than that of all keys. If the clause contains range predicates (see the discussion of the join type in Section 7.2.1, “Optimizing Queries with ), a loose index scan looks up the first key of each group that satisfies the range conditions, and again reads the least possible number of keys. This is possible under the following conditions:

  • The query is over a single table.

  • The includes the first consecutive parts of the index. (If, instead of , the query has a clause, all distinct attributes refer to the beginning of the index.)

  • The only aggregate functions used (if any) are and , and all of them refer to the same column.

  • Any other parts of the index than those from the referenced in the query must be constants (that is, they must be referenced in equalities with constants), except for the argument of or functions.

The output for such queries shows in the column.

The following queries fall into this category, assuming that there is an index on table :

SELECT c1, c2 FROM t1 GROUP BY c1, c2;
SELECT DISTINCT c1, c2 FROM t1;
SELECT c1, MIN(c2) FROM t1 GROUP BY c1;
SELECT c1, c2 FROM t1 WHERE c1 <  GROUP BY c1, c2;
SELECT MAX(c3), MIN(c3), c1, c2 FROM t1 WHERE c2 >  GROUP BY c1, c2;
SELECT c2 FROM t1 WHERE c1 <  GROUP BY c1, c2;
SELECT c1, c2 FROM t1 WHERE c3 =  GROUP BY c1, c2;

The following queries cannot be executed with this quick select method, for the reasons given:

  • There are aggregate functions other than or , for example:

    SELECT c1, SUM(c2) FROM t1 GROUP BY c1;
    
  • The fields in the clause do not refer to the beginning of the index, as shown here:

    SELECT c1,c2 FROM t1 GROUP BY c2, c3;
    
  • The query refers to a part of a key that comes after the part, and for which there is no equality with a constant, an example being:

    SELECT c1,c3 FROM t1 GROUP BY c1, c2;
    

7.2.13.2. Tight index scan

A tight index scan may be either a full index scan or a range index scan, depending on the query conditions.

When the conditions for a loose index scan are not met, it is still possible to avoid creation of temporary tables for queries. If there are range conditions in the clause, this method reads only the keys that satisfy these conditions. Otherwise, it performs an index scan. Because this method reads all keys in each range defined by the clause, or scans the whole index if there are no range conditions, we term it a tight index scan. Notice that with a tight index scan, the grouping operation is performed only after all keys that satisfy the range conditions have been found.

For this method to work, it is sufficient that there is a constant equality condition for all columns in a query referring to parts of the key coming before or in between parts of the key. The constants from the equality conditions fill in any “gaps” in the search keys so that it is possible to form complete prefixes of the index. These index prefixes then can be used for index lookups. If we require sorting of the result, and it is possible to form search keys that are prefixes of the index, MySQL also avoids extra sorting operations because searching with prefixes in an ordered index already retrieves all the keys in order.

The following queries do not work with the loose index scan access method described earlier, but still work with the tight index scan access method (assuming that there is an index on table ).

  • There is a gap in the , but it is covered by the condition :

    SELECT c1, c2, c3 FROM t1 WHERE c2 = 'a' GROUP BY c1, c3;
    
  • The does not begin with the first part of the key, but there is a condition that provides a constant for that part:

    SELECT c1, c2, c3 FROM t1 WHERE c1 = 'a' GROUP BY c2, c3;
    

7.2.14. LIMIT Optimization

In some cases, MySQL handles a query differently when you are using and not using :

  • If you are selecting only a few rows with , MySQL uses indexes in some cases when normally it would prefer to do a full table scan.

  • If you use with , MySQL ends the sorting as soon as it has found the first rows of the sorted result, rather than sorting the entire result. If ordering is done by using an index, this is very fast. If a filesort must be done, all rows that match the query without the clause must be selected, and most or all of them must be sorted, before it can be ascertained that the first rows have been found. In either case, after the initial rows have been found, there is no need to sort any remainder of the result set, and MySQL does not do so.

  • When combining with , MySQL stops as soon as it finds unique rows.

  • In some cases, a can be resolved by reading the key in order (or doing a sort on the key) and then calculating summaries until the key value changes. In this case, does not calculate any unnecessary values.

  • As soon as MySQL has sent the required number of rows to the client, it aborts the query unless you are using .

  • quickly returns an empty set. This can be useful for checking the validity of a query. When using one of the MySQL APIs, it can also be employed for obtaining the types of the result columns. (This trick does not work in the MySQL Monitor (the mysql program), which merely displays in such cases; you should instead use or for this purpose.)

  • When the server uses temporary tables to resolve the query, it uses the clause to calculate how much space is required.

7.2.15. How to Avoid Table Scans

The output from shows in the column when MySQL uses a table scan to resolve a query. This usually happens under the following conditions:

  • The table is so small that it is faster to perform a table scan than to bother with a key lookup. This is common for tables with fewer than 10 rows and a short row length.

  • There are no usable restrictions in the or clause for indexed columns.

  • You are comparing indexed columns with constant values and MySQL has calculated (based on the index tree) that the constants cover too large a part of the table and that a table scan would be faster. See Section 7.2.4, “ Clause Optimization”.

  • You are using a key with low cardinality (many rows match the key value) through another column. In this case, MySQL assumes that by using the key it probably will do many key lookups and that a table scan would be faster.

For small tables, a table scan often is appropriate and the performance impact is negligible. For large tables, try the following techniques to avoid having the optimizer incorrectly choose a table scan:

7.2.16. Speed of INSERT Statements

The time required for inserting a row is determined by the following factors, where the numbers indicate approximate proportions:

  • Connecting: (3)

  • Sending query to server: (2)

  • Parsing query: (2)

  • Inserting row: (1 × size of row)

  • Inserting indexes: (1 × number of indexes)

  • Closing: (1)

This does not take into consideration the initial overhead to open tables, which is done once for each concurrently running query.

The size of the table slows down the insertion of indexes by log , assuming B-tree indexes.

You can use the following methods to speed up inserts:

  • If you are inserting many rows from the same client at the same time, use statements with multiple lists to insert several rows at a time. This is considerably faster (many times faster in some cases) than using separate single-row statements. If you are adding data to a non-empty table, you can tune the variable to make data insertion even faster. See Section 5.2.2, “Server System Variables”.

  • If you are inserting a lot of rows from different clients, you can get higher speed by using the statement. See Section 13.2.4.2, “ Syntax”.

  • For a table, you can use concurrent inserts to add rows at the same time that statements are running if there are no deleted rows in middle of the table. See Section 7.3.3, “Concurrent Inserts”.

  • When loading a table from a text file, use . This is usually 20 times faster than using statements. See Section 13.2.5, “ Syntax”.

  • With some extra work, it is possible to make run even faster for a table when the table has many indexes. Use the following procedure:

    1. Optionally create the table with .

    2. Execute a statement or a mysqladmin flush-tables command.

    3. Use myisamchk --keys-used=0 -rq . This removes all use of indexes for the table.

    4. Insert data into the table with . This does not update any indexes and therefore is very fast.

    5. If you intend only to read from the table in the future, use myisampack to compress it. See Section 14.1.3.3, “Compressed Table Characteristics”.

    6. Re-create the indexes with myisamchk -rq . This creates the index tree in memory before writing it to disk, which is much faster that updating the index during because it avoids lots of disk seeks. The resulting index tree is also perfectly balanced.

    7. Execute a statement or a mysqladmin flush-tables command.

    Note that performs the preceding optimization automatically if the table into which you insert data is empty. The main difference is that you can let myisamchk allocate much more temporary memory for the index creation than you might want the server to allocate for index re-creation when it executes the statement.

    You can also disable or enable the indexes for a table by using the following statements rather than myisamchk. If you use these statements, you can skip the operations:

    ALTER TABLE  DISABLE KEYS;
    ALTER TABLE  ENABLE KEYS;
    
  • To speed up operations that are performed with multiple statements for non-transactional tables, lock your tables:

    LOCK TABLES a WRITE;
    INSERT INTO a VALUES (1,23),(2,34),(4,33);
    INSERT INTO a VALUES (8,26),(6,29);
    ...
    UNLOCK TABLES;
    

    This benefits performance because the index buffer is flushed to disk only once, after all statements have completed. Normally, there would be as many index buffer flushes as there are statements. Explicit locking statements are not needed if you can insert all rows with a single .

    To obtain faster insertions, for transactional tables, you should use and instead of .

    Locking also lowers the total time for multiple-connection tests, although the maximum wait time for individual connections might go up because they wait for locks. For example:

    1. Connection 1 does 1000 inserts

    2. Connections 2, 3, and 4 do 1 insert

    3. Connection 5 does 1000 inserts

    If you do not use locking, connections 2, 3, and 4 finish before 1 and 5. If you use locking, connections 2, 3, and 4 probably do not finish before 1 or 5, but the total time should be about 40% faster.

    , , and operations are very fast in MySQL, but you can obtain better overall performance by adding locks around everything that does more than about five inserts or updates in a row. If you do very many inserts in a row, you could do a followed by an once in a while (each 1,000 rows or so) to allow other threads access to the table. This would still result in a nice performance gain.

    is still much slower for loading data than , even when using the strategies just outlined.

  • To increase performance for tables, for both and , enlarge the key cache by increasing the system variable. See Section 7.5.2, “Tuning Server Parameters”.

7.2.17. Speed of UPDATE Statements

An update statement is optimized like a query with the additional overhead of a write. The speed of the write depends on the amount of data being updated and the number of indexes that are updated. Indexes that are not changed do not get updated.

Another way to get fast updates is to delay updates and then do many updates in a row later. Performing multiple updates together is much quicker than doing one at a time if you lock the table.

For a table that uses dynamic row format, updating a row to a longer total length may split the row. If you do this often, it is very important to use occasionally. See Section 13.5.2.5, “ Syntax”.

7.2.18. Speed of DELETE Statements

The time required to delete individual rows is exactly proportional to the number of indexes. To delete rows more quickly, you can increase the size of the key cache by increasing the system variable. See Section 7.5.2, “Tuning Server Parameters”.

To delete all rows from a table, if faster than than . See Section 13.2.9, “ Syntax”.

7.2.19. Other Optimization Tips

This section lists a number of miscellaneous tips for improving query processing speed:

  • Use persistent connections to the database to avoid connection overhead. If you cannot use persistent connections and you are initiating many new connections to the database, you may want to change the value of the variable. See Section 7.5.2, “Tuning Server Parameters”.

  • Always check whether all your queries really use the indexes that you have created in the tables. In MySQL, you can do this with the statement. See Section 7.2.1, “Optimizing Queries with .

  • Try to avoid complex queries on tables that are updated frequently, to avoid problems with table locking that occur due to contention between readers and writers.

  • With tables that have no deleted rows in the middle, you can insert rows at the end at the same time that another query is reading from the table. If it is important to be able to do this, you should consider using the table in ways that avoid deleting rows. Another possibility is to run to defragment the table after you have deleted a lot of rows from it. See Section 14.1, “The Storage Engine”.

  • To fix any compression issues that may have occurred with tables, you can use . See Section 14.8, “The Storage Engine”.

  • Use , , ... if you usually retrieve rows in , , ... order. By using this option after extensive changes to the table, you may be able to get higher performance.

  • In some cases, it may make sense to introduce a column that is “hashed” based on information from other columns. If this column is short and reasonably unique, it may be much faster than a “wide” index on many columns. In MySQL, it is very easy to use this extra column:

    SELECT * FROM 
      WHERE =MD5(CONCAT(,))
      AND ='' AND ='';
    
  • For tables that change frequently, you should try to avoid all variable-length columns (, , and ). The table uses dynamic row format if it includes even a single variable-length column. See Chapter 14, Storage Engines and Table Types.

  • It is normally not useful to split a table into different tables just because the rows become large. In accessing a row, the biggest performance hit is the disk seek needed to find the first byte of the row. After finding the data, most modern disks can read the entire row fast enough for most applications. The only cases where splitting up a table makes an appreciable difference is if it is a table using dynamic row format that you can change to a fixed row size, or if you very often need to scan the table but do not need most of the columns. See Chapter 14, Storage Engines and Table Types.

  • If you often need to calculate results such as counts based on information from a lot of rows, it may be preferable to introduce a new table and update the counter in real time. An update of the following form is very fast:

    UPDATE  SET =+1 WHERE =;
    

    This is very important when you use MySQL storage engines such as that has only table-level locking (multiple readers with single writers). This also gives better performance with most database systems, because the row locking manager in this case has less to do.

  • If you need to collect statistics from large log tables, use summary tables instead of scanning the entire log table. Maintaining the summaries should be much faster than trying to calculate statistics “live.” Regenerating new summary tables from the logs when things change (depending on business decisions) is faster than changing the running application.

  • If possible, you should classify reports as “live” or as “statistical,” where data needed for statistical reports is created only from summary tables that are generated periodically from the live data.

  • Take advantage of the fact that columns have default values. Insert values explicitly only when the value to be inserted differs from the default. This reduces the parsing that MySQL must do and improves the insert speed.

  • In some cases, it is convenient to pack and store data into a column. In this case, you must provide code in your application to pack and unpack information, but this may save a lot of accesses at some stage. This is practical when you have data that does not conform well to a rows-and-columns table structure.

  • Normally, you should try to keep all data non-redundant (observing what is referred to in database theory as third normal form). However, there may be situations in which it can be advantageous to duplicate information or create summary tables to gain more speed.

  • Stored routines or UDFs (user-defined functions) may be a good way to gain performance for some tasks. See Chapter 17, Stored Procedures and Functions, and Section 24.2, “Adding New Functions to MySQL”, for more information.

  • You can always gain something by caching queries or answers in your application and then performing many inserts or updates together. If your database system supports table locks (as do MySQL and Oracle), this should help to ensure that the index cache is only flushed once after all updates. You can also take advantage of MySQL's query cache to achieve similar results; see Section 5.14, “The MySQL Query Cache”.

  • Use when you do not need to know when your data is written. This reduces the overall insertion impact because many rows can be written with a single disk write.

  • Use when you want to give statements higher priority than your inserts.

  • Use to get retrievals that jump the queue. That is, the is executed even if there is another client waiting to do a write.

  • Use multiple-row statements to store many rows with one SQL statement. Many SQL servers support this, including MySQL.

  • Use to load large amounts of data. This is faster than using statements.

  • Use columns to generate unique values.

  • Use once in a while to avoid fragmentation with dynamic-format tables. See Section 14.1.3, “ Table Storage Formats”.

  • Use () tables when possible to get more speed. See Section 14.4, “The () Storage Engine”. tables are useful for non-critical data that is accessed often, such as information about the last displayed banner for users who don't have cookies enabled in their Web browser. User sessions are another alternative available in many Web application environments for handling volatile state data.

  • With Web servers, images and other binary assets should normally be stored as files. That is, store only a reference to the file rather than the file itself in the database. Most Web servers are better at caching files than database contents, so using files is generally faster.

  • Columns with identical information in different tables should be declared to have identical data types so that joins based on the corresponding columns will be faster.

  • Try to keep column names simple. For example, in a table named , use a column name of instead of . To make your names portable to other SQL servers, you should keep them shorter than 18 characters.

  • If you need really high speed, you should take a look at the low-level interfaces for data storage that the different SQL servers support. For example, by accessing the MySQL storage engine directly, you could get a speed increase of two to five times compared to using the SQL interface. To be able to do this, the data must be on the same server as the application, and usually it should only be accessed by one process (because external file locking is really slow). One could eliminate these problems by introducing low-level commands in the MySQL server (this could be one easy way to get more performance if needed). By carefully designing the database interface, it should be quite easy to support this type of optimization.

  • If you are using numerical data, it is faster in many cases to access information from a database (using a live connection) than to access a text file. Information in the database is likely to be stored in a more compact format than in the text file, so accessing it involves fewer disk accesses. You also save code in your application because you need not parse your text files to find line and column boundaries.

  • Replication can provide a performance benefit for some operations. You can distribute client retrievals among replication servers to split up the load. To avoid slowing down the master while making backups, you can make backups using a slave server. See Chapter 6, Replication.

  • Declaring a table with the table option makes index updates faster because they are not flushed to disk until the table is closed. The downside is that if something kills the server while such a table is open, you should ensure that the table is okay by running the server with the option, or by running myisamchk before restarting the server. (However, even in this case, you should not lose anything by using , because the key information can always be generated from the data rows.)