From SQL text to query plan — parsing, optimization, and execution operators
Understanding how a database turns your SQL into a physical execution plan explains why the same logical query can run in 10ms or 10 minutes depending on how it's written. The query optimizer makes cost-based decisions that seem opaque — until you understand what inputs it uses (table statistics, index availability, row estimates) and what operators it assembles (scans, joins, sorts, aggregates).
SQL is declarative — you say what you want, not how to get it. The query engine's job is to figure out the most efficient "how." It parses SQL into a logical plan (a tree of relational algebra operators), then uses table statistics to estimate the cost of many physical plans, and picks the cheapest one. The physical plan uses concrete operators: sequential scan, index scan, hash join, nested loop, sort, hash aggregate.
Stale statistics are the most common cause of sudden query regressions. When a table's data distribution changes dramatically (large import, purge), run ANALYZE immediately. Autovacuum includes ANALYZE, but it may lag behind bulk operations.