Careeroza
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
| Database | Command |
|---|---|
| MySQL | EXPLAIN SELECT ... / EXPLAIN ANALYZE SELECT ... (8.0.18+) |
| PostgreSQL | EXPLAIN (ANALYZE, BUFFERS) SELECT ... |
| SQL Server | "Include Actual Execution Plan" in SSMS, or SET STATISTICS PROFILE ON |
| Oracle | EXPLAIN PLAN FOR ... then DBMS_XPLAN.DISPLAY |
| SQLite | EXPLAIN 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
| id | parent | notused | detail |
|---|---|---|---|
| 3 | 0 | 216 | SCAN o |
| 7 | 0 | 45 | SEARCH 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.