Sub topic 11
Making MERGE fast on large tables
This chapter covers what to check when a MERGE that works on test data gets slow on millions of rows. It assumes you can write a MERGE with WHEN MATCHED and WHEN NOT MATCHED clauses, that you have read the earlier chapters on cardinality and concurrency, and that you can read a basic EXPLAIN plan. MERGE has been available since PostgreSQL 15. The examples run on 15 or later.
How PostgreSQL executes a MERGE
PostgreSQL plans a MERGE as a join between the source and the target, then applies the matching WHEN clause to each joined row. The planner chooses the join type from your clauses:
- If you only have WHEN MATCHED clauses, it needs only rows that match, so an inner join is enough.
- If you have WHEN NOT MATCHED, it must keep source rows that find no target row, so it uses an outer join from the source.
- On PostgreSQL 17, WHEN NOT MATCHED BY SOURCE also needs target rows that find no source row, which pushes the plan toward a full join.
Because MERGE is a join, the usual join tuning applies. The planner has three main strategies:
| Join strategy | Typical situation | What it does |
|---|---|---|
| Nested loop with index scan | Small source, large target | Probes the target index once per source row |
| Hash join | Large source, large target | Builds a hash table of one side, scans the other |
| Merge join | Both sides sorted or indexed on the join key | Walks both sides in order |
A sequential scan of the target is not a bug when the source is large. If your source touches a large share of the target, reading the whole target once is cheaper than millions of random index probes. Do not force an index there.
Set up a realistic test
The following script builds a one-million-row target and a 200,000-row staging table. Half of the staging rows overlap the target. The other half are new.
CREATE TABLE inventory_big (
product_id int PRIMARY KEY,
name text NOT NULL,
quantity int NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO inventory_big (product_id, name, quantity)
SELECT g, 'item ' || g, 100
FROM generate_series(1, 1000000) AS g;
CREATE TEMP TABLE inventory_updates_big (
product_id int PRIMARY KEY,
name text NOT NULL,
delta int NOT NULL
);
INSERT INTO inventory_updates_big (product_id, name, delta)
SELECT g, 'item ' || g, CASE WHEN g % 10 = 0 THEN 0 ELSE 5 END
FROM generate_series(900001, 1100000) AS g;
ANALYZE inventory_big;
ANALYZE inventory_updates_big;Two details matter here. The staging table has a primary key on the join column, which both speeds the join and guarantees one source row per target row. The script also runs ANALYZE on the staging table. Autovacuum does not process temporary tables, so without that call the planner has no statistics for the table you just loaded and may pick a poor join.
Index the join columns
The ON condition decides how the planner can find target rows. Follow these rules:
- The target needs an index whose leading columns match the equality conditions in
ON. A primary key or unique constraint on the business key does this for you. - The
ONcondition should compare plain columns. WritingON lower(t.name) = lower(s.name)cannot use a plain index onname. Either index the expression or store a normalized column. - If the match uses several columns, such as
(tenant_id, product_id), index them as one composite index, and puttenant_idin theONclause too. - Do not add indexes to the source unless you read it many times. A staging table is usually scanned once, so an index on it helps only the join strategies that need sorted input, and the primary key you already created covers that.
Every extra index on the target has a cost. Each inserted row writes an entry to every index, and each updated row writes new entries to every index it cannot update in place. Keep only the indexes that queries need.
Read the plan
EXPLAIN ANALYZE actually executes the MERGE, so wrap it in a transaction you roll back:
BEGIN;
EXPLAIN (ANALYZE, BUFFERS)
MERGE INTO inventory_big AS t
USING inventory_updates_big AS s
ON t.product_id = s.product_id
WHEN MATCHED AND s.delta <> 0 THEN
UPDATE SET quantity = t.quantity + s.delta,
updated_at = now()
WHEN NOT MATCHED THEN
INSERT (product_id, name, quantity)
VALUES (s.product_id, s.name, s.delta);
ROLLBACK;The top node is Merge on inventory_big. Below it, check these items:
- The join node. A hash or merge join is expected for a source this size. A nested loop with a million index probes would signal a bad row estimate.
- Estimated versus actual rows. A large gap means stale or missing statistics. Run
ANALYZEand compare again. - The tuples line. For MERGE, the plan reports how many rows were inserted, updated, deleted, and skipped. Compare these with what you expect. If "skipped" is large, your source holds many rows that do no work, and you can filter them out earlier.
- Hash batches. If the hash node reports more than one batch, the hash table did not fit in
work_memand spilled to disk. - Buffers. High
readcounts mean the data came from disk, not from the cache.
Skip rows that need no change
In PostgreSQL's MVCC model, an UPDATE never edits a row in place. It writes a new row version and leaves the old one as dead space for vacuum to clean up. That happens even when the new values equal the old ones. A MERGE that updates a million unchanged rows creates a million dead rows and a lot of write-ahead log.
Add a condition so the UPDATE only runs when something changes. In the test data, rows with a delta of zero change nothing, so the example above already filters them with s.delta <> 0. When you compare full row values from a snapshot, use IS DISTINCT FROM, which treats NULL as a comparable value:
MERGE INTO inventory_big AS t
USING inventory_updates_big AS s
ON t.product_id = s.product_id
WHEN MATCHED AND t.name IS DISTINCT FROM s.name THEN
UPDATE SET name = s.name,
updated_at = now();A plain <> comparison returns NULL when either side is NULL, and a NULL condition counts as not true, so the update would be skipped even though the values differ. For a MERGE that only checks equal and not-equal on non-null columns, <> is fine.
If most updates touch only columns that have no index, PostgreSQL can often use a heap-only tuple (HOT) update, which avoids writing new index entries. HOT needs free space in the same page, so a lower fillfactor on a frequently updated table helps:
ALTER TABLE inventory_big SET (fillfactor = 90);The setting affects only pages written after the change. Existing pages keep their layout until the table is rewritten.
Process very large sources in batches
One MERGE is one statement and one transaction. Merging 50 million rows in a single statement holds row locks until commit, generates a large burst of WAL, and delays vacuum cleanup of old row versions for the whole duration. If the statement fails near the end, all the work rolls back.
Splitting the source into key ranges and committing after each range keeps each transaction small. This DO block does that. It commits inside the loop, so run it as its own top-level statement and not inside a BEGIN block:
DO $$
DECLARE
lo int;
hi int;
step constant int := 100000;
BEGIN
SELECT min(product_id), max(product_id)
INTO lo, hi
FROM inventory_updates_big;
WHILE lo <= hi LOOP
MERGE INTO inventory_big AS t
USING (
SELECT product_id, name, delta
FROM inventory_updates_big
WHERE product_id >= lo AND product_id < lo + step
) AS s
ON t.product_id = s.product_id
WHEN MATCHED AND s.delta <> 0 THEN
UPDATE SET quantity = t.quantity + s.delta,
updated_at = now()
WHEN NOT MATCHED THEN
INSERT (product_id, name, quantity)
VALUES (s.product_id, s.name, s.delta);
COMMIT;
lo := lo + step;
END LOOP;
END
$$;Batching has trade-offs. The whole job is no longer atomic. If it fails halfway, earlier batches stay committed. A batch with an additive update like quantity + delta is not safe to simply rerun, because rerunning a committed batch would add the delta twice. Design batch jobs so each range is applied exactly once. You can record the last finished range in a progress table, or mark staging rows as processed in the same transaction. Batching also assumes the source has a usable range column. Batches of tens of thousands to a few hundred thousand rows are a common starting point. Measure on your own data.
Memory, statistics, and maintenance
Several settings and routines affect large merges:
work_memcontrols how much memory a hash or sort node can use before spilling to disk. Raise it for the session that runs the MERGE, for exampleSET work_mem = '256MB';, and not globally, because every node in every concurrent query can use that much.ANALYZEafter bulk loads. Run it on the staging table before the MERGE. Run it on the target after a very large merge, as autovacuum may not reach it for a while.VACUUMafter heavy updates or deletes. Autovacuum usually handles this, but a large one-time job can outrun its thresholds. A manualVACUUM (ANALYZE) inventory_big;after the job reclaims dead rows sooner.- Triggers. Row-level triggers on the target fire for each action MERGE performs, so a trigger that does extra work per row multiplies the cost.
- Foreign keys. Each inserted or updated row checks any foreign key constraints, which means an index lookup on the referenced table. Make sure referenced and referencing columns are indexed.
A tuning checklist
The diagram summarizes the order in which to investigate a slow MERGE.
Common symptoms and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| Plan shows a nested loop with huge actual row counts | Missing statistics on a temporary or fresh staging table | Run `ANALYZE` on the staging table |
| Small source, but the plan scans the whole target | No index on the `ON` column of the target | Create an index that matches the `ON` condition |
| Hash node reports several batches | `work_mem` too small for the hash table | Raise `work_mem` for the session |
| Table grows fast after each sync | Updates rewrite rows whose values did not change | Add an `IS DISTINCT FROM` or similar condition to WHEN MATCHED |
| Statement runs for hours, then fails and rolls back | One transaction covers the whole source | Merge in key-range batches with a commit per batch |
| Inserts into the target are slow even with a good join | Too many indexes or triggers on the target | Drop unused indexes and review trigger work |
MERGE compared with ON CONFLICT for bulk loads
For a pure insert-or-update of a large batch, you can also use INSERT ... ON CONFLICT. It checks the unique index for each row as it inserts. MERGE joins the whole source to the target, so it can use a hash join and skip a per-row index probe when the source is large. MERGE also gives you conditions per action and deletes. ON CONFLICT has simpler concurrency behavior, which the earlier chapters covered. Which one is faster depends on source size, how many rows already exist, and index layout, so benchmark both on your own data and not on a rule of thumb.
Exercise
A MERGE with a source of 500 rows into a 200-million-row target takes minutes. EXPLAIN ANALYZE shows a hash join with a sequential scan of the whole target. Which change is most likely to fix it, and why?
Show answer
Create an index on the target's ON column, such as the business key, then run ANALYZE on the target. With a tiny source and an index, the planner can use a nested loop that probes the index 500 times instead of reading 200 million rows. If an index already exists and the planner still scans the target, check that the ON condition compares plain columns, so the index can be used, and that statistics are current.
Exercise
A nightly MERGE updates 30 million rows, but profiling shows that 90 percent of the matched rows already hold the same values as the source. The target table bloats after each run. What should you change in the statement?
Show answer
Add a condition to the WHEN MATCHED clause so that the UPDATE only runs when something differs, for example WHEN MATCHED AND (t.name, t.quantity) IS DISTINCT FROM (s.name, s.quantity) THEN UPDATE SET .... Each skipped row writes no new row version, so the merge produces far less WAL and far fewer dead rows for vacuum to reclaim.
Exercise
You split a 50-million-row merge into batches with a commit after each one. The job fails at batch 12. Why can simply rerunning the whole job produce wrong results when the UPDATE is quantity = t.quantity + s.delta?
Show answer
The first 11 batches are already committed. Rerunning them would add their deltas a second time. To make the job safe to rerun, record the last completed range or mark processed source rows in the same transaction as each batch, and restart from the first unprocessed range.