0%
PostgreSQL Deep Dive: MVCC, Vacuum, Plans, and Replication
Architecture and Storage
MVCC and Vacuum
Concurrency and Schema
Joins and Query Tuning
PostgreSQL implements joins with three algorithms: nested loop, hash join and merge join. Each is the best choice in some situations and a disaster in others, and the planner chooses among them from row estimates and costs. Understanding how each works, what it needs and how it fails lets you read join plans, predict which method will win and design indexes and queries so the right method is cheap. This section covers the nested loop, the simplest and most frequently misused of the three.
How a nested loop works
A nested loop join reads rows from its outer child one at a time and, for each, runs its inner child to find matching rows. In its naive form the inner child is a full scan of the inner table, making the cost proportional to the product of the two sizes, which is only acceptable for tiny inputs. In practice the inner child is almost always an index scan parameterized by the outer row, such as an index lookup on orders where customer_id equals the current customer, making the cost proportional to the outer rows times the cost of one lookup.
When nested loops win
A nested loop is ideal when the outer side is small and the inner side has an index on the join key. A query that finds a single user and joins their orders, items and payments through foreign key indexes does a handful of index lookups and finishes in milliseconds, far faster than building hash tables over large tables. Nested loops also start returning rows immediately, which makes them the natural choice under LIMIT, and they are the only join method that can handle arbitrary join conditions such as inequalities or function calls without equality.
When nested loops fail
The cost of a nested loop grows linearly with the number of outer rows. If the planner expects 10 outer rows and gets 100000, the inner lookup runs 100000 times, and even at a tenth of a millisecond each, that is 10 seconds of random index and heap access. This is the plan disaster from the previous lessons. Nested loops also fail when the inner side has no useful index, so each loop scans the whole inner relation, a pattern visible as a Seq Scan or a Materialize on the inner side with loops equal to the outer rows.
Materialize and Memoize on the inner side
When the inner side has no parameterized index path, the planner may put a Materialize node over it, which stores the inner result in memory the first time and rescans the stored copy on each loop, avoiding repeated work but still comparing every pair. Since version 14, the planner may place a Memoize node over a parameterized inner side, caching the result for each distinct parameter value. If many outer rows share a join key, for example many orders for the same product, Memoize turns repeated lookups into cache hits, and the plan reports hits and misses.
Join conditions beyond equality
Nested loops handle any join condition, including ranges such as event time between a session start and end, geometric conditions such as a point within a polygon, and function based matches. For these, the inner side can still use an index if the condition is indexable with the outer value as a parameter, such as a GiST index on the polygon. Without an index, a nested loop with a non equality condition compares every pair, which scales quadratically and must be avoided for large inputs, often by restructuring the query or adding an index of the right type.
Lateral joins
A LATERAL subquery in FROM can reference columns of tables that come before it, which makes it a nested loop by construction: for each outer row, run the subquery with that row values. This is the idiomatic way to express queries such as the three most recent orders for each customer, with an inner subquery using ORDER BY and LIMIT 3 that an index on customer_id and created_at serves in a few page reads per customer. For small outer sides, lateral joins with LIMIT are much faster than window functions over the whole table.
Indexes that nested loops need
Every foreign key that is used for joins from the referenced side needs an index on the referencing column, since a nested loop driven from the parent table looks up children by that column. Postgres does not create these indexes automatically. Composite indexes that start with the join key and continue with a filter or sort column, such as order_id then status, let the inner lookup apply additional conditions in the index rather than as filters, reducing heap visits per loop. Covering indexes can make each inner lookup an index only scan.
Reading nested loop plans
In a plan, the first child of a Nested Loop is the outer side and the second is the inner. The inner side shows loops equal to the number of outer rows, with times and rows per loop. The key checks are whether the outer estimate is close to the actual, whether the inner side uses an index with the join key in Index Cond, and whether the inner rows per loop are small. A Join Filter on the nested loop means part of the condition is checked after the inner lookup, which can hide many wasted inner rows.
Parameterized paths
The planner represents an inner side that depends on the outer row as a parameterized path, a scan whose condition uses a value supplied by the outer side. When it considers a nested loop, it looks for parameterized index scans on the inner relation whose index columns match the join condition. If none exist, the only options are a full scan per loop, a Materialize, or a different join method. Adding an index on the join column of the inner relation is often what makes a parameterized path, and therefore a cheap nested loop, possible at all.
Nested loops and random I/O
Each inner lookup in a nested loop typically touches index pages and a heap page that may be anywhere in the table. When the data is cached, each lookup costs microseconds. When it is not, each heap fetch can be a random read from disk. This is why the same nested loop can run in 20 milliseconds on a warm system and 20 seconds after a restart or on a replica with a cold cache. The planner models this with random_page_cost and effective_cache_size, and a plan that relies on many lookups is sensitive to both.
Semi and anti joins
EXISTS and NOT EXISTS subqueries become semi joins and anti joins, which a nested loop executes efficiently: for a semi join, the inner lookup stops at the first match, and for an anti join, the outer row is returned only if the lookup finds nothing. With an index on the inner join key, each check is a single index descent. Plans label these as Nested Loop Semi Join and Nested Loop Anti Join, and reading their loops and rows follows the same rules as ordinary nested loops.
Batching lookups in the application
Applications sometimes implement a nested loop themselves by running one query per item in a list, which is the N plus one pattern. The database cannot optimize across those separate queries, and each one pays network round trip and parsing costs. Sending one query with all the keys, such as WHERE id equals ANY of an array, or a join, lets the database choose between a nested loop with an index and a hash join, and removes the per item overhead entirely.
Nested loops under LIMIT
When a query has ORDER BY and a small LIMIT, the planner may pick a nested loop driven by an ordered index scan, expecting to find enough matches after reading a few outer rows. If matches are rare, the loop reads far more outer rows than expected before the limit is satisfied. This shows in the plan as an outer side with actual rows much larger than estimated, and is fixed by better statistics, a composite index covering both the filter and the order, or a rewrite.
A nested loop runs its inner side once per outer row, so it is ideal when the outer side is small and the inner side has an index on the join key, and terrible when the outer side is underestimated. Index foreign keys, use LATERAL for per row top N, and check loops on the inner side.