Why Query Planning Is a Mathematical Problem
Why is mathematics important in database query planners? SQL usually describes the result a user wants, not every physical step required to obtain it. The database must estimate how many rows survive filters, compare scan and join strategies, price CPU and input/output work, consider memory limits and choose one execution plan from many possibilities. Beneath a short query are probability, statistics, combinatorics and optimisation.
The importance of mathematics becomes visible when the same query runs quickly today and slowly tomorrow, a planner chooses an index but reads most of the table anyway, one mistaken row estimate multiplies through several joins, or a sort spills from memory to storage. A planner does not know future data perfectly. It makes a decision using summaries, models and configurable cost assumptions.
This article uses the current PostgreSQL 18 documentation on EXPLAIN, planner statistics and row-estimation examples, checked on 10 October 2026. Other database engines use different estimators, operators and cost units. The worked examples explain transferable mechanisms rather than prescribing one production setting.
Quick Reading Routes
- Students: begin with declarative queries, selectivity, cardinality and scan costs.
- Parents: read the everyday analogies, safe experiments, misconceptions and learning steps.
- Teachers: use the row-estimation exercises, join-order puzzles and plan-comparison investigations.
- Career explorers: connect this topic to software engineering, data platforms, analytics, cloud services and performance work.
Practise on synthetic data in an authorised environment. `EXPLAIN ANALYZE` actually executes a query in PostgreSQL; do not run modifying or expensive statements on shared production systems without safeguards.
A Query Describes a Result, Not One Route
Declarative language leaves choices open
A statement such as `SELECT * FROM orders WHERE customer_id = 42` asks for matching rows. It does not necessarily demand a table scan, index scan or particular page order.
This separation allows the database to adapt its route to table size, data distribution, indexes, memory and hardware.
Equivalent plans can have different costs
Two plans can return the same rows while doing different work. One reads every table page and tests the predicate. Another follows an index to candidate row locations, then fetches table pages.
When only a few rows match, the index path may be cheaper. When most rows match, many random fetches can cost more than a sequential pass.
Correctness and efficiency are separate
The query semantics define correct results. The optimiser searches among transformations and physical operators that preserve those semantics.
A fast wrong answer is not optimisation. A correct slow answer may still need a better plan, schema or query.
Cardinality Is the Central Quantity
Cardinality counts rows
Base-table cardinality is the number of rows. Intermediate cardinality is the number expected after a filter or join. These counts determine how much later work each operator receives.
If a filter passes 1% of a one-million-row table, estimated output is 10,000 rows.
Selectivity is a fraction
Selectivity s is the estimated fraction of input rows passing a condition. Estimated rows are `N × s`.
For two independent conditions with selectivities s1 and s2, a simple estimate multiplies them: `N × s1 × s2`. Independence is often the weak assumption.
Error multiplies downstream
Suppose a planner estimates 100 rows but reality is 100,000. A nested-loop join that looked cheap can execute its inner work one thousand times more often than expected.
The plan can be locally reasonable under a globally wrong estimate. Diagnose estimate error before blaming the chosen operator.
Histograms Approximate Data Distributions
Equal-frequency buckets summarise ranges
Storing every value count would be expensive. A histogram divides observed values into buckets represented by boundaries. PostgreSQL statistics include histogram information for suitable columns.
For a range predicate such as `price < 75`, the estimator locates 75 among boundaries and interpolates a fraction within the bucket.
Interpolation is an assumption
If a bucket spans 50 to 100 and values are assumed roughly uniform within it, 75 lies halfway, suggesting half the bucket's rows satisfy the within-bucket part.
If values cluster near 50, linear interpolation underestimates matches. If they cluster near 100, it overestimates.
More buckets use more storage and sampling
A higher statistics target can create a finer summary and improve estimates for irregular data, at added collection time and catalogue space. It does not guarantee perfection.
Tune statistics where errors materially affect plans, rather than maximising every column by default.
Most-Common-Value Lists Protect Skew
Popular values deserve explicit counts
Suppose country codes appear unevenly: 60% SG, 15% MY, 10% ID and many smaller groups. A uniform estimate of 1/distinct_values would badly understate SG.
A most-common-value list stores frequent values and their frequencies separately.
The remaining mass is shared
After subtracting the common-value frequencies, the estimator distributes remaining probability among other distinct values under a model.
If common values occupy 85% and 100 other values share the remaining 15%, a simple frequency for an unlisted value is 0.0015.
Heavy hitters change capacity
A query for the dominant value may return hundreds of times more rows than one for a rare value. One prepared query shape can therefore need different plans depending on parameters.
This is why “the query is the same” does not imply “the best plan is the same.”
Distinct Counts Support Equality Estimates
Uniform fallback
When no exact frequency is known, an equality predicate may be estimated roughly as `1 / n_distinct` of rows under a uniform assumption.
With one million rows and 10,000 distinct customer IDs, that predicts about 100 rows per customer.
Real customers are not uniform
Some customers place one order and others thousands. The mean of 100 hides a heavy tail.
Statistics can capture some frequent IDs, but rare individual behaviour remains uncertain.
Distinct values also affect joins
For a join `A.key = B.key`, estimated matches depend on row counts, null fractions, distinct counts and distribution assumptions. A simple heuristic might relate output to `|A| × |B| / max(dA, dB)` when keys overlap.
It is a model, not a theorem about arbitrary data.
Correlated Columns Break Independence
City and postal code are related
Suppose `city = 'Singapore'` passes 10% of a global table and a Singapore postal prefix passes 1%. Multiplying gives 0.1%, but the prefix may occur only within Singapore, making the combined selectivity closer to 1%.
The independence estimate is wrong by a factor of ten.
Functional dependencies reduce surprise
If one column strongly determines another, separate selectivities should not be multiplied naively. PostgreSQL supports extended statistics that can capture some dependencies, multivariate distinct counts and most-common combinations.
These summaries help only for relationships they are configured and collected to represent.
Hidden correlation changes over time
Marketing campaigns, school terms or data migrations can alter relationships. Statistics collected last month may not describe today's distribution.
Monitor estimate error after major data change.
Sampling Introduces Statistical Error
ANALYZE examines a sample
For large tables, collecting full exact distributions would be expensive. PostgreSQL's statistics process samples rows and builds summaries.
A sample estimates population properties. Rare categories may be missed, and frequency estimates vary from sample to sample.
Larger samples reduce random error
For a simple proportion estimate, standard error scales roughly like `sqrt(p(1-p)/n)` under independent sampling. Quadrupling n roughly halves this component of error.
Database sampling details are more complex, but the square-root relationship explains diminishing returns.
Bias is different from variance
More samples reduce random variation but do not fix a systematically unrepresentative process or a model that assumes independence where none exists.
Diagnose whether error comes from sample noise, stale data or wrong structure.
Cost Is Measured in Relative Units
Cost is not elapsed milliseconds
PostgreSQL plan output includes startup and total cost in planner units based on configurable parameters. They compare alternatives inside the model; they are not direct predictions of wall-clock time.
Two machines can execute the same cost differently, and concurrent load changes actual duration.
Startup and total cost answer different questions
Startup cost is work before the operator can return its first row. Total cost estimates work to return all rows.
A sort may have high startup because it must read and order input before producing output. A streaming scan can produce rows early.
LIMIT changes the relevant objective
If a query needs only ten rows, the planner can favour a path with low startup even if its full total cost is larger. It expects execution to stop early.
The objective is the cost of the demanded result, not always the cost of exhausting the plan.
Sequential and Index Scans Trade Patterns
Sequential scan touches the table broadly
A sequential scan reads table pages in order and tests rows. Its cost is attractive when much of the table is needed or when storage favours sequential access.
It also avoids the overhead of traversing an index and fetching scattered rows.
Index scan narrows candidates
An index can locate key ranges quickly, then retrieve matching table tuples. The mathematics of database indexes, B-trees and logarithmic search owns the data-structure detail.
The planner's separate question is whether using that structure is cheaper for this predicate and data distribution.
Selectivity sets the crossover
If an index returns 20 rows from ten million, it likely avoids much work. If it returns eight million scattered rows, repeated heap access may be worse than one sequential scan.
The crossover depends on clustering, caching, page cost, row width and hardware.
Bitmap Scans Combine Two Ideas
Collect locations before table access
A bitmap index scan can gather matching tuple locations, combine conditions and visit table pages in a more ordered way. This can suit a medium-sized result where individual random fetches are costly but a full scan is excessive.
The bitmap is an intermediate set representation.
AND and OR become set operations
Two indexes can produce bitmaps combined by intersection for AND or union for OR. This is Boolean algebra applied to row-location sets.
The combination is useful only if the resulting selectivity and memory cost justify it.
Lossy representation requires recheck
When memory is constrained, a bitmap may identify pages rather than exact tuples, requiring the executor to recheck conditions on rows from those pages.
Compression reduces memory while adding verification work.
Join Order Creates a Combinatorial Search
Many tables mean many orders
For n tables, the number of simple left-deep join orders grows roughly factorially, n!. At ten tables, 10! is 3,628,800 before considering join algorithms and access paths.
The optimiser cannot exhaust every arbitrary possibility for very large n without spending too long planning.
Dynamic programming reuses subproblems
A planner can find good plans for smaller table subsets, then combine them. This avoids recomputing every partial join from scratch.
The state space is still large, so engines use thresholds, heuristics or genetic search for complex queries.
Join graphs restrict valid choices
Predicates connect tables in a graph. Joining two unrelated large tables before applying a selective relationship can create a huge intermediate product.
Good plans tend to apply selective filters and useful join edges early, subject to semantic constraints.
Nested-Loop Joins Multiply Inner Work
One outer row triggers inner access
For each outer row, a nested-loop join searches the inner input. A rough cost is `outer_cost + outer_rows × inner_cost_per_probe`.
With 100 outer rows and a 0.1-unit indexed probe, probes cost about 10 units. With one million outer rows, they cost about 100,000.
Small outer inputs are powerful
Nested loops can be excellent when an early filter leaves few rows and the inner lookup is indexed. They can be disastrous when cardinality is underestimated.
The operator is not inherently slow; its suitability depends on counts.
Caching can change repeated probes
If many outer rows share the same inner key, memoisation or buffer cache may reduce physical work. The cost model estimates such effects imperfectly.
Measure actual loops and buffer use in execution plans.
Hash Joins Exchange Memory for Linear Work
Build and probe
A hash join builds a hash table from one input, usually the smaller, then probes it with rows from the other. Expected lookup is near constant time under a good hash distribution.
Rough work is O(|A| + |B|), apart from output size and memory effects.
Memory limits cause batching
If the build side does not fit in memory, the executor partitions or spills data to storage. Extra passes increase I/O and latency.
A plan estimated for 50 MB but actually receiving 5 GB can behave very differently.
Hash collisions do not imply wrong answers
Different keys can share a hash value. The executor checks actual join equality after locating candidates.
Hashing narrows search; it does not replace correctness comparison.
Merge Joins Use Ordered Inputs
Sorted streams advance together
When both inputs are ordered by the join key, a merge join can scan them in tandem. Work is roughly linear in input size plus any sort cost.
Indexes or earlier operators may already provide the order.
Sort cost can dominate
Comparison sorting has typical O(n log n) behaviour. Large sorts may spill to storage if memory is insufficient.
A merge join can be attractive when order is free or reused, less so when two enormous inputs require fresh sorts.
Duplicates create groups
If many rows share a key on both sides, the join output for that key can be the product of group sizes. Ten thousand matching rows on each side can produce 100 million pairs.
No join algorithm can avoid returning a genuinely enormous result demanded by the query.
Sorts, Aggregates and Memory Grants
Grouping estimates affect memory
A hash aggregate needs space for groups. If distinct-group count is underestimated, it may spill or use more batches.
Estimating 1,000 groups when reality is one million changes the memory problem by three orders of magnitude.
Ordered aggregation trades sort for streaming
If input is sorted by group key, an aggregate can process one group at a time. Producing that order may require a sort, unless an index or upstream merge already provides it.
Plans can reuse physical properties; operator costs are not independent.
More memory is not always better globally
Giving one query a large memory allowance can prevent its spill, but many concurrent queries can exhaust the machine. Capacity planning multiplies per-query limits by concurrency.
A 1 GB setting with 100 simultaneous memory-hungry operations does not fit in 32 GB.
Storage Hardware Changes Relative Costs
Random and sequential access differ
Rotating disks penalise random seeks heavily. Solid-state storage reduces seek cost but still has controller, queueing and bandwidth limits.
Cost parameters should reflect the environment well enough for plan comparison.
Cache hits avoid physical reads
Database buffers and operating-system caches can serve pages from memory. A plan that looks I/O-heavy may run quickly when warm and slowly when cold.
The cache mathematics in computer memory addresses, cache hits, latency and bandwidth helps explain the difference.
SSD internals still matter
Write amplification, queue depth and garbage collection affect latency. The article on solid-state drives, NAND pages, wear levelling and error correction explains that storage is not one constant-time box.
Benchmark representative workloads rather than copying cost settings blindly.
Parameter Values Can Change the Best Plan
Selective and common values differ
For a rare customer, an index nested loop may be ideal. For a common status matching 80% of rows, a sequential scan and hash join may be better.
One prepared statement can receive both.
Generic plans average across parameters
Database engines may choose between custom plans that use current parameter values and generic plans that amortise planning. A generic plan avoids repeated planning cost but can be poor for skewed values.
The trade-off depends on execution frequency, planning time and value distribution.
Parameter sensitivity needs measurement
Test representative rare, median and heavy-hitter values. One benchmark parameter does not establish plan quality for the population.
Record both estimated and actual rows for each case.
Statistics Become Stale
Data changes after collection
Bulk loads, deletions and seasonal shifts alter row counts and distributions. Planner statistics remain a snapshot until refreshed.
If a table grows from one million to 100 million rows, old assumptions can produce very different cost comparisons.
Automatic maintenance has thresholds
PostgreSQL can automatically analyse tables based on change thresholds and configuration. Very large or unusual tables may need tuned settings or deliberate analysis after bulk operations.
Do not schedule collection without considering its resource cost.
Staleness and model error look similar
Both can produce wrong row estimates. Compare statistics age, sample summaries and data relationships before choosing a fix.
Increasing the target cannot repair a statistic that was never refreshed.
EXPLAIN Is a Measurement Instrument
Plain EXPLAIN shows estimates
PostgreSQL `EXPLAIN` shows the chosen plan with estimated costs and rows. It does not execute the statement merely to obtain actual row counts.
This makes it safer for inspecting potentially modifying statements, though planning itself can still require locks and catalogue access.
EXPLAIN ANALYZE executes
`EXPLAIN ANALYZE` runs the query and reports actual timing and rows. For `UPDATE`, `DELETE` or other modifying statements, effects occur unless contained and rolled back appropriately.
The official PostgreSQL documentation warns users to account for this behaviour.
Compare estimates at every node
Find the first operator where actual rows diverge substantially from estimates. Later errors may be consequences of that earlier mistake.
Also inspect loops: 10 rows per loop over 100,000 loops is one million rows of work.
Optimisation Includes Planning Time
Better search can cost too much
Spending ten seconds finding a plan that saves one millisecond is wasteful for a one-off query. For a query executed billions of times, extra planning may pay.
The objective includes planning plus repeated execution cost.
Heuristics prune the search
Optimisers discard dominated or implausible alternatives, use equivalence classes and stop exhaustive search beyond thresholds.
This means the chosen plan can be good without being proven globally optimal.
Plan stability has value
A slightly slower but predictable plan may be operationally preferable to one that swings between fast and disastrous with small estimate changes.
Performance engineering considers tail behaviour and recovery, not only the lowest benchmark mean.
Parallel Plans Add Coordination Costs
Workers divide eligible work
A planner can assign portions of a scan, join or aggregate to several workers. If work divided perfectly among p workers and coordination were free, elapsed compute time might approach 1/p of the serial value.
Real speed-up is smaller because setup, data exchange, skew and serial stages remain.
Amdahl's Law gives a ceiling
If fraction f of work is parallelisable, ideal speed-up on p workers is `1 / ((1 – f) + f/p)`. With f = 0.9 and p = 8, the ceiling is about 4.71, not 8.
Adding more workers gives diminishing returns because the serial 10% remains.
Skew leaves workers idle
If one key owns half the rows, one worker may receive much more work than others. Completion follows the slowest partition, not the average partition.
Measure per-worker rows and time. Parallelism multiplies resources and can worsen contention when many queries run together.
Instrumentation Changes the Measurement Slightly
Timing has overhead
`EXPLAIN ANALYZE` records counters and, depending on options, timing and buffer information. Instrumentation adds work, especially for operators called millions of times.
The reported plan remains extremely useful, but it is not a perfectly invisible observer.
Cache state affects repeated tests
The first run may load pages from storage; later runs reuse cache. Comparing plans from different cache states can misattribute the speed difference.
Record warm or cold conditions, concurrent load and server configuration.
Repetition supports confidence
Run safe representative queries several times and report distributions. One unusually fast execution can result from favourable cache and scheduling; one slow execution can overlap background maintenance.
Performance claims need enough samples and a defined environment.
Partition Pruning Removes Impossible Data
Constraints narrow the search space
A table partitioned by month can place January rows separately from February rows. A query constrained to January need not scan partitions that cannot satisfy the predicate.
This is set elimination: if partition P's value range is disjoint from the query range Q, then `P ∩ Q` is empty.
Pruning can happen at different stages
Some predicates are known during planning; others depend on parameters or values produced while executing. Engines may prune partitions during planning, plan initialisation or execution according to their capabilities.
Check the actual plan rather than assuming a partition key guarantees pruning.
Too many partitions add overhead
Every partition brings metadata and planning choices. Thousands of tiny partitions can lengthen planning and maintenance even when execution touches few.
Choose boundaries from access patterns, retention and operational needs—not a belief that more partitions automatically mean more speed.
Partitioning does not replace indexes
Pruning can remove irrelevant partitions, while an index finds rows inside the remaining ones. These mechanisms solve different levels of the search problem.
A January query can still need to scan millions of January rows if no selective inner access path exists.
Materialisation Trades Recalculation for Storage
Reusing a result can save repeated work
If an intermediate result is needed many times, an executor can materialise it once and read it again. Let computation cost be C, read-back cost R and reuse count k. Recomputing costs roughly kC; materialising costs about C + kR plus write and memory overhead.
Materialisation helps when R is much smaller than C and the result fits efficiently.
Large intermediates can spill
An underestimated result may exceed memory and write to temporary storage. The plan then pays serialisation, I/O and later reads.
Measure temporary bytes and row counts when an apparently elegant reusable subplan becomes slow.
Reuse can change semantics under volatility
Some expressions or functions are volatile: repeated evaluation may intentionally produce different results or observe changing state. An optimiser cannot freely compute them once unless semantics permit.
Mathematical equivalence must include side effects and volatility, not only returned values in one example.
Common subexpressions are not always free wins
Sharing work can increase lifetime and memory pressure, while independent evaluation might allow early filtering. The planner weighs total context.
Optimisation is a systems decision rather than a collection of isolated algebra tricks.
Common Misconceptions to Correct
“Using an index is always faster”
Indexes help selective access. Reading most rows through scattered index lookups can cost more than a sequential scan.
“Cost equals milliseconds”
Planner cost is a relative model in configured units. Actual time depends on hardware, cache, concurrency and execution.
“EXPLAIN ANALYZE is read-only”
It executes the statement. Modifying queries can modify data unless controlled.
“More statistics guarantee the perfect plan”
Statistics are sampled summaries used by imperfect models. More detail can help but cannot capture every correlation or future value.
“The fastest plan for one parameter is best”
Skew can make rare and common values need different strategies.
“The planner caused every slow query”
Locks, storage stalls, network delay, concurrent load, large requested results and application behaviour can dominate even with a sensible plan.
How Students Can Build Transferable Skill
Estimate rows by hand
Create a table of 10,000 fictional books with genre, language and year. Define frequencies and calculate expected rows for single predicates.
Then add correlation, such as one genre appearing mostly in one language, and show why independence multiplication fails.
Compare scan costs
Assign sequential page cost 1, random page cost 4 and CPU test cost 0.01. Estimate a full scan and index path for match fractions 0.01%, 1%, 20% and 80%.
Find the approximate crossover and explain why it depends on page clustering.
Solve a join-order puzzle
Give four tables with row counts and join selectivities. Calculate intermediate sizes for different orders.
Observe how applying a selective join early can prevent a huge temporary result.
Read an authorised plan
On a local sample database, compare `EXPLAIN` estimates with `EXPLAIN ANALYZE` actual rows for safe SELECT queries. Change data skew, run ANALYZE and compare again.
Record assumptions and avoid shared production systems.
Guidance for Parents and Teachers
Start with routes through a library
To find three books, a librarian can scan every shelf or use a catalogue then visit exact locations. The catalogue route is good for a few books; scanning may be simpler when almost every book is needed.
Then explain where the analogy breaks: database pages, caches and joins create more complex costs.
Reward estimates before software output
Students should predict which filter is selective and which join order is dangerous before opening a plan. Tools then test reasoning rather than replace it.
Ask why an estimate might be wrong.
Use mistakes as model evidence
When prediction and execution differ, identify whether the statistic, independence assumption, hardware cost or measurement boundary was wrong.
That reflection is more valuable than memorising operator names.
Mathematics Learning in Singapore
The MOE secondary mathematics syllabuses centre mathematical problem solving and include ratio, algebra, graphs, probability, statistics and algorithms. Query planning connects these ideas: selectivity is a proportion, histograms approximate distributions, join orders create combinatorial search, and cost functions compare alternatives.
Students can practise with paper tables, spreadsheets and a small local database. The transferable skill is to predict from a model, measure execution, compare estimate with evidence and refine the model.
SEAB states that the Singapore-Cambridge Secondary Education Certificate begins in 2027 with G1, G2 and G3 subjects; current information is on the SEC page. This article is enrichment, not an examination or admissions claim.
Did You Know?
A plan can be the cheapest according to the planner's model and still be slow in reality because the row estimates or cost assumptions were wrong.
Ten joined tables already permit millions of simple orderings. Optimisers need algorithms and heuristics just to search plans quickly enough.
An index can make a query slower when most rows qualify, because following many scattered pointers costs more than reading the table in order.
Frequently Asked Questions
What mathematics is most useful for query planning?
Start with ratios, algebra, probability, statistics and logarithms. Combinatorics, algorithms and optimisation become important for joins and plan search.
What is cardinality estimation?
It is predicting how many rows an operator will output. Those predictions influence scan, join, sort and memory choices.
Why can estimates be wrong?
Statistics may be sampled, stale or too coarse; columns may be correlated; parameters may be skewed; and models simplify storage and execution.
Is a sequential scan bad?
No. It can be the cheapest way to read a large fraction of a table, especially with efficient sequential I/O.
What does EXPLAIN ANALYZE do?
In PostgreSQL it executes the statement and reports actual execution information alongside estimates. Use it carefully, especially for statements that modify data.
Should developers force a plan?
Hints or rewrites can help specific cases but may become brittle as data changes. First investigate statistics, query semantics, schema and cost assumptions.
Does database-performance knowledge guarantee a data career?
No. It supports a pathway alongside SQL, programming, data modelling, systems, testing and communication.
Useful Next Reading
- Read PostgreSQL's current documentation on Using EXPLAIN.
- Review Statistics Used by the Planner and Row Estimation Examples.
- Connect access paths to database indexes, B-trees and logarithmic search.
- Compare execution state with database transactions, atomicity, isolation and concurrency.
- Review the MOE secondary mathematics syllabuses for curriculum context.
Final Perspective
Database query planners show why mathematics matters when one correct request has many possible physical routes. Statistics estimate how much data flows through each step. Cost functions compare scans, joins and sorts. Combinatorial search finds a useful plan before planning itself becomes too expensive.
The strongest question is not “Why did the database ignore my index?” It is “What cardinalities did it estimate, which distributions and dependencies did the statistics represent, what costs did it compare, and where did actual execution first diverge?”
That question turns performance tuning from folklore into investigation. It also teaches students a durable method: build a model, state its assumptions, compare prediction with evidence, and improve the model without pretending uncertainty has disappeared.
