comparison Data & storage
Hash join versus merge join under skew
Compare the same rows two ways: a hash join pays for a build or partition that outgrows memory; a merge join pays for missing input order. See which cost changes without treating either score as runtime.
What it means
A hash join can avoid sorting, but it needs memory for the rows it builds into a hash table. A merge join can avoid building that table, but it needs both inputs in compatible order on the join key. Neither is always cheaper: the comparison depends on which work the inputs already let the join skip.
A hash join builds its table from one input and looks up matching keys from the other, called the probe input. If the build input does not fit in memory, the join may have to work in batches. Skew matters here: repeated keys that go to the same partition can leave one partition too large to fit. A merge join instead works through the two ordered inputs, matching their keys as it goes.
Try it
Simulation: start with 100 build rows, 200 probe rows, hash memory for 80 rows, and a largest hash partition of 60 rows. Leave Required scenario evidence at provided. With Both inputs sorted set to no, hash costs 900 synthetic units and merge costs 2,494. These are scores for comparing work, not milliseconds.
Hash join versus merge join under skew
Connect memory budget, ordering and cardinality to join algorithm costs
Modeled hash cost lower.
Comparison premises
- Memory allowance80
- Largest partition60
- Inputs sortedno
- Lower proxy costhash
Each segment is a stipulated cost unit, not milliseconds. Hash uses base plus spill and skew penalties; merge uses base plus a sort penalty if needed.
Evaluated inputs
- Required scenario evidence
- provided
- Largest modeled hash partition
- 60 rows
- Build input rows
- 100 count
- Probe input rows
- 200 count
- Hash memory capacity
- 80 rows
- Both inputs sorted
- no
Synthetic cost units combine row visits and approximate sort work with explicit spill penalties; not calibrated planner or actual I/O; output cardinality held fixed.
About this model
The controls set only a local, bounded scenario. The computed branch is not a verdict about a live system. Inputs listed as not evaluated did not participate in this branch after validation.
Reset restores the original inputs. It does not change the open or closed state of help or FAQ answers.
- Change only Both inputs sorted to
yes. Merge falls to 300: the inputs now arrive in join-key order, so there is no sort charge. Hash stays at 900 because the 100-row build still exceeds the 80-row capacity. - Keep the inputs sorted and raise Hash memory capacity to 100 rows. The build now fits exactly. Hash falls to 300, tying merge; nothing changed on the merge side.
- Use Reset to return to the original six settings and the 900 versus 2,494 comparison.
All four row quantities must be whole numbers from 1 to 10,000. The largest partition cannot contain more rows than the build input. A blank or fractional count is invalid, not a reason to reuse the previous score. With valid counts but Required scenario evidence set to missing, the result is unknown: neither cost is calculated.
Where the costs come from
Both alternatives start with the same charge for visiting the input rows: 100 + 200 = 300 units. The number of output rows is held fixed. What differs is the extra work charged on top of those 300 units.
| With the starting inputs | Hash join | Merge join |
|---|---|---|
| Input visits | 300 | 300 |
| Extra work | 600 for a build larger than memory; 0 extra for the 60-row partition, which fits | 2,194 for sorting the two inputs |
| Total in synthetic units | 900 | 2,494 |
For hash, the simulation adds twice the input-visit cost when the build exceeds capacity. It adds one more input-visit cost if the largest partition also exceeds capacity. These are fixed penalties, not counts of disk operations. For merge, no charges sort work for both inputs: for each input of size n, take n × log₂(n), add the two terms, then round up once. For 100 and 200 rows that gives 2,194 extra units. The simulation has no separate setting for just one ordered input.
When one partition changes the result
Consider a smaller unsorted pair: 8 build rows and 4 probe rows, with memory for 4 rows. The common input cost is 12. The build exceeds capacity, so hash costs 12 + 24 = 36 if its largest partition fits. Merge costs 12 + 24 + 8 = 44: the last two terms are the sort work for 8 and 4 rows.
Now change only the largest partition from 4 rows to 5. The total number of rows has not increased, but that partition no longer fits. Hash takes the extra 12-unit penalty, rising from 36 to 48. Merge stays at 44 and becomes the lower score. The important distinction is between the size of the whole build, which was too large in both cases, and the size of its largest partition, which crossed the limit only in the second case. The simulation takes that partition size as an input; it does not predict it from key values.
Set both inputs sorted and the hash memory allowance to 100 rows, with the original 60-row largest partition. Both proxy costs are 300 units. The tie means neither extra charge applies in this case; it is not a benchmark showing equal execution time. Keep the two cost bars on the same unit scale.
In practice
When reading an existing PostgreSQL plan, look at what feeds the join, not just the join's name. For a merge join, does an index scan supply the needed order, or is there a sort? For a hash join, how many rows are estimated on the build side? If execution details are available, the hash node's batch count helps distinguish a single batch from work split across batches. A synthetic spill penalty is not evidence that your query used disk.
Treat estimated row counts as estimates, especially when a few values occur far more often than others. In PostgreSQL 18, planner statistics remain approximate after ANALYZE. A higher statistics target may improve estimates for an irregular column distribution; it does not guarantee a particular join plan.
The useful rule is to identify the work that differs while holding the inputs constant. Existing order can remove a sort; sufficient memory can remove a hash penalty. If you do not know the input order or have evidence about batching, those are the next details to look for in the plan. The lower score in this comparison is not a runtime prediction or a reason to change a database setting.
Frequently asked questions
Editorial questions based on the listed sources and explicitly labeled local examples.
Does merge join need sorted inputs?
Yes. A merge join consumes inputs in compatible join-key order; an engine may use existing index order or perform sorting. Cost also depends on the actual plan.
Can a hash join spill?
Yes, when its working set exceeds memory.
Does skew affect partitions?
Repeated keys can concentrate work if the hash partition function maps equal keys to the same partition. The lab accepts the largest partition size as supplied evidence and adds a spill cost when it exceeds memory; it does not calculate PostgreSQL's partition distribution or actual batching.
Does lower proxy cost prove speed?
No. This proxy assigns synthetic charges to row visits, spill, skew and sorting. It does not measure memory allocation, caching, batching, output costs or elapsed time. Compare actual plans only under the same permitted workload and measurement conditions.
Sources & model boundaries
Primary references used for this explanation. The interactive example is an educational model, not a live check.
- PostgreSQL Using EXPLAIN
Join plans; hash batches. Merge joins need ordered join-key inputs; index scans or sorting can provide order. Multi-batch hash work can involve disk space, while planner costs and measurements remain distinct.
Checked .
- PostgreSQL statistics used by planner
§14.2.1. PostgreSQL planner statistics remain approximate after ANALYZE. For irregular column distributions, a higher statistics target may improve estimates; it does not guarantee a particular join plan.
Checked .