EXPLAIN is a diagnostic keyword that asks the database engine to reveal how it will execute (or has executed) a query. The output, often called the execution plan, lists each processing step, the order of operations, estimated or actual rows processed, cost estimates, and sometimes I/O, CPU, or memory statistics. By studying the plan, developers can verify that appropriate indexes are used, detect full table scans, gauge join algorithms, and identify performance bottlenecks.Behavior differs slightly by dialect:- PostgreSQL: EXPLAIN returns estimated plans. Adding ANALYZE actually runs the query and appends real execution times and row counts.- MySQL and MariaDB: EXPLAIN gives an estimated plan; EXPLAIN ANALYZE (v8.0+) executes the statement and produces timing data.- Oracle: EXPLAIN PLAN populates the PLAN_TABLE; SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY) is required to view it.- SQL Server: SET SHOWPLAN_XML ON or the GUI Display Estimated Execution Plan serves the same purpose.- SQLite: EXPLAIN QUERY PLAN shows a simplified plan.Key caveats:- Plain EXPLAIN does not mutate data; with ANALYZE it WILL execute the statement and may modify data for INSERT/UPDATE/DELETE queries.- Cost units are relative to the optimizer and are not wall-clock times.- Output format varies (text, XML, JSON); always consult the dialect docs when parsing programmatically.
ANALYZE
(boolean) - Execute the statement and append actual run statistics.VERBOSE
(boolean) - Include additional details such as target columns.COSTS
(boolean) - Show estimated startup and total costs.BUFFERS
(boolean) - Include shared/local/temp page statistics (requires ANALYZE).FORMAT
(text) - Output format: TEXT, XML, JSON, YAML.TIMING
(boolean) - Show per-node timing when ANALYZE is on.Note
- Exact option names vary by dialect; if unsupported, specify "None".ANALYZE, VACUUM, CREATE INDEX, SET enable_seqscan, SET work_mem, Query Optimizer, Execution Plan
PostgreSQL 6.0 (1997); similar functionality later adopted by other databases
No. EXPLAIN only inspects the query. However, EXPLAIN ANALYZE will run the statement, so an UPDATE or DELETE will modify rows.
Cost is an internal unit used by the optimizer to compare alternate plans. It combines estimated I/O and CPU work, not elapsed time.
In PostgreSQL use: `EXPLAIN (FORMAT JSON) SELECT ...;`. MySQL 8.0 has `EXPLAIN FORMAT=JSON`.
Large gaps between estimated and actual rows indicate stale statistics or data skew. Run ANALYZE (or equivalent) to refresh stats, or create more selective indexes.