EXPLAIN
Nombre
EXPLAIN -- muestra el plan de ejecución de una sentencia
Sinopsis
EXPLAIN [ ANALYZE ] [ VERBOSE ] sentencia
Descripción
Este comando muestra el plan de ejecución que genera el planeador de PostgreSQL para la sentencia proporcionada. El plan de ejecución muestra como las tablas referenciadas por la sentencia serán recorridas - por un recorrido secuencial plano, por índice, etc. - y si se referencian múltiples tablas, que algorítmos de junta serán usados para reunir las filas requeridas de cada tabla de entrada.
La parte más crítica que muestra es el costo estimado de ejecución, lo cual es la suposición del planeador de cuanto tiempo tomará ejecutar la sentencia (medido en unidades de página de disco leídas). En realidad dos números son mostrados: el tiempo de iniciación antes de que la primer fila pueda ser devuelta, y el tiempo total para devolver todas las filas. Para la mayoría de las consultas el tiempo total es lo que importa, pero en contextos como en una subconsulta EXISTS, el planeador elegirá el tiempo de iniciación menor en vez del tiempo total menor (debido a que el ejecutor se detendrá luego de obtener una fila). También, si limita el número de filas a devolver con una clausula LIMIT, el planeador hace una interpolación apropiada entre el costo final y estima que plan es el realmente más económico.
La opción ANALYZE causa que la sentencia sea ejecutada realmente, no solo planeada. Se devuelven y muestran la duración total medida para cada nodo (en milisegundos) y el número total de filas devuletas realmente. Esto es útil para ver si los estimados del planeador se acercan a la realidad.
Importante: Recuerde que la sentencia es realmente ejecutada cuando se envía la opción ANALYZE. Aunque EXPLAIN desechará cualquier salida que devolvería SELECT, otros efectos colaterales de la sentencia pasarán de manera usual. Si desea usar EXPLAIN ANALYZE sobre una sentencia INSERT, UPDATE, DELETE, CREATE TABLE AS, o EXECUTE sin permitir que el comando afecte los datos, use este enfoque:
BEGIN; EXPLAIN ANALYZE ...; ROLLBACK;
Parámetros
- ANALYZE
- Llevar a cabo el comando y mostrar los tiempos de ejecución reales.
- VERBOSE
- Incluir la lista de columnas de salida para cada nodo en el árbol del plan.
- sentencia
- Cualquier sentencia SELECT, INSERT, UPDATE, DELETE, VALUES, EXECUTE, DECLARE, o CREATE TABLE AS, de cuya cual su plan quiere ser analizado.
Notes
There is only sparse documentation on the optimizer's use of cost information in PostgreSQL. Refer to Section 14.1 for more information.
In order to allow the PostgreSQL query planner to make reasonably informed decisions when optimizing queries, the ANALYZE statement should be run to record statistics about the distribution of data within the table. If you have not done this (or if the statistical distribution of the data in the table has changed significantly since the last time ANALYZE was run), the estimated costs are unlikely to conform to the real properties of the query, and consequently an inferior query plan might be chosen.
Genetic query optimization (GEQO) randomly tests execution plans. Therefore, when the number of join relations exceeds geqo_thresholdcausing genetic query optimization to be used, the execution plan is likely to change each time the statement is executed.
In order to measure the run-time cost of each node in the execution plan, the current implementation of EXPLAIN ANALYZE can add considerable profiling overhead to query execution. As a result, running EXPLAIN ANALYZE on a query can sometimes take significantly longer than executing the query normally. The amount of overhead depends on the nature of the query.
Examples
To show the plan for a simple query on a table with a single integer column and 10000 rows:
EXPLAIN SELECT * FROM foo;
QUERY PLAN
---------------------------------------------------------
Seq Scan on foo (cost=0.00..155.00 rows=10000 width=4)
(1 row)
If there is an index and we use a query with an indexable WHERE condition, EXPLAIN might show a different plan:
EXPLAIN SELECT * FROM foo WHERE i = 4;
QUERY PLAN
--------------------------------------------------------------
Index Scan using fi on foo (cost=0.00..5.98 rows=1 width=4)
Index Cond: (i = 4)
(2 rows)
Here is an example of a query plan for a query using an aggregate function:
EXPLAIN SELECT sum(i) FROM foo WHERE i < 10;
QUERY PLAN
---------------------------------------------------------------------
Aggregate (cost=23.93..23.93 rows=1 width=4)
-> Index Scan using fi on foo (cost=0.00..23.92 rows=6 width=4)
Index Cond: (i < 10)
(3 rows)
Here is an example of using EXPLAIN EXECUTE to display the execution plan for a prepared query:
PREPARE query(int, int) AS SELECT sum(bar) FROM test
WHERE id > $1 AND id < $2
GROUP BY foo;
EXPLAIN ANALYZE EXECUTE query(100, 200);
QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------
HashAggregate (cost=39.53..39.53 rows=1 width=8) (actual time=0.661..0.672 rows=7 loops=1)
-> Index Scan using test_pkey on test (cost=0.00..32.97 rows=1311 width=8) (actual time=0.050..0.395 rows=99 loops=1)
Index Cond: ((id > $1) AND (id < $2))
Total runtime: 0.851 ms
(4 rows)
Of course, the specific numbers shown here depend on the actual contents of the tables involved. Also note that the numbers, and even the selected query strategy, might vary between PostgreSQL releases due to planner improvements. In addition, the ANALYZE command uses random sampling to estimate data statistics; therefore, it is possible for cost estimates to change after a fresh run of ANALYZE, even if the actual distribution of data in the table has not changed.
Compatibility
There is no EXPLAIN statement defined in the SQL standard.
