The EXPLAIN and EXPLAIN ANALYZE commands are powerful tools for analyzing query performance in PostgreSQL.
EXPLAIN will show the plan that the PostgreSQL planner generated for a SQL statement while EXPLAIN ANALYZE will show the same plan but also execute the query and display actual runtimes and row counts.
To use EXPLAIN, simply prepend the SQL statement with the keyword EXPLAIN, like this:
EXPLAIN SELECT * FROM mytable WHERE id = 10;
This will output the execution plan for the query. The output consists of a tree of nodes, with each node representing an operation in the plan. The nodes are indented to show the hierarchical structure of the plan.
Heres an example output:
QUERY PLAN
-----------------------------------------------------
Seq Scan on mytable (cost=0.00..12.50 rows=1 width=62)
Filter: (id = 10)
The output gives us important information about the plan. In this case, the query uses a sequential scan on the ‘mytable‘ table and applies a filter for ‘id = 10‘. The ‘cost‘ field represents the estimated cost of each operation in the plan. Lower costs indicate faster operations.
EXPLAIN ANALYZE is used in the same way as EXPLAIN, but it also executes the query and shows actual runtimes and row counts. Heres an example:
EXPLAIN ANALYZE SELECT * FROM mytable WHERE id = 10;
The output will be similar to EXPLAIN’s, but it will include runtimes and row counts for each node in the plan.
QUERY PLAN
------------------------------------------------------------
Seq Scan on mytable (cost=0.00..12.50 rows=1 width=62) (actual time=0.015..0.015 rows=1 loops=1)
Filter: (id = 10)
Rows Removed by Filter: 999
Planning time: 0.086 ms
Execution time: 0.042 ms
The ‘actual time‘ field represents the actual time taken by each operation in the plan. The ‘loops‘ field represents the number of times the operation was executed. The ‘Rows Removed by Filter‘ field shows how many rows were filtered out by the WHERE clause.
In conclusion, EXPLAIN and EXPLAIN ANALYZE commands in PostgreSQL are useful tools for analyzing and optimizing query performance. By examining the query execution plan and collecting actual runtime statistics, you can identify slow-performing queries and improve them.