Hard postgresql sql

How does PostgreSQL choose between a nested loop, hash join and merge join?

The 30 second answer

A nested loop runs the inner side once per outer row, which is great when the outer side is small and the inner side has an index. A hash join builds a hash table on the smaller input and probes it with the other, which suits large unsorted equi-joins if the table fits in work_mem. A merge join walks two inputs sorted on the join key. The planner picks by estimated rows, so bad estimates mean bad joins.

Could you say this in an interview?

The three strategies, in the docs' words.

  • Nested loop: "The right relation is scanned once for every row found in the left relation. This strategy is easy to implement but can be very time consuming. (However, if the right relation can be scanned with an index scan, this can be a good strategy…)"
  • Merge join: "Each relation is sorted on the join attributes before the join starts. Then the two relations are scanned in parallel… each relation has to be scanned only once." The sort can come from an index.
  • Hash join: "the right relation is first scanned and loaded into a hash table, using its join attributes as hash keys. Next the left relation is scanned" and each row probes the table.

When each wins.

SituationUsually best
Few outer rows, index on the inner join columnNested loop
Many rows on both sides, equality join, no useful orderHash join
Both sides already sorted on the key (indexes), or the result must be sorted on itMerge join
Non-equality join (a.x < b.y)Nested loop (hash and merge need equality-style conditions)

What goes wrong. The planner chooses from estimated row counts. If it expects 10 orders for a customer and there are 500,000, it picks a nested loop that runs the inner index scan half a million times. If the hash table doesn't fit in work_mem, the hash join splits into batches on disk; EXPLAIN ANALYZE shows Batches: greater than 1.

Example. Revenue per brand for one category:

EXPLAIN (ANALYZE, BUFFERS)
SELECT b.name, sum(oi.quantity * oi.unit_price) AS revenue
FROM order_items oi
JOIN products p ON p.id = oi.product_id
JOIN brands   b ON b.id = p.brand_id
WHERE p.category_id = 3
GROUP BY b.name;

A good plan typically filters products by category_id with an index, then joins order_items through an index on order_items(product_id) if few products match, or with a hash join if many do. Missing the order_items(product_id) index forces a full scan of the largest table for every run.

Diagnosing. For testing only, the docs suggest switching off plan types (SET enable_nestloop = off) to see whether another plan is really faster. If it is, the estimates are wrong, so fix statistics or the query; don't ship planner switches in production.

Trade-offs.

  • Index foreign-key columns used in joins. PostgreSQL doesn't create those indexes automatically.
  • Raising work_mem helps hash joins and sorts but applies per operation and per connection, so a large value times many connections can exhaust memory.
  • The planner also chooses join order, and the number of tables affects how exhaustively it searches; the docs explain how explicit JOIN syntax and settings affect that.

Alternate interview scenarios

"A report joining five tables became slow after the data grew tenfold."

Look for a nested loop whose outer estimate is far below the actual rows. Refresh statistics, add extended statistics for correlated filters, and check that join columns are indexed.

"The hash join spills to disk."

Batches is above 1. Reduce the input (filter earlier, select fewer columns) or raise work_mem for that session or role only.

Sources (4)
  1. PostgreSQL docs: Planner/optimizer (join strategies)postgresql.org
  2. PostgreSQL docs: Controlling the planner with explicit JOIN clausespostgresql.org
  3. PostgreSQL docs: Query planning configuration (enable_* and work_mem related settings)postgresql.org
  4. PostgreSQL docs: Using EXPLAINpostgresql.org