Execution Plans

How a Query Runs

When you send a query, the database parses it, the optimizer chooses a plan (which indexes, which join order and algorithm), and the executor runs that plan. The plan, not the SQL text, decides the speed.

EXPLAIN

DatabaseCommand
MySQLEXPLAIN SELECT ... / EXPLAIN ANALYZE SELECT ... (8.0.18+)
PostgreSQLEXPLAIN (ANALYZE, BUFFERS) SELECT ...
SQL Server"Include Actual Execution Plan" in SSMS, or SET STATISTICS PROFILE ON
OracleEXPLAIN PLAN FOR ... then DBMS_XPLAN.DISPLAY
SQLiteEXPLAIN QUERY PLAN SELECT ...

Example

A join with no helpful index on the join column:

EXPLAIN QUERY PLAN
SELECT c.CustomerName, o.Amount
FROM Orders o JOIN Customers c ON c.CustomerID = o.CustomerID
WHERE o.Amount > 100;

Result: 2 rows

idparentnotuseddetail
30216SCAN o
7045SEARCH c USING INTEGER PRIMARY KEY (rowid=?)

What to Look For

  • Full table scans (SCAN, Seq Scan, Table Scan) on large tables.
  • Estimated vs actual rows far apart: statistics are stale (ANALYZE / UPDATE STATISTICS).
  • Sorts and temporary tables on big inputs.
  • Nested loops over large row counts where a hash join would be better.