Overview

SQL is declarative: the optimizer turns your query into a plan, a tree of physical operators (scans, joins, sorts, aggregates), by estimating the cost of alternatives. Most “the database is slow” problems are a bad plan, and a bad plan is usually a bad row estimate.

Core concepts

flowchart LR
  A[SQL text] --> B[Parse and bind]
  B --> C[Rewrite / simplify]
  C --> D[Optimize: enumerate plans, cost them]
  D --> E[Execute chosen plan]
  S[(Statistics)] --> D
  • Statistics describe data: row counts, distinct values, most common values, histograms. They feed cardinality estimates (how many rows each step returns).
  • Cost combines estimated I/O and CPU for each operator. The cheapest total wins. Costs are relative units, not milliseconds.
  • Join order and algorithm are the biggest decisions (sql-joins); the number of orders grows factorially, so engines prune or use heuristics for many tables.
  • Plan reuse: prepared statements and plan caches avoid re-optimizing, but a plan built for one parameter value can be wrong for another (parameter sniffing in SQL Server, bind peeking in Oracle, generic versus custom plans in PostgreSQL).

How to look at plans:

EngineEstimated planActual plan with row counts
PostgreSQLEXPLAINEXPLAIN (ANALYZE, BUFFERS)
SQL ServerEstimated Execution Plan, SET SHOWPLAN_XML ONActual Execution Plan, SET STATISTICS XML ON
OracleEXPLAIN PLAN + DBMS_XPLAN.DISPLAYDBMS_XPLAN.DISPLAY_CURSOR with GATHER_PLAN_STATISTICS

Worked example

EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT * FROM big WHERE customer_id = 42;

Read plans inside out, comparing estimated rows with actual rows at each node. A gap of 10x or more points at stale or missing statistics, correlated predicates, or a function wrapped around a column. The plans in indexing-theory show the same query going from a parallel sequential scan to a bitmap index scan once an index exists.

Pitfalls and production notes

  • Refresh statistics after bulk loads (ANALYZE, UPDATE STATISTICS, DBMS_STATS.GATHER_TABLE_STATS). Autovacuum, auto-update statistics and the Oracle automatic stats job do this on a schedule, which may lag a big load.
  • Do not tune by cost alone; compare actual time and buffers or reads.
  • Hints and forced plans are a last resort; they freeze a decision the data may outgrow.
  • Test with production-sized data. A plan on 1,000 rows says little about 100 million.

Practice questions

  1. A query estimates 1 row but returns 2 million. Name three possible causes.
  2. Why can the same query be fast for one customer and slow for another?
  3. Which operator would you expect for a join of a small filtered table to a huge indexed one?

References

indexing-theory · sql-joins · table-partitioning · transactions-acid · pg-explain-analyze · sqlserver-execution-plans · oracle-execution-plans