hosting y dominios

Capítulo 7. Optimización de MySQL

Tabla de contenidos

7.1. Panorámica sobre optimización
7.1.1. Limitaciones y soluciones de compromiso en el diseño de MySQL
7.1.2. Diseñar aplicaciones pensando en la portabilidad
7.1.3. Para qué hemos usado MySQL
7.1.4. El paquete de pruebas de rendimiento (benchmarks) de MySQL
7.1.5. Usar pruebas de rendimiento (benchmarks) propios
7.2. Optimizar sentencias SELECT y otras consultas
7.2.1. Sintaxis de EXPLAIN (Obtener información acerca de un SELECT)
7.2.2. Estimar el renidimiento de una consulta
7.2.3. Velocidad de las consultas SELECT
7.2.4. Optimización de las cláusulas WHERE por parte de MySQL
7.2.5. Optimización de rango
7.2.6. Index Merge Optimization
7.2.7. Cómo optimiza MySQL IS NULL
7.2.8. Cómo MySQL optimiza DISTINCT
7.2.9. Cómo optimiza MySQL los LEFT JOIN y RIGHT JOIN
7.2.10. Cómo optimiza MySQL ORDER BY
7.2.11. Cómo optimiza MySQL los GROUP BY
7.2.12. Cómo optimiza MySQL las cláusulas LIMIT
7.2.13. Cómo evitar lecturas completas de tablas
7.2.14. Velocidad de la sentencia INSERT
7.2.15. Velocidad de las sentencias UPDATE
7.2.16. Velocidad de sentencias DELETE
7.2.17. Otros consejos sobre optimización
7.3. Temas relacionados con el bloqueo
7.3.1. Métodos de bloqueo
7.3.2. Cuestiones relacionadas con el bloqueo (locking) de tablas
7.4. Optimizar la estructura de una base de datos
7.4.1. Elecciones de diseño
7.4.2. Haga sus datos lo más pequeños posibles
7.4.3. Índices de columna
7.4.4. Índices de múltiples columnas
7.4.5. Cómo utiliza MySQL los índices
7.4.6. La caché de claves de MyISAM
7.4.7. Cómo cuenta MySQL las tablas abiertas
7.4.8. Cómo abre y cierra tablas MySQL
7.4.9. Desventajas de crear muchas tablas en la misma base de datos
7.5. Optimización del servidor MySQL
7.5.1. Factores de sistema y afinamientos de parámetros de arranque
7.5.2. Afinar parámetros del servidor
7.5.3. Vigilar el rendimiento del optimizador de consultas
7.5.4. Efectos de la compilación y del enlace en la velocidad de MySQL
7.5.5. Cómo utiliza MySQL la memoria
7.5.6. Cómo usa MySQL las DNS
7.6. Cuestiones relacionadas con el disco
7.6.1. Utilizar enlaces simbólicos

La optimización es una tarea compleja, porque requiere un conocimiento de todo el sistema a optimizar. Se podría optimizar sólo algunos aspectos teniendo poco conocimiento del sistema o aplicación, pero cuanto más óptimo se quiera el sistema, más se tiene que conocer acerca del mismo.

Este capítulo intenta explicar y da algunos ejemplos de las diferentes maneras de optimizar MySQL. Sin embargo se debe recordar que siempre existen vías de hacer todavía más rápido el sistema, aunque pudieran requerir un notable incremento de esfuerzos.

7.1. Panorámica sobre optimización

El factor más importante para hacer un sistema rápido es su diseño básico. Ademas, es necesario conocer los procesos que cumple el sistema y cuáles son sus cuellos de botella. En la mayoría de casos los cuellos de botella nacen de los siguientes factores:

  • Búsqueda en Disco. El disco necesita cierto tiempo para encontrar un paquete de datos. Con discos modernos, el tiempo medio para esto es usualmente menor a 10ms, así que en teoría se pueden hacer 100 búsquedas por segundo. Este tiempo mejora lentamente con los discos nuevos y es muy difícil optimizarlo para una sola tabla. La manera de optimizar el tiempo de búsqueda es distribuir los datos dentro de más de un disco.

  • Lectura y escritura en disco. Cuando el disco se encuentra en la posición correcta, necesitamos leer los datos. Los discos modernos transfieren al menos 10-20MB/s. Esto es mucho más fácil de optimizar que las búsquedas, puesto que podemos leer en paralelo desde múltiples discos.

  • Ciclos de CPU. Cuando tenemos datos en la memoria principal, necesitamos procesarlos para obtener algún resultado. Tener tablas pequeñas en comparación con la cantidad de memoria es el factor mas común de limitación. Pero con tablas pequeñas, la rapidez no es usualmente el problema.

  • Ancho de banda de Memoria. Cuando el CPU necesita más datos de los que puede almacenar en la cache de la CPU, el ancho principal de la memoria se convierte en un cuello de botella. Es poco común en la mayoría de casos, pero debe tenerse en cuenta.

7.1.1. Limitaciones y soluciones de compromiso en el diseño de MySQL

Al utilizar el motor de almacenamiento MyISAM, MySQL usa un bloqueo (lock) extremadamente rápido de tablas, que permite múltiples lecturas o una sola escritura. El mayor problema con este motor de almacenamiento ocurre cuando se tiene un flujo constante de actualizaciones y selecciones lentas de una sola tabla. Si éste es el problema para algunas tablas, puede usar otro motor de almacenamiento para ellas. Ver Capítulo 14, Motores de almacenamiento de MySQL y tipos de tablas.

MySQL puede trabajar con tablas transaccionales y no transaccionales. Para hacer el trabajo más facil con tablas no transaccionales (donde no se puede deshacer una transacción si algo va mal), MySQL tiene las siguientes reglas. Obsérvese que estas reglas sólo se aplican cuando no se está corriendo en modo SQL estricto o si se usa el especificador IGNORE para un INSERT o un UPDATE.

  • Todas las columnas tienen valores por defecto. Obsérvese que cuando se ejecuta en modo SQL estricto (incluyendo modo SQL TRADITIONAL), se debe especificar cualquier valor para una columna NOT NULL.

  • Si se inserta un valor inapropiado o fuera de rango dentro de una columna, MySQL atribuye a la columna el “ mejor valor posible ” en vez de reportar un error. Para valores numéricos, éste es el 0, el valor más pequeño posible o el valor más grande posible. Para cadenas de texto, puede ser una cadena vacía o el trozo de la cadena más grande que quepa en la columna. Este comportamiento no se aplica cuando se ejecuta en modo SQL estricto TRADITIONAL.

  • Todas las expresiones calculadas retornan un valor que puede ser usado en vez de señalar una condición de error. Por ejemplo, 1/0 devuelve NULL. (Este comportamiento puede ser cambiado usando el modo SQL ERROR_FOR_DIVISION_BY_ZERO).

Si se usa una tabla no transaccional, no debería usar MySQL para comprobar el contenido de la columna. En general, la manera más segura (y generalmente más rápida) es usar la aplicacion para asegurarse que se están pasando sólo valores legales a la base de datos.

Para más informacion acerca de esto, ver Sección 1.7.6, “Cómo trata MySQL las restricciones (Constraints)” y Sección 13.2.4, “Sintaxis de INSERT o Sección 5.3.2, “El modo SQL del servidor”.

7.1.2. Diseñar aplicaciones pensando en la portabilidad

Debido a que todos los servidores SQL implementan diferentes partes del estándar SQL, toma trabajo escribir aplicaciones SQL portables. Es muy fácil obtener portabilidad para selects muy simples y para inserts, pero es más difícil cuantas más funcionalidades se requieran. Obtener una aplicación que sea rápida en varios sistemas de bases de datos, es una tarea muy difícil.

Para hacer aplicaciones complejas portables, necesita determinar para cuáles servidores SQL debe trabajar, después determinar qué características soportan esos servidores.

Todos los sistemas de bases de datos tienen algunos puntos débiles. Esto es, tienen diferentes concesiones de diseño que conducen a comportamientos diferentes.

Puede usar el programa de MySQL crash-me para encontrar funciones, tipos y límites que puede usar con una selección de servidores de bases de datos. crash-me no comprueba cada posible característica, pero es razonablemente completo, puesto que hace cerca de 450 pruebas.

Un ejemplo de un tipo de información de la que el programa crash-me puede proveer es que no debería usar nombres de columnas que sean mayores de 18 caracteres si quiere que la aplicación funcione en Informix o DB2.

El programa crash-me y MySQL benchmarks son independientes de la base de datos. Mirando por encima cómo están escritos, puede hacerse una idea de qué debe hacer que sus propias aplicaciones sean independientes de bases de datos. Los programas se encuentran en el directorio sql-bench dentro del código fuente de la distribución de MySQL. Estan escritos en Perl y usan la interfaz para bases de datos DBI. Usar DBI ya soluciona una parte de los problemas de portabilidad puesto que provee de métodos de acceso independientes a las bases de datos.

Ver http://dev.mysql.com/tech-resources/benchmarks/ para los resultados de las mediciones.

Esforzarse para ser independiente del motor de bases de datos, implica prestar atención a los cuellos de botella de cada servidor SQL. Por ejemplo, MySQL es muy rápido obteniendo y actualizando registros para tablas MyISAM, pero tiene un problema mezclando lecturas y escrituras lentas sobre la misma tabla. Por otra parte, Oracle tiene un enorme problema cuando intenta acceder a registros que se han actualizado recientemente (hasta que se escriben en el disco). Las bases de datos transaccionales en general no son muy buenas generando resúmenes de tablas desde las tablas de registro (log), puesto que en este caso el bloqueo (lock) de registros es casi inútil.

Para hacer una aplicación realmente independiente de la base de datos, se necesita definir una interfaz fácilmente extendible a través de la cual se manipularán los datos. Puesto que C++ está disponible en la mayoría de los sistemas, tiene sentido usar una interfaz basada en clases de C++ hacia la base de datos.

Si usa alguna característica que es específica de algún sistema de base de datos (por ejemplo la sentencia REPLACE, que es específica en MySQL), debería implementar la misma característica para otros servidores SQL codificando un método alternativo. Aunque la alternativa sea más lenta, permite que la misma tarea se haga en otros servidores.

Con MySQL, puede usar la sintaxis /*! */ para agregar algunas palabras claves de MySQL a una consulta. El código dentro de /**/ es tratado como un comentario (e ignorado) por la mayoría de los otros servidores SQL.

Si el alto rendimiento es más importante que la exactitud, como en algunas aplicaciones Web, es posible crear una capa de la aplicación que almacene en una cache todos los resultados para obtener un rendimiento mejor. Dejando que los resultados viejos expiren en determinado tiempo, puede mantener la cache razonablemente actualizado. Éste es un método para soportar picos de carga, al que se añade la posibilidad de implementar un incremento dinámico de la cache y un aumento del tiempo de expiración, hasta que las cosas regresen a la normalidad.

En este caso, la información de creación de la tabla debe contener información del tamaño inicial de la cache y de la frecuencia de refresco de la tabla.

Una alternativa para implementar una aplicación en cache es usar la cache para consultas de MySQL. Habilitando la cache para consultas, el servidor toma los detalles de las consultas determinando qué resultados pueden ser reutilizados. Esto simplifica la aplicación. Ver Sección 5.12, “La caché de consultas de MySQL”.

7.1.3. Para qué hemos usado MySQL

Esta sección describe un uso inicial de MySQL.

Durante el inicio del desarrollo de MySQL, las características de MySQL fueron pensadas para ajustarse a nuestro cliente más grande, que hacía data-warehouse para un par de los mayoristas más grandes de Suecia.

Desde todas las tiendas obteníamos resúmenes semanales de todas las transacciones con tarjetas de bonos, y se esperaba de nosotros información útil para que los dueños de las tiendas entendieran cómo sus campañas publicitarias afectaban a sus propios clientes.

El volumen de datos era enorme (cerca de siete millones de transacciones resumidas por mes), y teníamos datos de 4-10 años que debíamos presentar a los usuarios. Teníamos peticiones semanales de nuestros clientes, quienes querían acceso instantáneo a los nuevos reportes de esta información.

Solucionamos este problema almacenando toda la información por mes en unas “tablas de transacciones” comprimidas. Teníamos una serie de sencillas macros que generaban resúmenes de tablas agrupados por diferentes criterios (grupo de productos, id del cliente, tienda, etc) a partir de las tablas en las que fueron almacenadas las transacciones. Los reportes eran páginas Web que eran generadas dinámicamente por un pequeño script escrito en Perl. Este script analizaba la página Web, ejecutaba una sentencia SQL y escribía los resultados. Debimos usar PHP o mod_perl en vez de eso, pero no estaban disponibles en aquel entonces.

Para datos gráficos, escribimos una sencilla herramienta en C que podía procesar los resultados de una consulta SQL y generar una imagen GIF basada en los resultados. Esta herramienta también era dinámicamente invocada desde el script en Perl que analizaba las páginas Web.

En la mayoría de casos, se podía crear un nuevo reporte simplemente copiando un script existente y modificando la consulta SQL que utilizaba. En algunos casos, necesitábamos agregar más columnas a una tabla de resumen existente o generar una nueva. Esto también fue sencillo puesto que guardábamos todas las tablas con las transacciones en disco. (El tamaño era de alrededor de 50GB de tablas de transacciones y 200GB de otros datos del cliente.)

También permitimos a nuestros clientes acceder a las tablas de resumen directamente con ODBC, para que los usuarios avanzados pudieran experimentar con los datos por sí mismos.

Este sistema trabajó bien y no tuvimos problemas elaborando los datos en un modesto servidor Sun Ultra SPARCstation (2x200Mhx). Finalmente el sistema fue migrado a Linux.

7.1.4. El paquete de pruebas de rendimiento (benchmarks) de MySQL

Esta sección debería contener una descripción técnica del paquete de pruebas de rendimiento de MySQL (así como del crash-me), pero esa descripción aún no ha sido escrita. Sin embargo, puede hacerse una buena idea de cómo hacer pruebas de rendimiento viendo el código y los resultados dentro del directorio sql-bench en el código fuente de la distribución de MySQL.

La finalidad de este paquete de pruebas de rendimiento es visualizar qué operaciones se realizan bien y cuáles lo hacen pobremente en cada implementación de SQL.

Estas pruebas de rendimiento no son multi hilo, así que miden el tiempo mínimo para las operaciones realizadas. Se planea agregar en un futuro pruebas multi hilo al paquete.

Para usar el paquete, deben satisfacerse los siguientes requisitos:

Una vez obtenido el código fuente de la distribución de MySQL, el paquete de pruebas de rendimiento se encuentra en el directorio sql-bench. Para ejecutar las pruebas de rendimiento, compílese MySQL, váyase al directorio sql-bench y ejecútese el script run-all-tests:

shell> cd sql-bench
shell> perl run-all-tests --server=nombre_servidor

nombre_servidor debe ser uno de los servidores soportados. Para obtener la lista completa de opciones y servidores soportados, invóquese el comando:

shell> perl run-all-tests --help

El script crash-me también está situado dentro del directorio sql-bench. crash-me intenta determinar qué características soporta una base de datos y cuáles son sus capacidades y limitaciones. Esto lo consigue ejecutando consultas. Determina por ejemplo:

  • Cuáles tipos de columnas se soportan

  • Cuántos índicies se soportan

  • Qué funciones se soportan

  • Qué tamaño puede alcanzar una consulta

  • Que tamaño puede alcanzar una columna VARCHAR

Para más información acerca de resultados de pruebas de rendimiento, visítese http://dev.mysql.com/tech-resources/benchmarks/.

7.1.5. Usar pruebas de rendimiento (benchmarks) propios

Decididamente debería realizar pruebas de rendimiento sobre su aplicación y su base de datos para determinar dónde se encuentran los cuellos de botella. Eliminando un cuello de botella (o reemplazándolo con un módulo “tonto”) puede fácilmente identificar el siguiente cuello de botella. Aunque el rendimiento global de su aplicación sea aceptable, debería al menos hacer un plan para cada cuello de botella, y decidir cómo eliminarlo si algún día realmente necesita un rendimiento extra.

Para ejemplos de programas de pruebas de rendimiento portables, mire el paquete de pruebas de rendimiento MySQL. Ver Sección 7.1.4, “El paquete de pruebas de rendimiento (benchmarks) de MySQL”. Puede tomar cualquier programa de este paquete y modificarlo en base a sus necesidades. Así puede probar diferentes soluciones para su problema y probar cuál realmente es más rápida para usted.

Otro paquete de pruebas de rendimiento es Open Source Database Benchmark, disponible en http://osdb.sourceforge.net/.

Es muy común que un problema ocurra sólo cuando el sistema está bajo mucha carga. Muchos de nuestros clientes nos contactan cuando tienen un sistema (probado) en producción y encuentran problemas de carga. En la mayoría de casos, los problemas de rendimiento se deben a cuestiones relacionadas con el diseño básico de la base de datos (por ejemplo, lecturas completas de las tablas no son buenas bajo alta carga) o problemas con el sistema operativo o las bibliotecas. En la mayoría de casos, esos problemas se solucionarían mucho más fácilmente si los sistemas no estuvieran en producción.

Para evitar este tipo de problemas, es conveniente hacer pruebas de rendimiento a las aplicaciones enteras bajo la mayor carga de trabajo posible. Para ello, puede utilizarse Super Smack, disponible en http://jeremy.zawodny.com/mysql/super-smack/. Como su nombre indica, puede poner de rodillas a un sistema, así que asegúrese de usarlo sólo en sistemas de desarrollo.

7.2. Optimizar sentencias SELECT y otras consultas

Ante todo, un factor afecta a todas las sentencias: cuanto más compleja es la configuración de los permisos, mayor es la carga.

Usar permisos simples cuando se ejecuta una sentencia GRANT permite a MySQL reducir la carga en la verificación de permisos cuando los clientes ejecutan sentencias. Por ejemplo, si no se concede (grant) ningún privilegio a nivel de tabla o de columna, el servidor no necesita verificar nunca el contenido de las tablas tables_priv y columns_priv. Similarmente, si no se establece límites de recursos sobre ninguna cuenta, el servidor no tiene que realizar conteos de recursos. Cuando se tiene un alto volumen de consultas, puede valer la pena utilizar una estructura de permisos simplificada para reducir la carga de verificación de los mismos.

Si el problema es con una expresión o función específica de MySQL, se puede utilizar la función BENCHMARK() en el cliente mysql para realizar una prueba de velocidad. Su sintaxis es BENCHMARK(número_iteraciones,expresion). El valor devuelto siempre es cero, pero mysql muestra cuánto tardó en ejecutarse la sentencia. Por ejemplo:

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

Este resultado se obtuvo en un sistema Pentium II 400MHz. Muestra que MySQL puede ejecutar 1,000,000 de expresiones simples de suma en 0.32 segundo sobre ese sistema.

Todas las funciones de MySQL deberían estar altamente optimizadas, pero pueden existir algunas excepciones. BENCHMARK() es una excelente herramienta para determinar si alguna función es un problema en una consulta.

7.2.1. Sintaxis de EXPLAIN (Obtener información acerca de un SELECT)

EXPLAIN nombre_de_tabla

O:

EXPLAIN SELECT opciones_de_select

La sentencia EXPLAIN puede utilizarse como un sinónimo de DESCRIBE o también como una manera para obtener información acerca de cómo MySQL ejecuta una sentencia SELECT:

  • EXPLAIN nombre_de_tabla es sinónimo de DESCRIBE nombre_de_tabla o SHOW COLUMNS FROM nombre_de_tabla.

  • Cuando se precede una sentencia SELECT con la palabra EXPLAIN, MySQL muestra información del optimizador sobre el plan de ejecución de la sentencia. Es decir, MySQL explica cómo procesaría el SELECT, proporcionando también información acerca de cómo y en qué orden están unidas (join) las tablas.

Esta sección trata sobre el segundo uso de EXPLAIN.

EXPLAIN es una ayuda para decidir qué índices agregar a las tablas, con el fin de que las sentencias SELECT encuentren registros más rápidamente. EXPLAIN puede utilizarse también para verificar si el optimizador une (join) las tablas en el orden óptimo. Si no fuera así, se puede forzar al optimizador a unir las tablas en el orden en el que se especifican en la sentencia SELECT empezando la sentencia con SELECT STRAIGHT_JOIN en vez de simplemente SELECT.

Si un índice no está siendo utilizado por las sentencias SELECT cuando debiera, debe ejecutarse el comando ANALYZE TABLE, a fin de actualizar las estadísticas de la tabla como la cardinalidad de sus claves, que pueden afectar a la decisiones que el optimizador toma. Ver Sección 13.5.2.1, “Sintaxis de ANALYZE TABLE.

EXPLAIN muestra una línea de información para cada tabla utilizada en la sentencia SELECT. Las tablas se muestran en el mismo orden en el que MySQL las leería al procesar la consulta. MySQL resuelve todas las uniones (joins) usando un método de single-sweep multi-join. Esto significa que MySQL lee un registro de la primera tabla; encuentra su correspondiente en la segunda tabla, en la tercera, y así sucesivamente. Cuando todas las tablas han sido procesadas, MySQL muestra las columnas seleccionadas y recorre a la inversa la lista de tablas hasta que encuentra aquélla para la que la sentencia devuelve más registros. Se lee entonces el siguiente registro de esta tabla y el proceso continúa con la siguiente tabla.

EXPLAIN retorna una tabla; cada línea de esta tabla muestra información acerca de una tabla, y tiene las siguientes columnas:

  • id

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

  • select_type

    The type of SELECT, which can be any of the following:

    • SIMPLE

      Simple SELECT (not using UNION or subqueries)

    • PRIMARY

      Outermost SELECT

    • UNION

      Second or later SELECT statement in a UNION

    • DEPENDENT UNION

      Second or later SELECT statement in a UNION, dependent on outer query

    • UNION RESULT

      Result of a UNION.

    • SUBQUERY

      First SELECT in subquery

    • DEPENDENT SUBQUERY

      First SELECT in subquery, dependent on outer query

    • DERIVED

      Derived table SELECT (subquery in FROM clause)

  • table

    The table to which the row of output refers.

  • type

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

    • system

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

    • const

      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. const tables are very fast because they are read only once.

      const is used when you compare all parts of a PRIMARY KEY or UNIQUE index with constant values. In the following queries, tbl_name can be used as a const table:

      SELECT * FROM tbl_name WHERE primary_key=1;
      
      SELECT * FROM tbl_name
      WHERE primary_key_part1=1 AND primary_key_part2=2;
      

    • eq_ref

      One row is read from this table for each combination of rows from the previous tables. Other than the const 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 PRIMARY KEY or UNIQUE index.

      eq_ref 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 eq_ref join to process ref_table:

      SELECT * FROM ref_table,other_table
      WHERE ref_table.key_column=other_table.column;
      
      SELECT * FROM ref_table,other_table
      WHERE ref_table.key_column_part1=other_table.column
      AND ref_table.key_column_part2=1;
      

    • ref

      All rows with matching index values are read from this table for each combination of rows from the previous tables. ref is used if the join uses only a leftmost prefix of the key or if the key is not a PRIMARY KEY or UNIQUE 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.

      ref can be used for indexed columns that are compared using the = or <=> operator.

      In the following examples, MySQL can use a ref join to process ref_table:

      SELECT * FROM ref_table WHERE key_column=expr;
      
      SELECT * FROM ref_table,other_table
      WHERE ref_table.key_column=other_table.column;
      
      SELECT * FROM ref_table,other_table
      WHERE ref_table.key_column_part1=other_table.column
      AND ref_table.key_column_part2=1;
      

    • ref_or_null

      This join type is like ref, but with the addition that MySQL does an extra search for rows that contain NULL values. This join type optimization is used most often in resolving subqueries.

      In the following examples, MySQL can use a ref_or_null join to process ref_table:

      SELECT * FROM ref_table
      WHERE key_column=expr OR key_column IS NULL;
      

      See Sección 7.2.7, “Cómo optimiza MySQL IS NULL.

    • index_merge

      This join type indicates that the Index Merge optimization is used. In this case, the key column contains a list of indexes used, and key_len contains a list of the longest key parts for the indexes used. For more information, see Sección 7.2.6, “Index Merge Optimization”.

    • unique_subquery

      This type replaces ref for some IN subqueries of the following form:

      value IN (SELECT primary_key FROM single_table WHERE some_expr)
      

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

    • index_subquery

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

      value IN (SELECT key_column FROM single_table WHERE some_expr)
      

    • range

      Only rows that are in a given range are retrieved, using an index to select the rows. The key column indicates which index is used. The key_len contains the longest key part that was used. The ref column is NULL for this type.

      range can be used for when a key column is compared to a constant using any of the =, <>, >, >=, <, <=, IS NULL, <=>, BETWEEN, or IN operators:

      SELECT * FROM tbl_name
      WHERE key_column = 10;
      
      SELECT * FROM tbl_name
      WHERE key_column BETWEEN 10 and 20;
      
      SELECT * FROM tbl_name
      WHERE key_column IN (10,20,30);
      
      SELECT * FROM tbl_name
      WHERE key_part1= 10 AND key_part2 IN (10,20,30);
      

    • index

      This join type is the same as ALL, except that only the index tree is scanned. This usually is faster than ALL, 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.

    • ALL

      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 const, and usually very bad in all other cases. Normally, you can avoid ALL by adding indexes that allow row retrieval from the table based on constant values or column values from earlier tables.

  • possible_keys

    The possible_keys column indicates which indexes MySQL could 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 EXPLAIN. That means that some of the keys in possible_keys might not be usable in practice with the generated table order.

    If this column is NULL, there are no relevant indexes. In this case, you may be able to improve the performance of your query by examining the WHERE clause to see 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 EXPLAIN again. See Sección 13.1.2, “Sintaxis de ALTER TABLE.

    To see what indexes a table has, use SHOW INDEX FROM tbl_name.

  • key

    The key column indicates the key (index) that MySQL actually decided to use. The key is NULL if no index was chosen. To force MySQL to use or ignore an index listed in the possible_keys column, use FORCE INDEX, USE INDEX, or IGNORE INDEX in your query. See Sección 13.2.7, “Sintaxis de SELECT.

    For MyISAM and BDB tables, running ANALYZE TABLE helps the optimizer choose better indexes. For MyISAM tables, myisamchk --analyze does the same. See Sección 13.5.2.1, “Sintaxis de ANALYZE TABLE and Sección 5.8.3, “Mantenimiento de tablas y recuperación de un fallo catastrófico (crash)”.

  • key_len

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

  • ref

    The ref column shows which columns or constants are used with the key to select rows from the table.

  • rows

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

  • Extra

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

    • Distinct

      MySQL stops searching for more rows for the current row combination after it has found the first matching row.

    • Not exists

      MySQL was able to do a LEFT JOIN 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 LEFT JOIN 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 t2.id is defined as NOT NULL. In this case, MySQL scans t1 and looks up the rows in t2 using the values of t1.id. If MySQL finds a matching row in t2, it knows that t2.id can never be NULL, and does not scan through the rest of the rows in t2 that have the same id value. In other words, for each row in t1, MySQL needs to do only a single lookup in t2, regardless of how many rows actually match in t2.

    • range checked for each record (index map: #)

      MySQL found no good index to use, but found that some of indexes might be used once column values from preceding tables are known. For each row combination in the preceding tables, MySQL checks whether it is possible to use a range or index_merge access method to retrieve rows. The applicability criteria are as described in Sección 7.2.5, “Optimización de rango” and Sección 7.2.6, “Index Merge Optimization”, with the exception that all column values for the preceding table are known and considered to be constants.

      This is not very fast, but is faster than performing a join with no index at all.

    • Using filesort

      MySQL needs to 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 WHERE clause. The keys then are sorted and the rows are retrieved in sorted order. See Sección 7.2.10, “Cómo optimiza MySQL ORDER BY.

    • Using index

      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.

    • Using temporary

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

    • Using where

      A WHERE 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 Extra value is not Using where and the table join type is ALL or index.

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

    • Using sort_union(...), Using union(...), Using intersect(...)

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

    • Using index for group-by

      Similar to the Using index way of accessing a table, Using index for group-by indicates that MySQL found an index that can be used to retrieve all columns of a GROUP BY or DISTINCT 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 Sección 7.2.11, “Cómo optimiza MySQL los GROUP BY.

You can get a good indication of how good a join is by taking the product of the values in the rows column of the EXPLAIN output. This should tell you roughly how many rows MySQL must examine to execute the query. If you restrict queries with the max_join_size system variable, this product also is used to determine which multiple-table SELECT statements to execute. See Sección 7.5.2, “Afinar parámetros del servidor”.

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

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

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:

    TableColumnColumn Type
    ttActualPCCHAR(10)
    ttAssignedPCCHAR(10)
    ttClientIDCHAR(10)
    etEMPLOYIDCHAR(15)
    doCUSTNMBRCHAR(15)
  • The tables have the following indexes:

    TableIndex
    ttActualPC
    ttAssignedPC
    ttClientID
    etEMPLOYID (primary key)
    doCUSTNMBR (primary key)
  • The tt.ActualPC values are not evenly distributed.

Initially, before any optimizations have been performed, the EXPLAIN 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 type is ALL 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, VARCHAR and CHAR are considered the same if they are declared as the same size. Since tt.ActualPC is declared as CHAR(10) and et.EMPLOYID is CHAR(15), there is a length mismatch.

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

mysql> ALTER TABLE tt MODIFY ActualPC VARCHAR(15);

tt.ActualPC and et.EMPLOYID are both VARCHAR(15). Executing the EXPLAIN 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 rows values is less by a factor of 74. This version is executed in a couple of seconds.

A second alteration can be made to eliminate the column length mismatches for the tt.AssignedPC = et_1.EMPLOYID and tt.ClientID = do.CUSTNMBR comparisons:

mysql> ALTER TABLE tt MODIFY AssignedPC VARCHAR(15),
    ->                MODIFY ClientID   VARCHAR(15);

EXPLAIN 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

This is almost as good as it can get.

The remaining problem is that, by default, MySQL assumes that values in the tt.ActualPC column are evenly distributed, and that is not the case for the tt table. Fortunately, it is easy to tell MySQL to analyze the key distribution:

mysql> ANALYZE TABLE tt;

The join is perfect, and EXPLAIN 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 rows column in the output from EXPLAIN is an educated guess from the MySQL join optimizer. You should check whether the numbers are even close to the truth. If not, you may get better performance by using STRAIGHT_JOIN in your SELECT statement and trying to list the tables in a different order in the FROM clause.

7.2.2. Estimar el renidimiento de una consulta

In most cases, you can estimate the 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(row_count) / log(index_block_length / 3 * 2 / (index_length + data_pointer_length)) + 1.

In MySQL, an index block is usually 1024 bytes and the data pointer is usually 4 bytes. For a 500,000-row table with an index length of 3 bytes (medium integer), the formula indicates log(500,000)/log(1024/3*2/(3+4)) + 1 = 4 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 (as above) to find where to place the new index and normally two seeks to update the index and write the row.

Note that the preceding discussion doesn't mean that your application performance slowly degenerates by log N. 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 N). To avoid this, increase the key cache size as the data grows. For MyISAM tables, the key cache size is controlled by the key_buffer_size system variable. See Sección 7.5.2, “Afinar parámetros del servidor”.

7.2.3. Velocidad de las consultas SELECT

In general, when you want to make a slow SELECT ... WHERE 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 EXPLAIN statement to determine which indexes are used for a SELECT. See Sección 7.4.5, “Cómo utiliza MySQL los índices” and Sección 7.2.1, “Sintaxis de EXPLAIN (Obtener información acerca de un SELECT)”.

Some general tips for speeding up queries on MyISAM tables:

  • To help MySQL better optimize queries, use ANALYZE TABLE 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 SHOW INDEX FROM tbl_name and examining the Cardinality 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 (if 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 records in order according to the index. Note that the first time you sort a large table this way, it may take a long time.

7.2.4. Optimización de las cláusulas WHERE por parte de MySQL

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

Note that work on the MySQL optimizer is ongoing, so this section is incomplete. MySQL does many optimizations, not all of which are documented here.

Some of the optimizations performed by MySQL are listed here:

  • 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.

  • COUNT(*) on a single table without a WHERE is retrieved directly from the table information for MyISAM and HEAP tables. This is also done for any NOT NULL expression when used with only one table.

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

  • HAVING is merged with WHERE if you don't use GROUP BY or group functions (COUNT(), MIN(), and so on).

  • For each table in a join, a simpler WHERE is constructed to get a fast WHERE evaluation for the table and also to skip records 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 WHERE clause on a PRIMARY KEY or a UNIQUE index, where all index parts are compared to constant expressions and are defined as NOT NULL.

    All of the following tables are used as constant tables:

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

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

  • If you use SQL_SMALL_RESULT, 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. The optimizer is more complex and bases its estimate on additional factors such as table size, number of rows, and I/O block size, so a fixed percentage no longer determines the choice between using an index or a scan.

  • 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 record is output, those that do not match the HAVING clause are skipped.

Some examples of queries that are very fast:

SELECT COUNT(*) FROM tbl_name;

SELECT MIN(key_part1),MAX(key_part1) FROM tbl_name;

SELECT MAX(key_part2) FROM tbl_name
    WHERE key_part1=constant;

SELECT ... FROM tbl_name
    ORDER BY key_part1,key_part2,... LIMIT 10;

SELECT ... FROM tbl_name
    ORDER BY key_part1 DESC, key_part2 DESC, ... LIMIT 10;

The following queries are resolved using only the index tree, assuming that the indexed columns are numeric:

SELECT key_part1,key_part2 FROM tbl_name WHERE key_part1=val;

SELECT COUNT(*) FROM tbl_name
    WHERE key_part1=val1 AND key_part2=val2;

SELECT key_part2 FROM tbl_name GROUP BY key_part1;

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

SELECT ... FROM tbl_name
    ORDER BY key_part1,key_part2,... ;

SELECT ... FROM tbl_name
    ORDER BY key_part1 DESC, key_part2 DESC, ... ;

7.2.5. Optimización de rango

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

7.2.5.1. Método de acceso a rango para índices simples

For a single-part index, index value intervals can be conveniently represented by corresponding conditions in the WHERE clause, so we'll talk about range conditions rather than “intervals”.

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

  • For both BTREE and HASH indexes, comparison of a key part with a constant value is a range condition when using the =, <=>, IN, IS NULL, or IS NOT NULL operators.

  • For BTREE indexes, comparison of a key part with a constant value is a range condition when using the >, <, >=, <=, BETWEEN, !=, or <> operators, or LIKE 'pattern' (where 'pattern' doesn't start with a wildcard).

  • For all types of indexes, multiple range conditions combined with OR or AND 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 const or system 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 WHERE clause:

SELECT * FROM t1 WHERE key_col > 1 AND key_col < 10;

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

SELECT * FROM t1 WHERE key_col LIKE 'ab%' OR key_col 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 WHERE clause for each of the possible indexes. During the extraction process, conditions that can't be used for constructing the range condition are dropped, conditions that produce overlapping ranges are combined, and conditions that produce empty ranges are removed.

For example, consider the following statement, where key1 is an indexed column and nonkey 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 key1 is as follows:

  1. Start with original WHERE 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 nonkey = 4 and key1 LIKE '%b' because they cannot be used for a range scan. The right way to remove them is to replace them with TRUE, so that we don't miss any matching records when doing the range scan. Having replaced them with TRUE, 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:

    • (key1 LIKE 'abcde%' OR TRUE) is always true

    • (key1 < 'uux' AND key1 > 'z') is always false

    Replacing these conditions with constants, we get:

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

    Removing unnecessary TRUE and FALSE 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 in the example), the condition used for a range scan is less restrictive than the WHERE clause. MySQL performs an additional check to filter out rows that satisfy the range condition but not the full WHERE clause.

The range condition extraction algorithm can handle nested AND/OR constructs of arbitrary depth, and its output doesn't depend on the order in which conditions appear in WHERE clause.

7.2.5.2. 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 records 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 key1(key_part1, key_part2, key_part3), and the following set of key tuples listed in key order:

key_part1  key_part2  key_part3
  NULL       1          'abc'
  NULL       1          'xyz'
  NULL       2          'foo'
   1         1          'abc'
   1         1          'xyz'
   1         2          'abc'
   2         1          'aaa'

The condition key_part1 = 1 defines this interval:

(1, -inf, -inf) <= (key_part1, key_part2, key_part3) < (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 key_part3 = '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 HASH indexes, each interval containing identical values can be used. This means that the interval can be produced only for conditions in the following form:

        key_part1 cmp const1
    AND key_part2 cmp const2
    AND ...
    AND key_partN cmp constN;
    

    Here, const1, const2, ... are constants, cmp is one of the =, <=>, or IS NULL comparison operators, and the conditions cover all index parts. (That is, there are N conditions, one for each part of an N-part index.)

    See Sección 7.2.5.1, “Método de acceso a rango para índices simples” for the definition of what is considered to be a constant.

    For example, the following is a range condition for a three-part HASH index:

    key_part1 = 1 AND key_part2 IS NULL AND key_part3 = 'foo'
    
  • For a BTREE index, an interval might be usable for conditions combined with AND, where each condition compares a key part with a constant value using =, <=>, IS NULL, >, <, >=, <=, !=, <>, BETWEEN, or LIKE 'pattern' (where 'pattern' 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 records that match the condition (or two intervals if <> or != is used). For example, for this condition:

    key_part1 = 'foo' AND key_part2 >= 10 AND key_part3 > 10
    

    The single interval is:

    ('foo', 10, 10)
       < (key_part1, key_part2, key_part3)
          < ('foo', +inf, +inf)
    

    It is possible that the created interval contains more records than the initial condition. For example, the preceding interval includes the value ('foo', 11, 0), which does not satisfy the original condition.

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

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

    The intervals is:

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

    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 key_len column in the EXPLAIN output indicates the maximum length of the key prefix used.

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

    key_part1 >= 1 AND key_part2 < 2
    

    But in fact, the condition is converted to this:

    key_part1 >= 1 AND key_part2 IS NOT NULL
    

Sección 7.2.5.1, “Método de acceso a rango para índices simples” describes how optimizations are performed to combine or eliminate intervals for range conditions on single-part index. Analogous steps are performed for range conditions on multiple-part keys.

7.2.6. Index Merge Optimization

The Index Merge (index_merge) method is used to retrieve rows with several ref, ref_or_null, or range scans and merge the results into one. This method is employed when the table condition is a disjunction of conditions for which ref, ref_or_null, or range could be used with different keys.

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 EXPLAIN output, this method appears as index_merge in the type column. In this case, the key column contains a list of indexes used, and key_len contains a list of the longest key parts for those indexes.

Examples:

SELECT * FROM tbl_name WHERE key_part1 = 10 OR key_part2 = 20;

SELECT * FROM tbl_name
    WHERE (key_part1 = 10 OR key_part2 = 20) AND non_key_part=30;

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

SELECT * FROM t1, t2
    WHERE t1.key1=1
    AND (t2.key1=t1.some_col OR t2.key2=t1.some_col2);

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

  • intersection

  • union

  • sort-union

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:

    1. An Index Merge scan using the (goodkey1 < 10 OR goodkey2 < 20) condition.

    2. A range scan using the badkey < 30 condition.

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

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

    (x AND y) OR z = (x OR z) AND (y OR z)
    (x OR y) AND z = (x AND z) OR (y AND z)
    

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. Index Merge Intersection Access Algorithm

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

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

    key_part1=const1 AND key_part2=const2 ... AND key_partN=constN
    
  • Any range condition over a primary key of an InnoDB or BDB table.

Here are some examples:

SELECT * FROM innodb_table WHERE primary_key < 10 AND key_col1=20;

SELECT * FROM tbl_name
WHERE (key1_part1=1 AND key1_part2=2) AND key2=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 records are not retrieved and (EXPLAIN output contains Using index in Extra field in this case). Here is an example of such 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 records 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 InnoDB or BDB table, it is not used for record retrieval, but is used to filter out records retrieved using other conditions.

7.2.6.2. Algoritmo de acceso a 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 WHERE clause was converted to several range conditions on different keys combined with OR, and each condition is one of the following:

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

    key_part1=const1 AND key_part2=const2 ... AND key_partN=constN
    
  • Any range condition over a primary key of an InnoDB or BDB table.

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

Here are some examples:

SELECT * FROM t1 WHERE key1=1 OR key2=2 OR key3=3;

SELECT * FROM innodb_table WHERE (key1=1 AND key2=2) OR
  (key3='foo' AND key4='bar') AND key5=5;

7.2.6.3. Index Merge Sort-Union Access Algorithm

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

Here are some examples:

SELECT * FROM tbl_name WHERE key_col1 < 10 OR key_col2 < 20;

SELECT * FROM tbl_name
     WHERE (key_col1 > 10 OR key_col2 = 20) AND nonkey_col=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 records and sort them before returning any records.

7.2.7. Cómo optimiza MySQL IS NULL

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

SELECT * FROM tbl_name WHERE key_col IS NULL;

SELECT * FROM tbl_name WHERE key_col <=> NULL;

SELECT * FROM tbl_name
    WHERE key_col=const1 OR key_col=const2 OR key_col IS NULL;

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

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

This optimization can handle one IS NULL for any key part.

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

SELECT * FROM t1 WHERE t1.a=expr 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 ...);

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

Note that the optimization can handle only one IS NULL level. In the following query, MySQL uses key lookups only on the expression (t1.a=t2.a AND t2.a IS NULL) and is not able to use the key part on b:

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. Cómo MySQL optimiza DISTINCT

DISTINCT combined with ORDER BY needs a temporary table in many cases.

Note that because DISTINCT may use GROUP BY, you should be aware of how MySQL works with columns in ORDER BY or HAVING clauses that are not part of the selected columns. See Sección 12.10.3, “GROUP BY con campos escondidos”.

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

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

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

Due to this equivalence, the optimizations applicable to GROUP BY queries can be also applied to queries with a DISTINCT clause. Thus, for more details on the optimization possibilities for DISTINCT queries, see Sección 7.2.11, “Cómo optimiza MySQL los GROUP BY.

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

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

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

7.2.9. Cómo optimiza MySQL los LEFT JOIN y RIGHT JOIN

An A LEFT JOIN B join_condition is implemented in MySQL as follows:

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

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

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