↑↓ select ↵ open ⌫ change scope Open full search

PG.CENTER connects PostgreSQL documentation, reference, and ecosystem knowledge. Maintained by Pigsty.

Wiki / Plan Nodes / Modification

ModifyTable

ModifyTable

Performs the data-modification operation selected by the plan and produces RETURNING rows when requested.

Reading PostgreSQL 18.6.

Description

Performs the data-modification operation selected by the plan and produces RETURNING rows when requested.

Core node tag
T_ModifyTable
Structured EXPLAIN Node Type
ModifyTable
Inputs
Modification input plan or plans
Output
RETURNING tuples when requested
Executor initializer
ExecInitModifyTable
Memory mechanism
unclassified

EXPLAIN names and attributes

Structured formats use the Node Type above. Text-format spellings can also include operation, strategy, join type, scan direction or aggregation-stage attributes.

Text names recorded by this source: Insert, Update, Delete, Merge.

Parallel-aware and parallel-safe are different plan properties. A node running inside a parallel worker is not necessarily a parallel-aware node.

Memory and temporary storage

This extraction does not assign a universal memory limit or spill policy to this node. Inspect the same-build implementation and its expressions or provider.

If the FDW supports batching, and batching is requested, accumulate rows and insert them in batches. Otherwise use the per-row inserts.

Initialize the batch slots. We don't know how many slots will be needed, so we initialize them as the batch grows, and we keep them across batches. To mitigate an inefficiency in how resource owner handles objects with many references (as with many slots all referencing the same tuple descriptor) we copy the appropriate tuple descriptor for each slot.

Parallel execution and instrumentation

The source callbacks below can coordinate execution or collect worker instrumentation. Their presence is not a blanket claim that this node supports a shared parallel scan or shared state.

Callbacks in this build: none extracted from this node implementation.

Same-version manual discussion

Merge join requires its input data to be sorted on the join keys. In this example each input is sorted by using an index scan to visit the rows in the correct order; but a sequential scan and sort could also be used. (Sequential-scan-and-sort frequently beats an index scan for sorting many rows, because of the nonsequential disk access required by the index scan.)

One way to look at variant plans is to force the planner to disregard whatever strategy it thought was the cheapest, using the enable/disable flags described in Section 19.7.1 . (This is a crude tool, but useful. See also Section 14.3 .) For example, if we're unconvinced that merge join is the best join type for the previous example, we could try

which shows that the planner thinks that hash join would be nearly 50% more expensive than merge join for this case. Of course, the next question is whether it's right about that. We can investigate that using EXPLAIN ANALYZE , as discussed below .

As seen in this example, when the query is an INSERT , UPDATE , DELETE , or MERGE command, the actual work of applying the table changes is done by a top-level Insert, Update, Delete, or Merge plan node. The plan nodes underneath this node perform the work of locating the old rows and/or computing the new data. So above, we see the same sort of bitmap table scan we've seen already, and its output is fed to an Update node that stores the updated rows. It's worth noting that although the data-modifying node can take a considerable amount of run time (here, it's consuming the lion's share of the time), the planner does not currently add anything to the cost estimates to account for that work. That's because the work to be done is the same for every correct query plan, so it doesn't affect planning decisions.

When an UPDATE , DELETE , or MERGE command affects a partitioned table or inheritance hierarchy, the output might look like this:

In this example the Update node needs to consider three child tables, but not the originally-mentioned partitioned table (since that never stores any data). So there are three input scanning subplans, one per table. For clarity, the Update node is annotated to show the specific target tables that will be updated, in the same order as the corresponding subplans.

Examples from this manual build

Example copied from the PostgreSQL 18.6 manual; it was not executed for this collection.

Another possible type of join is a merge join, illustrated here:

EXPLAIN SELECT *
FROM tenk1 t1, onek t2
WHERE t1.unique1 < 100 AND t1.unique2 = t2.unique2;

                                        QUERY PLAN
------------------------------------------------------------------------------------------
 Merge Join  (cost=0.56..233.49 rows=10 width=488)
   Merge Cond: (t1.unique2 = t2.unique2)
   ->  Index Scan using tenk1_unique2 on tenk1 t1  (cost=0.29..643.28 rows=100 width=244)
         Filter: (unique1 < 100)
   ->  Index Scan using onek_unique2 on onek t2  (cost=0.28..166.28 rows=1000 width=244)

Example copied from the PostgreSQL 18.6 manual; it was not executed for this collection.

Keep in mind that because EXPLAIN ANALYZE actually runs the query, any side-effects will happen as usual, even though whatever results the query might output are discarded in favor of printing the EXPLAIN data. If you want to analyze a data-modifying query without changing your tables, you can roll the command back afterwards, for example:

BEGIN;

EXPLAIN ANALYZE UPDATE tenk1 SET hundred = hundred + 1 WHERE unique1 < 100;

                                                           QUERY PLAN
--------------------------------------------------------------------------------------------------------------------------------
 Update on tenk1  (cost=5.06..225.23 rows=0 width=0) (actual time=1.634..1.635 rows=0.00 loops=1)
   ->  Bitmap Heap Scan on tenk1  (cost=5.06..225.23 rows=100 width=10) (actual time=0.065..0.141 rows=100.00 loops=1)
         Recheck Cond: (unique1 < 100)
         Heap Blocks: exact=90
         Buffers: shared hit=4 read=2
         ->  Bitmap Index Scan on tenk1_unique1  (cost=0.00..5.04 rows=100 width=0) (actual time=0.031..0.031 rows=100.00 loops=1)
               Index Cond: (unique1 < 100)
               Index Searches: 1
               Buffers: shared read=2
 Planning Time: 0.151 ms
 Execution Time: 1.856 ms

ROLLBACK;

Executor implementation notes

NOTES The ModifyTable node receives input from its outerPlan, which is the data to insert for INSERT cases, the changed columns' new values plus row-locating info for UPDATE and MERGE cases, or just the row-locating info for DELETE cases.

The relation to modify can be an ordinary table, a foreign table, or a view. If it's a view, either it has sufficient INSTEAD OF triggers or this node executes only MERGE ... DO NOTHING. If the original MERGE targeted a view not in one of those two categories, earlier processing already pointed the ModifyTable result relation to an underlying relation of that other view. This node does process ri_WithCheckOptions, which may have expressions from those other, automatically updatable views.

MERGE runs a join between the source relation and the target table. If any WHEN NOT MATCHED [BY TARGET] clauses are present, then the join is an outer join that might output tuples without a matching target tuple. In this case, any unmatched target tuples will have NULL row-locating info, and only INSERT can be run. But for matched target tuples, the row-locating info is used to determine the tuple to UPDATE or DELETE. When all clauses are WHEN MATCHED or WHEN NOT MATCHED BY SOURCE, all tuples produced by the join will include a matching target tuple, so all tuples contain row-locating info.

If the query specifies RETURNING, then the ModifyTable returns a RETURNING tuple after completing each row insert, update, or delete. It must be called again to continue the operation. Without RETURNING, we just loop within the node until all the work is done, then return NULL. This avoids useless call/return overhead.

Context struct for a ModifyTable operation, containing basic execution state and some output variables populated by ExecUpdateAct() and ExecDeleteAct() to report the result of their actions to callers.

EXPLAIN identity in core source

case T_ModifyTable:
			sname = "ModifyTable";
			switch (((ModifyTable *) plan)->operation)
			{
				case CMD_INSERT:
					pname = operation = "Insert";
					break;
				case CMD_UPDATE:
					pname = operation = "Update";
					break;
				case CMD_DELETE:
					pname = operation = "Delete";
					break;
				case CMD_MERGE:
					pname = operation = "Merge";
					break;
				default:
					pname = "???";
					break;
			}
			break;

EXPLAIN labels in this source build

Text-format labelStructured node identity
InsertModifyTable
UpdateModifyTable
DeleteModifyTable
MergeModifyTable

Related entries

Documentation and source

Source build
Version
18.6
Build
PostgreSQL 18.6 source archive
Source fingerprint
555610c24d53e4316da5b7d3fc25c279d96856d5e0e23ee308c328c5fa881d9f

Compare versions

PostgreSQL 14 → 15: changed.

--- PostgreSQL 14
+++ PostgreSQL 15
@@ -8,6 +8,7 @@
   "text_names": [
     "Insert",
     "Update",
-    "Delete"
+    "Delete",
+    "Merge"
   ]
 }

Compares recorded interfaces and attributes. Source fingerprints and build metadata are excluded; an absent sample is not proof of the introduction or removal release.

Export JSON · Back to Plan Nodes · Recorded in PostgreSQL 10 through 20; the first sample is not necessarily its introduction.