Sitemap
Abhinav Thakur

Abhinav Thakur

Engineer @ PocketFM | Obsessed with System Design, Scaling Backends & Crafting Efficient Databases.

Database Series: Query Optimization

23 min readNov 23, 2026

--

Database Indexing & Querying Part 2: How a Database Decides How to Run Your SQL

Press enter or click to view image in full size

Query Optimization and Execution Plans

Cost-based optimization, statistics and cardinality estimation, join algorithms, and predicate pushdown, explained through PostgreSQL and MySQL internals

A university librarian is asked a simple question: “Which books by Indian authors, published after 2015, have been borrowed more than five times?”

There are two ways to answer it. The first is to pull out all two million borrowing records, look up the book behind each one, and then check author and year. The second is to start from the catalogue, narrow it down to the few hundred books that are both recent and by Indian authors, and only then look up how often each was borrowed. Both methods return the identical list. One takes a lunch break, the other takes a minute.

Now add a twist. The librarian does not count the shelves before deciding. She works from last year’s inventory sheet, which says “Indian authors: 40 books”. The real number today is 4,000. Her plan was built on a number that is no longer true, and the minute-long method quietly turns into an hour-long one.

That librarian is a query optimizer. SQL is declarative: you describe what you want, never how to fetch it, so the database has to invent the “how” every single time. This article is about how it does that. We will look at how a cost-based optimizer picks between many equivalent plans, how statistics and cardinality estimation feed that choice (and why they are the weakest link), how the three classic join algorithms differ, and how predicate pushdown shrinks the work before it ever starts.

The inventory sheet maps directly onto the database’s statistics, and “narrow the catalogue first” is exactly what predicate pushdown does. We will return to both.

From SQL Text to an Execution Plan

When a query arrives, the server does not run it directly. It goes through a pipeline: the parser checks syntax and builds a query tree, a rewrite stage expands views and applies rule-based transformations, the planner/optimizer chooses an execution strategy, and only then does the executor run it. PostgreSQL’s internals documentation describes the planner’s job as producing the plan expected to run fastest, among many ways of producing the same result set.

The output of the optimizer is a plan tree. The leaves are scan nodes that read raw rows from tables (sequential scans, index scans, bitmap scans), and above them sit join, sort, and aggregate nodes. Each node has an estimated cost and an estimated row count, and the cost of a parent includes the cost of its children. That tree is exactly what you see when you run EXPLAIN.

For every table in the query, the planner first generates the candidate ways to read it. A sequential scan is always possible; each index whose key matches a predicate adds another candidate. Which of these wins depends on how many rows qualify, which is why we will spend so much time on estimation later. If you want the storage-level picture behind these choices, the earlier posts Database Series : How Databases Store Data and Database Series : B Tree vs LSM Tree cover heap pages and index structures, which are the raw materials the optimizer chooses between.

Two stages are worth separating in your head, because interviewers like to probe the difference. Logical optimization rewrites the query into an equivalent but cheaper algebraic form (push a filter down, flatten a subquery, drop an unneeded join). It is mostly rule-based and mostly safe regardless of data. Physical optimization then chooses concrete algorithms and access paths: which index, which join method, in what order. That second stage is the cost-based part, and it is where statistics matter.

Press enter or click to view image in full size

Cost-Based Optimization: Choosing the Cheapest Plan

Early databases relied on fixed heuristics: always use an index if one exists, always join tables in the order they are written. Those rules are cheap and sometimes right, but they cannot know that an index on a column where 90% of rows match is slower than just reading the table. Whether an index helps depends on the data, and so does the best join order. The idea that fixed this goes back to IBM’s System R (Selinger et al., 1979): estimate the cost of each candidate plan using statistics about the data, and execute the cheapest one. Every mainstream relational engine still works this way.

A cost-based optimizer is really three cooperating parts, a framing used by Leis et al. in their well-known VLDB paper on optimizer quality: cardinality estimation (how many rows will each step produce), a cost model (how expensive is each operator given those row counts), and plan enumeration (which of the astronomically many equivalent plans do we even consider). A mistake in the first part flows into the second, which flows into the third. Keep that chain in mind, because it explains most real-world slow-query incidents.

How the Cost Model Prices a Plan

PostgreSQL expresses cost in arbitrary units anchored to the price of reading one page sequentially. seq_page_cost is 1.0, random_page_cost is 4.0, cpu_tuple_cost is 0.01, cpu_index_tuple_cost is 0.005 and cpu_operator_cost is 0.0025. Only the ratios matter; scaling every number by the same factor changes no decision.

The PostgreSQL documentation walks through the simplest case. A table with 345 pages and 10,000 rows costs 345 × 1.0 + 10,000 × 0.01 = 445 to scan sequentially. Add a WHERE unique1 < 7000 filter and the estimate rises to 470, not falls, because every row is still visited and each now pays a small cpu_operator_cost for the comparison. The filter reduces the rows emitted, not the work done. That distinction (rows scanned versus rows emitted) is a common source of confusion when reading plans.

Each node also reports two numbers: a start-up cost (work before the first row can come out, such as building a hash table or sorting) and a total cost. The difference matters with LIMIT. The docs show a query where adding LIMIT 2 makes the planner abandon a bitmap scan for a plain index scan, because the bitmap scan pays a heavy start-up price that a query needing only two rows should not pay.

One default deserves a closer look. A random_page_cost of 4.0 does not claim that random I/O is physically four times slower than sequential. The documentation says the number is deliberately low because most random reads, such as indexed lookups, are assumed to hit cache. If your working set is fully cached, or storage latency is low, a smaller value is reasonable, and the docs note that setting it equal to seq_page_cost makes sense for a database that fits entirely in RAM. effective_cache_size (default 4GB) plays a related role: it tells the planner how much cache it can assume when pricing index scans, without allocating any memory.

[YOUR PRODUCTION EXPERIENCE HERE: add a short story about a query where changing random_page_cost, adding an index, or refreshing statistics flipped a plan in production, with before/after latency numbers.]

Plan Enumeration and the Join-Order Explosion

For a query over n tables, the number of ways to order the joins grows brutally. With 10 tables there are 10! = 3,628,800 left-deep orderings, and if bushy tree shapes are allowed the count climbs past 17 billion. Optimizers cope with this by using dynamic programming: find the best plan for every pair of tables, reuse those results to find the best for every triple, and so on, discarding dominated plans along the way. PostgreSQL’s documentation describes the planner generating scan paths for each table first, then considering joins, and preferring pairs of tables that are actually connected by a join condition so it does not waste time on Cartesian products.

Exhaustive search still becomes impractical. Beyond roughly ten tables the docs say it is no longer practical to try everything, so PostgreSQL switches to a genetic, probabilistic search once the query has at least geqo_threshold FROM items (default 12). That search is faster but may miss the best plan. MySQL takes a different route, using a greedy, depth-limited search rather than full dynamic programming.

Two settings control how much freedom the planner gets. join_collapse_limit and from_collapse_limit (both default 8) decide how many items the planner will flatten into one big reorderable join list. This leads to a classic interview trap. It is tempting to say "the order I write my joins in affects the plan", and for inner joins in PostgreSQL that is false: an explicit INNER JOIN is semantically identical to listing the tables in FROM, so it does not constrain order. It does start to matter once a query has more joins than join_collapse_limit, and setting that parameter to 1 deliberately forces the written order. Outer joins are different: a LEFT JOIN removes some freedom because rows from the preserved side must survive, and only FULL JOIN fixes the order completely.

The Cost Model Is Not the Weak Link

It is natural to blame the cost formulas when a plan goes wrong, but the evidence points elsewhere. Leis et al. measured PostgreSQL on a realistic multi-join benchmark and found that the effect of cost-model errors was dwarfed by cardinality-estimation errors, and that even fairly simple cost models were sufficient. The PostgreSQL docs themselves warn that cost constants are best treated as averages over your whole workload and that tuning them from a handful of experiments is risky. In other words: before touching random_page_cost, check whether the estimated row counts are right. That is where we go next.

Cached Plans and Parameter Sensitivity

One more production wrinkle: planning costs time, so prepared statements can reuse plans. PostgreSQL can build a custom plan for each execution using the actual parameter values, or a generic plan that ignores them and can be reused. The default plan_cache_mode = auto chooses between them automatically. If the ideal plan depends heavily on the parameter (say, a status value that matches 0.1% of rows for one customer and 60% for another), a generic plan can be wrong for one of them. Knowing this explains the otherwise baffling situation where the same query is fast in a SQL console and slow from the application.

Statistics and Cardinality Estimation: Where Plans Are Really Made or Broken

Cardinality is the number of rows an operator produces. Selectivity is the fraction of input rows that survive a predicate. The optimizer’s basic move is estimated rows = input rows × selectivity, repeated for every filter and every join in the tree. Everything downstream (which index, which join method, how much memory a hash table needs) hangs on those numbers.

What the Database Knows About Your Data

PostgreSQL keeps table-level facts in pg_class: the number of pages (relpages) and rows (reltuples) as of the last VACUUM or ANALYZE. At planning time it checks the current page count, which is cheap, and if the table has grown it scales reltuples proportionally. This is why a table that doubled in size since the last analyze is not estimated as stale-by-100%, but it is also why bulk loads and heavy skew can still fool it.

Column-level facts live in pg_statistic, readable through the pg_stats view, and are gathered by ANALYZE from a random sample rather than a full scan. For each column the planner stores the fraction of nulls (null_frac), the estimated number of distinct values (n_distinct), a list of most common values with their frequencies, and a histogram of the remaining values. The histogram is equal-height: it divides the non-MCV values into buckets that each hold the same fraction of rows, so dense regions of the value range get narrow buckets. The default_statistics_target setting (default 100) controls how many MCV entries and histogram buckets are kept, at the price of a slower ANALYZE, and can be raised for individual columns with ALTER TABLE ... SET STATISTICS. As a rule of thumb the sample size scales with this target, at roughly 300 rows per unit, so 30,000 rows by default.

MySQL’s InnoDB historically leaned on index statistics gathered by sampling index pages, which tell the optimizer little about unindexed columns. Since MySQL 8.0, you can build histograms on any column with ANALYZE TABLE t UPDATE HISTOGRAM ON col WITH 100 BUCKETS, which helps the optimizer estimate filter selectivity and choose better join orders for skewed, non-indexed columns. Unlike PostgreSQL's automatic analyze, those histograms are created and refreshed explicitly.

Worked Estimates, Straight From the PostgreSQL Docs

The documentation includes real numbers worth internalizing, because they show the algorithm precisely. On a 10,000-row table:

  • Equality on a common value. The value ‘CRAAAA’ appears in the MCV list with frequency 0.003, so the estimate is 10,000 × 0.003 = 30 rows. The histogram is not consulted at all for equality.
  • Equality on a value not in the MCV list. The planner subtracts the total frequency of all MCVs from 1 and spreads the remainder evenly across the remaining distinct values: (1 − Σ MCV freqs) / (n_distinct − #MCVs). With 676 distinct values and 10 MCVs this gives 0.0014559, so about 15 rows.
  • Range predicate. For unique1 < 1000, the histogram has ten buckets with bounds {0, 993, 1997, ...}. The value 1000 sits just inside the second bucket, so the planner counts one whole bucket plus a linear fraction of the second: (1 + (1000 − 993) / (1997 − 993)) / 10 = 0.100697, which is 1,007 rows. Inside a bucket it simply assumes values are spread evenly, an assumption we will meet again.
  • Range predicate on a non-unique column. The planner applies the condition to each MCV entry directly and sums the matching frequencies, then uses the histogram only for the non-MCV remainder and adds the two parts.
Press enter or click to view image in full size

When Estimates Go Wrong

Those formulas are simple, and the simplicity is the problem. They rest on a few assumptions that real data violates constantly.

Independence. When a query has two filters, the planner multiplies their selectivities. In the docs, unique1 < 1000 AND stringu1 = 'xxx' gets 0.100697 × 0.0014559 ≈ 0.00015, which rounds to one row. That is fine when the columns are unrelated. It collapses when they are correlated: city and postal code, country and currency, or status = 'shipped' and shipped_at IS NOT NULL. The documentation demonstrates this with two columns that always hold the same value. Each filter alone is estimated at 1%, the AND of both at 0.01%, so the plan assumes 1 row while the table returns 100.

PostgreSQL’s remedy is extended statistics via CREATE STATISTICS. Functional-dependency statistics tell the planner that one column determines another, and fix the example above, but only for equality conditions and only at the column level. N-distinct statistics fix a different estimate: the number of groups for GROUP BY a, b, which the docs show being guessed at 1,000 when the real answer is 100. Multivariate MCV lists go furthest, storing actual value combinations, so the planner can tell that a = 1 AND b = 10 matches nothing and can handle range conditions, at a higher cost in ANALYZE time, storage, and planning time.

Uniformity. Inside a histogram bucket, and across all values that are not in the MCV list, the planner assumes an even spread. Heavy skew that the MCV list does not capture leaves the estimate off.

Joins. For t1.unique2 = t2.unique2 with no MCV data and all-unique keys, the planner uses roughly 1 / max(rows1, rows2) as selectivity, so (50 × 10,000) × 0.0001 = 50 rows. When MCV lists exist on both sides, it compares them directly for the common values and estimates the rest the same way. A subtle point from the docs: the size of the join result is estimated for the pair of relations before any join algorithm is picked, so the estimate does not come from "outer rows × rows per inner lookup", and the two views can diverge.

The deeper issue is compounding. Each join multiplies the previous error. Leis et al. found that the cardinality estimators of the major commercial and open-source systems all produce large errors on realistic multi-join queries. They also found that the damage is sharper when many indexes exist, since a plan built on an underestimate can choose index-driven nested loops that look cheap on paper, whereas engines relying mainly on hash joins and full scans stay robust despite the same errors. So the classic failure looks like this: the planner thinks the outer side of a join has 10 rows, picks a nested loop with an index probe, the outer side really has 2 million rows, and a plan that should take milliseconds takes minutes.

Missing information. When the planner has nothing to go on, it falls back on hardcoded defaults. For pattern matching, for example, PostgreSQL assumes a fixed fraction (0.5% of rows). Wrapping a column in a function, as in WHERE lower(email) = ..., hides the column's statistics from the planner and from ordinary indexes, which is one reason expression indexes (which also collect statistics on the expression) exist.

Staleness. Statistics describe the past. Autovacuum triggers analyze when enough rows change, but a large bulk load, or data whose distribution shifts after the last run, can leave the planner working from a picture that no longer matches the table. This is the librarian’s out-of-date inventory sheet.

Diagnosing: Estimated Versus Actual Rows

The most useful habit is comparing estimated rows with actual rows. EXPLAIN ANALYZE executes the query and prints both for every node. Scan the tree from the bottom for the first node where the two diverge by an order of magnitude or more; everything above it is built on a wrong number, and everything below it is probably fine. A few cautions from the PostgreSQL docs prevent false alarms:

  • The rows and time in actual are averages per execution, so multiply by loops to get the total for a node on the inner side of a nested loop.
  • A node stopped early by a LIMIT, or the inner side of a merge join that stopped reading when the other side ran out, can show a gap that is not a real estimation error.
  • EXPLAIN ANALYZE really runs the statement. Wrap UPDATE and DELETE experiments in a transaction and roll back.

MySQL has an equivalent in EXPLAIN ANALYZE (added in 8.0.18), which reports actual row counts, loop counts, and timings next to the estimates.

Get Abhinav Thakur’s stories in your inbox

Join Medium for free to get updates from this writer.

When you find the bad node, the order of fixes usually goes: run ANALYZE, raise the statistics target for that column, add extended statistics for correlated columns, and only then consider rewriting the query or reaching for enable_* switches. Those switches are crude diagnostic tools, not a long-term plan: they tell you whether the planner's second-best choice was actually better, which is the evidence you need to go fix the estimate.

Ten years after the original paper, the same authors revisited the question and reached a similar conclusion: cardinality estimation remains the central weak point, and robustness and adaptive execution remain open problems, even with learned estimators now being researched. Knowing that the estimator, not the search, is the fragile part is what separates a useful answer to “why did this plan go bad?” from a guess.

Join Algorithms: Nested Loop, Hash Join, and Merge Join

A join combines two inputs, and PostgreSQL’s executor always joins exactly two at a time, building multi-table joins as a tree. For each pair, the planner picks one of three strategies. None is best in general; each wins in a different region of input sizes, indexes, sort order, and memory.

Nested Loop Join

For every row from the outer input, scan the inner input for matches. With no index on the inner side that costs roughly N × M row comparisons, which is why the textbook version has a bad reputation. With an index on the inner join key, each outer row triggers one cheap index lookup, and the total becomes roughly N × log M. Nested loop is the only algorithm that handles arbitrary join conditions, including inequalities, and it produces its first row almost immediately.

The PostgreSQL docs show it winning for a selective query. With t1.unique1 < 10 there are only 10 outer rows, so the plan runs the inner index scan on t2 ten times (loops=10 in EXPLAIN ANALYZE), for a total estimated cost of 118.50. When the inner side has no usable parameterized access, the planner may add a Materialize node so the inner result is computed once and replayed from memory for each outer row. PostgreSQL also has Memoize, which caches inner results by parameter value so repeated outer keys skip the inner scan.

MySQL is the interesting historical case. Until MySQL 8.0.18 its only join strategy was the nested-loop family, including block nested loop, which buffers a batch of outer rows so each inner scan can be compared against many outer rows at once. Starting with 8.0.18, hash join takes over for equi-joins that cannot use an index, and from 8.0.20 the block nested loop is gone entirely, with hash join used wherever it would have appeared. If an index on the join column is available, MySQL still prefers a nested loop with an index lookup.

Hash Join

Read the smaller input and build an in-memory hash table keyed on the join columns (the build phase), then stream the other input and probe the table for each row (the probe phase). The cost is roughly N + M, with no sorting and no index needed. The price is that it only works for equality conditions, it needs memory for the build side, and it cannot emit any row until the whole hash table is built.

When the build side does not fit in the memory budget, which comes from work_mem in PostgreSQL and join_buffer_size in MySQL, the join splits the data into partitions ("batches") and spills them to disk, making multiple passes. EXPLAIN ANALYZE shows this in the Hash node as a batch count above 1. This is where estimation errors hurt directly: the planner picks the build side and sizes its memory from estimated row counts, so an underestimate can silently turn an in-memory join into a disk-heavy one.

Hash join is not “always faster than nested loop”, a common over-simplification. In the docs, raising the filter from unique1 < 10 to unique1 < 100 flips the plan. With 100 outer rows, 100 separate index probes become more expensive than scanning all 10,000 rows of t2 once and probing a hash table, so the planner switches to a hash join with an estimated cost of 709.73. Same query shape, one constant changed, different algorithm.

Merge Join

Sort both inputs on the join key, then walk them in lockstep with one cursor each, emitting matches as the cursors meet. After sorting, the cost is roughly N + M, and each input is read only once. The sort can come from an explicit sort step or for free from an index scan on the join key. PostgreSQL’s merge join requires equality-style join operators.

It shines when inputs are already sorted (for example, both sides have a B-Tree on the join key), when the query also needs results ordered by the join key, or when both inputs are huge and a sort that can spill gracefully is safer than a giant hash table. The docs show a case where the planner chose merge join at an estimated 233.49 over a hash join that, once merge join was disabled for the experiment, was estimated at 344.08, about 50% more. There is a subtle runtime wrinkle: when the outer side has duplicate join keys, the inner side has to back up and rescan the matching group, and EXPLAIN ANALYZE counts those repeats as extra rows, so the inner node's actual row count can look larger than the table itself.

Choosing Between Them

Nested loop (indexed inner)Hash joinMerge join Join conditionsAnyEqualityEquality (in PostgreSQL) Rough costN × log MN + MN + M, plus sorting if needed MemorySmallBuild side must fit or spillSort memory, spills gracefully First rowImmediatelyAfter the build phaseAfter sorting, unless inputs are presorted Sweet spotSmall outer side, indexed inner sideLarge unsorted inputs, no useful indexPresorted inputs, ordered output, very large inputs

Join order and join algorithm are chosen together, and both lean on the cardinality estimates from the previous section. A good mental model: the optimizer asks, for each pair, “how many rows will each side have, is there an index on the inner key, how much memory will this take, and does anyone downstream want sorted output?” Get the first question wrong and everything else follows from a false premise.

Press enter or click to view image in full size

Predicate Pushdown: Filter Early, Move Less Data

Back to the librarian. The fast method was “narrow the catalogue first, then look up borrowing counts”. In database terms, that is predicate pushdown: apply each filter as close to the data source as the query’s semantics allow, before joins and aggregations, and where possible inside the scan or the storage layer itself. The result set does not change. What changes is how many rows flow upward through the plan, and since every join, sort, and hash table downstream pays per row, small early savings compound.

Pushing Filters Below a Join

Consider:

SELECT o.id, c.name
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.order_date >= '2026-01-01' AND c.region = 'EMEA';

Written naively, this reads as “join everything, then filter”. For an inner join, the optimizer is free to evaluate order_date while scanning orders and region while scanning customers, then join the two small results. PostgreSQL's docs describe this as one of the planner's responsibilities: attach each condition from the WHERE clause to the most appropriate node of the plan. A condition on one table lands on that table's scan, shown as Filter: or, if an index can serve it, Index Cond:. A condition that mentions both tables, such as t1.hundred < t2.hundred, cannot be evaluated until both rows are together, so it appears at the join node as a Join Filter. The planner can also derive extra filters from equalities: given a.x = b.x AND a.x = 5, it can apply x = 5 to both tables.

Press enter or click to view image in full size

Outer Joins: Where Pushdown Needs Care

Pushdown must never change the answer, and outer joins are where that rule bites. PostgreSQL’s EXPLAIN makes the distinction visible. A Join Filter comes from an outer join's ON clause, so a row that fails it can still be emitted with NULLs on the other side. A plain Filter is applied after the outer-join rules and removes rows unconditionally. Compare:

-- Condition in ON: every order survives; customer columns are NULL when the customer isn't in EMEA
SELECT o.id, c.name
FROM orders o
LEFT JOIN customers c ON c.id = o.customer_id AND c.region = 'EMEA';
-- Condition in WHERE: orders without an EMEA customer are dropped entirely
SELECT o.id, c.name
FROM orders o
LEFT JOIN customers c ON c.id = o.customer_id
WHERE c.region = 'EMEA';

Because the second query’s WHERE rejects the NULL-extended rows anyway, the optimizer can rewrite the LEFT JOIN into an INNER JOIN. That is a real optimization, not just a tidy-up: inner joins are simpler to execute, and they unlock join reordering and further pushdown (DataFusion, Spark, and ClickHouse all do this rewrite). The reverse is the trap. Pushing a WHERE filter on the nullable side below a left join, without that rewrite, would change the result.

Filters also move through aggregation selectively. A condition on a grouping column (HAVING city = 'BOSTON' after GROUP BY city) can be evaluated before grouping. A condition on an aggregate result (HAVING count(*) > 5) cannot, because the aggregate does not exist yet.

Some predicates simply cannot be pushed. Anything involving a volatile function or a subquery usually stays where it is. And a predicate that wraps the column in a function, such as WHERE extract(year from created_at) = 2025, cannot be matched against an ordinary index or min/max statistics on created_at. Rewriting it as a range (created_at >= '2025-01-01' AND created_at < '2026-01-01') is the standard fix, often called making the predicate sargable.

Pushing Filters Into the Storage Layer

The deepest form of pushdown moves the test into the scan so rows are rejected before they are ever fully read. There are three common levels.

Index conditions. A predicate that matches a B-Tree’s key becomes an Index Cond, so the scan touches only the relevant range instead of the whole table.

Index Condition Pushdown (MySQL). Take an index on (zipcode, lastname, firstname) and the query WHERE zipcode = '95054' AND lastname LIKE '%etrunia%'. The LIKE with a leading wildcard cannot narrow the index range, so without ICP the server fetches a full table row for every entry matching the zipcode and only then tests the name. With ICP (enabled by default), the storage engine tests the lastname condition using just the index entry and fetches the full row only if it passes. EXPLAIN shows Using index condition. Two details come up in interviews: for InnoDB, ICP applies only to secondary indexes (a clustered index already has the full row in the buffer, so there is no extra I/O to save), and conditions involving subqueries or stored functions cannot be pushed. The point of the optimization is avoiding those extra row fetches, each of which is a potential random page read, a cost covered in Database Series : Buffer Pool, Page Cache, and Memory Management.

Columnar files and remote sources. Column-oriented formats such as Parquet store min and max values per column per row group, in the file footer. A reader fetches this metadata first, then skips any row group whose range cannot satisfy the predicate, as in the diagram above. Two caveats matter. The gain depends on how data is laid out: if every row group’s date range spans the whole year, a narrow date filter skips nothing, which is why sorting or clustering data by commonly filtered columns pays off. And filters on non-partition columns are not helped by partition-level pruning. The storage trade-offs behind this are explained in Database Series : Row vs Columnar Storage. The same idea extends outward: engines push filters to remote databases and object stores to cut network traffic, and some hash joins build a Bloom filter from the build side and push it to the probe side’s scan. Any part of a condition the source cannot fully evaluate stays above as a residual filter, so correctness is preserved.

How Pushdown Ties Back to Estimates

Pushdown changes the numbers the cost model sees. After the filters move below the join, the optimizer estimates the filtered sizes of orders and customers, and those smaller estimates are what make a small hash-table build side or a nested loop with an index look attractive. That means a wrong filter selectivity, not just a wrong join estimate, can flip the join algorithm. In EXPLAIN ANALYZE, Rows Removed by Filter is the tell: a scan that discards millions of rows to return a few is a candidate for an index, a better-matching predicate, or storage-level pruning.

Key Takeaways

  • The optimizer turns declarative SQL into a physical plan by comparing candidate plans on estimated cost. It has three parts: cardinality estimation, a cost model, and plan enumeration.
  • PostgreSQL prices plans in abstract units anchored to a sequential page read (seq_page_cost = 1.0). A filter reduces rows emitted, not rows scanned, so it can raise the cost of a scan even while shrinking its output.
  • Join-order search explodes combinatorially, so engines use dynamic programming and fall back to heuristics (PostgreSQL’s GEQO past geqo_threshold, default 12). For inner joins, written order does not matter unless you exceed join_collapse_limit or set it to 1.
  • Statistics (row counts, distinct counts, MCV lists, equal-height histograms) drive every estimate. The independence and uniformity assumptions break on correlated or skewed data, and errors compound across joins. Cardinality errors, not cost-model errors, are the dominant cause of bad plans.
  • Debug slow queries by comparing estimated and actual rows in EXPLAIN ANALYZE, then fix in order: ANALYZE, a higher statistics target, extended statistics, and only then query rewrites or enable_* switches.
  • Nested loop suits a small outer side with an indexed inner side; hash join suits large unsorted inputs with equality conditions; merge join suits presorted inputs or ordered output. The best choice flips as selectivity changes.
  • Predicate pushdown applies filters as early as semantics allow: below joins, into scans, into index entries, and into file metadata. Outer-join semantics decide what is safe to move, and a WHERE that rejects NULLs lets a left join become an inner join.

Sources

Thank you for reading until the end. Before you go:

  • Please consider clapping and following the writer! 👏
  • Connect me on LinkedIn

--

--

Abhinav Thakur
Abhinav Thakur

Engineer @ PocketFM | Obsessed with System Design, Scaling Backends & Crafting Efficient Databases.