Skip to content

Query Plan

In one line

A query plan is the optimizer's chosen execution strategy — the sequence of operations to run a query.

In simple words

A query plan is the execution strategy the database query optimizer creates for your SQL query. It's a tree of operations:

  1. Scan operations — how to access each table (sequential scan, index scan, bitmap scan)
  2. Join operations — how to combine tables (nested loop, hash join, merge join)
  3. Sort and aggregate — ordering and grouping steps
  4. Filter — WHERE clause conditions applied at each stage

The optimizer considers multiple possible plans and picks the one with the lowest estimated cost. Factors include available indexes, table statistics, data distribution, and join order.

View the plan with EXPLAIN. A good plan uses indexes and efficient join strategies; a bad plan does full table scans and nested loops on large datasets.

Example

sql
-- Query plan as a tree:
-- SELECT name FROM users JOIN orders ON users.id = orders.user_id WHERE orders.total > 100

-- Plan might be:
-- Hash Join
--   -> Seq Scan on users
--   -> Filter (total > 100)
--        -> Index Scan on orders_user_idx

-- Bad plan (slow):
-- Nested Loop Join
--   -> Seq Scan on users (10000 rows)
--   -> Seq Scan on orders (50000 rows)
-- Total: 10000 * 50000 = 500M comparisons

-- Good plan (fast):
-- Hash Join
--   -> Seq Scan on users (10000 rows)
--   -> Filter + Index Scan on orders (100 rows)
-- Total: 10000 + 100 = 10100 operations

The plan is a tree of operations. Hash joins on indexed data are fast. Nested loops on full table scans are slow. The optimizer picks the cheapest plan.

Common confusions

  • Confused with: query optimization

    The difference: Query optimization is the process of the optimizer evaluating multiple plans and choosing the best one. A query plan is the specific result — the chosen execution strategy. Optimization is the process; the plan is the output.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary