WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

PostgreSQL · Intermediate · question 32 of 100

How do you use the EXPLAIN and EXPLAIN ANALYZE commands to analyze query performance in PostgreSQL?

📕 Buy this interview preparation book: 100 PostgreSQL questions & answers — PDF + EPUB for $5

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.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic PostgreSQL interview — then scores it.
📞 Practice PostgreSQL — free 15 min
📕 Buy this interview preparation book: 100 PostgreSQL questions & answers — PDF + EPUB for $5

All 100 PostgreSQL questions · All topics