Query execution and optimization
The same SQL can use several physical plans. Their cost depends on data and access paths. Compare estimates with observed work to explain the plan that actually ran.
#Section 30Parse, bind, rewrite, plan and execute
Resolve which table owns email, its type, and its join relationships before choosing an access path. Query meaning comes before physical planning.
Parsing turns tokens into a syntax tree. Semantic analysis, or binding, resolves names, scopes, types and permissions. Query rewriting expands or transforms expressions while preserving meaning, such as exposing a view’s underlying query. A query plan is a physical operator tree specifying scans, joins, sorts and result construction. Optimization chooses among candidate plans; execution runs the chosen tree.
A sequential scan visits table pages and tests rows. An index scan navigates candidate index entries and fetches rows. An index-only scan obtains required data from index entries when coverage and visibility permit. A bitmap-style path can collect candidate row locations before visiting heap pages in a more organized order. Selectivity and locality determine which path saves work.
An iterator execution model asks child operators for their next tuple: a join requests inputs, a filter tests them, and the projection computes outputs. Other engines process batches or compile specialized code. Pipelining passes outputs onward without materializing the complete intermediate result. A sort or a hash-table build may need to consume substantial input before producing its first output, so it can be a blocking stage.
Do not equate written SQL order with operator order. A selective customer lookup can precede joining to bookings even if the query lists tables differently. Outer joins, volatile expressions and semantic dependencies restrict legal transformations. The optimizer is free to reorder only when the result’s meaning is preserved.
One email lookup through the stages
Consider SELECT b.id FROM users u JOIN bookings b ON b.user_id = u.id WHERE u.email = :email. Parsing recognizes the selected expression, join and predicate. Binding proves that u.email belongs to users, that b.user_id is compatible with u.id, and that b.id is the requested booking identity. A nonexistent column is a semantic error before any successful data result can be returned.
The logical request joins customers to bookings and filters the customer email. A valid transformation filters users first, because this inner-join predicate refers only to users. If email is unique, at most one customer remains. The planner can then choose a user-email index followed by booking-user lookups, rather than producing the full join and filtering it afterwards.
The executor asks the user scan for a qualifying row, passes its id into the booking access path and projects each resulting booking id. It can return Asha’s first booking before consuming unrelated bookings. If ORDER BY requires a sort, the first returned row may instead wait for the operator to gather and order its input. The physical plan explains both total work and when output can begin.
#Section 31Nested-loop, hash and sort-merge joins
A customer-booking equality join need not test every pair. Its physical algorithm can exploit keys, memory, or ordering without changing the intended matches.
A nested-loop join searches the inner input for each outer row. A selective outer side with an indexed inner key can work well; unindexed repeated scans can multiply work.
A hash join builds an equality-key table and probes it from the other input. Memory limits can introduce partitioning and spills; repeated keys can still produce a large required output.
A sort-merge join consumes inputs ordered by join keys. It advances the smaller key until keys match, then emits the matching groups’ combinations. The merge work is linear in input traversal plus output, but sorting unsorted inputs adds roughly . Existing compatible index order can remove that sorting cost. Duplicate groups require care because a match can be many-to-many.
| Algorithm | Useful situation | Main snag |
|---|---|---|
| Nested loop | Small outer side, indexed inner matches | Repeated expensive inner work |
| Hash join | Large equality join, useful build fit | Spill, skew, memory use |
| Sort-merge | Ordered large inputs | Sorting and duplicate groups |
Avoiding unnecessary comparisons does not avoid required output. A legitimately large match set can dominate any join algorithm.
Build and probe the actual relationship
In a hash join with users on the build side, hash each user id and store the corresponding customer record in its bucket. Then visit a booking, hash its user_id, inspect the bucket and compare actual ids to resolve collisions. Asha’s two bookings both match Asha’s same user record, so both output pairs are emitted. Charu can be in the build table yet produce no pair in an inner join.
Build and probe visits describe a simplified algorithm, not CPU instructions. Memory spills, collisions, and output work still matter; compare actual runtimes under representative data.
For sort-merge, keep the user and booking inputs ordered by the common key. When the user key is smaller, advance users; when the booking key is smaller, advance bookings. At an equal key, emit the matching group, including all of Asha’s bookings. When both sides have repeated keys, the algorithm must emit each legal pair in the equal-key groups, not just zip their rows together.
#Section 32Statistics, selectivity and join ordering
Underestimating available seats can make a plan repeat far more inner work than expected. Valid indexes cannot repair a mistaken cardinality estimate by themselves.
Selectivity is the fraction passing a predicate. Cardinality estimation predicts output count from that distribution; an incorrect assumption can make repeated inner work much more expensive.
Statistics summarize distributions. A histogram stores bucket boundaries or frequencies over value ranges. Most-common-value statistics capture skew that uniform assumptions miss. Distinct-count estimates help predict grouping and join outputs. Correlated columns break an independence assumption: show identity and seat state may not have independent distributions. PostgreSQL offers extended statistics for suitable cases.
A cost-based optimizer estimates candidate plans’ resource work and chooses a favourable cost. Cost is a model unit, not necessarily elapsed milliseconds. Join order matters because intermediate sizes determine later work. Join a highly selective input early when legal, and the remaining joins may have much less to process. Searching every possible order becomes expensive as the number of relations grows, so optimizers prune or approximate the search.
Statistics age as data changes. A freshly populated or highly skewed table can make a cached assumption poor. Better statistics can change the plan without adding an index. Conversely, accurate estimates do not remove a fundamentally large required output or a badly specified query.
An estimate can be internally consistent and still wrong
A correct calculation using an incorrect selectivity still produces a poor estimate. Compare actual and predicted rows at the same operator boundary.
Histograms handle ranges by summarizing value intervals, while common-value frequencies help with a hot category. Neither automatically understands that one show’s free seats differ from another show’s free seats. Assuming independent predicates multiplies their estimated fractions; correlations can make that multiplication wrong in either direction.
A plan can also choose a correct row estimate yet suffer from memory limits or concurrent resource pressure. Cardinality is one input to cost, not the whole explanation of latency. Compare counts first because they propagate through many operator decisions, then inspect the resource that actually became expensive.
#Section 33Reading EXPLAIN and investigating a slow query
A slow query may read pages, spill, wait on locks, or return too much data. Inspect the exact query and representative parameters before adding an index.
EXPLAIN shows estimates; EXPLAIN ANALYZE executes and observes the plan. Inspect rows, loops, filters, buffers, spills, and waits. Parent times can include child work, so blindly summing them double-counts. EXPLAIN guide.
EXPLAIN (ANALYZE, BUFFERS)
SELECT user_id, SUM(price)
FROM bookings
WHERE status = 'paid'
GROUP BY user_id;A sequential scan can be correct when the query needs much of a small table. An index can lose when it fetches most rows through scattered heap accesses. A mismatched expression, type cast or collation can prevent the intended index condition. Large OFFSET, a correlated subquery with repeated work, and a join at the wrong grain can all waste effort without a missing index.
Reproduce the symptom, inspect the plan, check fresh statistics and wait evidence, then change the actual cause. Measure again under comparable data and cache conditions. Warm and cold runs answer different questions. A cached application result is different from a warm database page cache.
Read repeated work in a plan
Suppose a nested-loop inner scan returns one match each time it runs. A displayed row count of one can look cheap until you inspect how many outer rows invoked it. Multiplying rows per loop by loops tells you how many result rows that node produced across those invocations. If a filter rejects most visited rows, the returned-row count alone can understate traversal work.
A buffer hit means the database found the page in its own buffer cache. A buffer read means it requested the page from the lower layer; that does not necessarily establish an uncached device read because the operating system may cache it. Temporary reads and writes can indicate spilling work, while a long lock wait may be visible in separate session and wait diagnostics rather than as a large row count.
For a suspect index, inspect the index condition separately from a later filter. A condition handled only by a filter may still require broad index traversal. Try the measured query with representative selective and non-selective parameter values, because a plan suitable for Asha’s two bookings may not suit a customer whose history dominates the table.