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:
| Engine | Estimated plan | Actual plan with row counts |
|---|---|---|
| PostgreSQL | EXPLAIN | EXPLAIN (ANALYZE, BUFFERS) |
| SQL Server | Estimated Execution Plan, SET SHOWPLAN_XML ON | Actual Execution Plan, SET STATISTICS XML ON |
| Oracle | EXPLAIN PLAN + DBMS_XPLAN.DISPLAY | DBMS_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
costalone; 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
- A query estimates 1 row but returns 2 million. Name three possible causes.
- Why can the same query be fast for one customer and slow for another?
- Which operator would you expect for a join of a small filtered table to a huge indexed one?
References
- PostgreSQL manual, Using EXPLAIN: https://www.postgresql.org/docs/current/using-explain.html
Related
indexing-theory · sql-joins · table-partitioning · transactions-acid · pg-explain-analyze · sqlserver-execution-plans · oracle-execution-plans