Sub topic 11
Making MERGE Fast on Large Tables
This chapter assumes that you know basic joins, indexes, transactions, and the MERGE syntax. It also assumes that inventory is the target table and inventory_updates is the source table from earlier examples.
MERGE compares source rows with target rows using its ON condition. On a large table, the cost usually comes from this comparison. PostgreSQL must find matching target rows, read the source rows, and then perform the required updates, inserts, or deletes.
Index the join columns
An index on the target columns used by the ON condition is usually the most important optimization. For example:
CREATE INDEX inventory_product_id_idx
ON inventory (product_id);If product_id is a primary key, PostgreSQL already created a unique index for it. Creating another index on the same column is unnecessary.
If inventory_updates is a regular table and contains many rows, index its join column too:
CREATE INDEX inventory_updates_product_id_idx
ON inventory_updates (product_id);
ANALYZE inventory;
ANALYZE inventory_updates;ANALYZE collects statistics about the table. PostgreSQL uses those statistics to estimate row counts and choose a join strategy.
| Object | Useful index or action | Why it helps |
|---|---|---|
| Target join column | Primary key or index | Finds matched target rows quickly |
| Large source table | Index on source join column | Helps source-side joins and preparation |
| Temporary source table | Index after loading data | Speeds the merge and enforces useful uniqueness |
| Both tables | `ANALYZE` | Gives the planner current row estimates |
Inspect the execution plan
Use EXPLAIN to see the plan without running the statement. Use EXPLAIN ANALYZE to run it and report actual timing and row counts.
EXPLAIN (ANALYZE, BUFFERS)
MERGE INTO inventory AS t
USING inventory_updates AS s
ON t.product_id = s.product_id
WHEN MATCHED 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);ANALYZE adds actual execution measurements. BUFFERS shows how many shared memory pages PostgreSQL read or changed.
Look for a large difference between estimated and actual rows. For example, a plan that estimates 10 source rows but reads 10 million rows may use an unsuitable join strategy. Run ANALYZE after a large load, and investigate stale or unusual data distributions if estimates remain inaccurate.
A sequential scan is not automatically a problem. If the source table is small or PostgreSQL expects to read most of a table, scanning it from beginning to end can be faster than using an index.
Keep the join searchable
Write the ON condition so PostgreSQL can compare indexed columns directly.
MERGE INTO inventory AS t
USING inventory_updates AS s
ON t.product_id = s.product_id
WHEN MATCHED THEN
UPDATE SET quantity = t.quantity + s.delta
WHEN NOT MATCHED THEN
INSERT (product_id, name, quantity)
VALUES (s.product_id, s.name, s.delta);Expressions around a join column can prevent an ordinary index from being useful:
ON lower(t.product_code) = lower(s.product_code)If this comparison is required, consider storing normalized values or creating matching expression indexes. Also avoid unnecessary casts between different data types. Make the source and target join columns use compatible types.
Prepare and batch large sources
A source query that computes aggregates or removes duplicates may be expensive. Prepare it once in a temporary table when the result will be reused or inspected:
CREATE TEMP TABLE prepared_updates AS
SELECT product_id, max(name) AS name, sum(delta) AS delta
FROM inventory_updates
GROUP BY product_id;
CREATE UNIQUE INDEX prepared_updates_product_id_idx
ON prepared_updates (product_id);
ANALYZE prepared_updates;
MERGE INTO inventory AS t
USING prepared_updates AS s
ON t.product_id = s.product_id
WHEN MATCHED THEN
UPDATE SET quantity = t.quantity + s.delta
WHEN NOT MATCHED THEN
INSERT (product_id, name, quantity)
VALUES (s.product_id, s.name, s.delta);The unique index documents and enforces the rule that the source has at most one row per product. For very large imports, process source rows in batches. Smaller transactions reduce lock duration, transaction growth, and recovery work, although batching requires a reliable way to divide the source without skipping or repeating rows.
Understand the work performed by updates
An update can rewrite a row even when the new values equal the old values. If unchanged rows do not need an update, add a condition:
MERGE INTO inventory AS t
USING prepared_updates 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 AND s.delta > 0 THEN
INSERT (product_id, name, quantity)
VALUES (s.product_id, s.name, s.delta);Fewer updates mean less table and index maintenance, less write-ahead logging, and fewer row locks.
Exercise
The target table has a primary key on product_id, but the source is a 50-million-row permanent table. What should you check first to improve a MERGE?
Show answer
Check the execution plan, confirm that the source join column has a suitable index, and run ANALYZE on both tables. Then compare estimated and actual row counts.