1 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>MERGE</title><link rel="stylesheet" type="text/css" href="stylesheet.css" /><link rev="made" href="pgsql-docs@lists.postgresql.org" /><meta name="generator" content="DocBook XSL Stylesheets Vsnapshot" /><link rel="prev" href="sql-lock.html" title="LOCK" /><link rel="next" href="sql-move.html" title="MOVE" /></head><body id="docContent" class="container-fluid col-10"><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="5" align="center">MERGE</th></tr><tr><td width="10%" align="left"><a accesskey="p" href="sql-lock.html" title="LOCK">Prev</a> </td><td width="10%" align="left"><a accesskey="u" href="sql-commands.html" title="SQL Commands">Up</a></td><th width="60%" align="center">SQL Commands</th><td width="10%" align="right"><a accesskey="h" href="index.html" title="PostgreSQL 18.0 Documentation">Home</a></td><td width="10%" align="right"> <a accesskey="n" href="sql-move.html" title="MOVE">Next</a></td></tr></table><hr /></div><div class="refentry" id="SQL-MERGE"><div class="titlepage"></div><a id="id-1.9.3.156.1" class="indexterm"></a><div class="refnamediv"><h2><span class="refentrytitle">MERGE</span></h2><p>MERGE — conditionally insert, update, or delete rows of a table</p></div><div class="refsynopsisdiv"><h2>Synopsis</h2><pre class="synopsis">
3 [ WITH <em class="replaceable"><code>with_query</code></em> [, ...] ]
4 MERGE INTO [ ONLY ] <em class="replaceable"><code>target_table_name</code></em> [ * ] [ [ AS ] <em class="replaceable"><code>target_alias</code></em> ]
5 USING <em class="replaceable"><code>data_source</code></em> ON <em class="replaceable"><code>join_condition</code></em>
6 <em class="replaceable"><code>when_clause</code></em> [...]
7 [ RETURNING [ WITH ( { OLD | NEW } AS <em class="replaceable"><code>output_alias</code></em> [, ...] ) ]
8 { * | <em class="replaceable"><code>output_expression</code></em> [ [ AS ] <em class="replaceable"><code>output_name</code></em> ] } [, ...] ]
10 <span class="phrase">where <em class="replaceable"><code>data_source</code></em> is:</span>
12 { [ ONLY ] <em class="replaceable"><code>source_table_name</code></em> [ * ] | ( <em class="replaceable"><code>source_query</code></em> ) } [ [ AS ] <em class="replaceable"><code>source_alias</code></em> ]
14 <span class="phrase">and <em class="replaceable"><code>when_clause</code></em> is:</span>
16 { WHEN MATCHED [ AND <em class="replaceable"><code>condition</code></em> ] THEN { <em class="replaceable"><code>merge_update</code></em> | <em class="replaceable"><code>merge_delete</code></em> | DO NOTHING } |
17 WHEN NOT MATCHED BY SOURCE [ AND <em class="replaceable"><code>condition</code></em> ] THEN { <em class="replaceable"><code>merge_update</code></em> | <em class="replaceable"><code>merge_delete</code></em> | DO NOTHING } |
18 WHEN NOT MATCHED [ BY TARGET ] [ AND <em class="replaceable"><code>condition</code></em> ] THEN { <em class="replaceable"><code>merge_insert</code></em> | DO NOTHING } }
20 <span class="phrase">and <em class="replaceable"><code>merge_insert</code></em> is:</span>
22 INSERT [( <em class="replaceable"><code>column_name</code></em> [, ...] )]
23 [ OVERRIDING { SYSTEM | USER } VALUE ]
24 { VALUES ( { <em class="replaceable"><code>expression</code></em> | DEFAULT } [, ...] ) | DEFAULT VALUES }
26 <span class="phrase">and <em class="replaceable"><code>merge_update</code></em> is:</span>
28 UPDATE SET { <em class="replaceable"><code>column_name</code></em> = { <em class="replaceable"><code>expression</code></em> | DEFAULT } |
29 ( <em class="replaceable"><code>column_name</code></em> [, ...] ) = [ ROW ] ( { <em class="replaceable"><code>expression</code></em> | DEFAULT } [, ...] ) |
30 ( <em class="replaceable"><code>column_name</code></em> [, ...] ) = ( <em class="replaceable"><code>sub-SELECT</code></em> )
33 <span class="phrase">and <em class="replaceable"><code>merge_delete</code></em> is:</span>
36 </pre></div><div class="refsect1" id="id-1.9.3.156.5"><h2>Description</h2><p>
37 <code class="command">MERGE</code> performs actions that modify rows in the
38 target table identified as <em class="replaceable"><code>target_table_name</code></em>,
39 using the <em class="replaceable"><code>data_source</code></em>.
40 <code class="command">MERGE</code> provides a single <acronym class="acronym">SQL</acronym>
41 statement that can conditionally <code class="command">INSERT</code>,
42 <code class="command">UPDATE</code> or <code class="command">DELETE</code> rows, a task
43 that would otherwise require multiple procedural language statements.
45 First, the <code class="command">MERGE</code> command performs a join
46 from <em class="replaceable"><code>data_source</code></em> to
48 producing zero or more candidate change rows. For each candidate change
49 row, the status of <code class="literal">MATCHED</code>,
50 <code class="literal">NOT MATCHED BY SOURCE</code>,
51 or <code class="literal">NOT MATCHED [BY TARGET]</code>
52 is set just once, after which <code class="literal">WHEN</code> clauses are evaluated
53 in the order specified. For each candidate change row, the first clause to
54 evaluate as true is executed. No more than one <code class="literal">WHEN</code>
55 clause is executed for any candidate change row.
57 <code class="command">MERGE</code> actions have the same effect as
58 regular <code class="command">UPDATE</code>, <code class="command">INSERT</code>, or
59 <code class="command">DELETE</code> commands of the same names. The syntax of
60 those commands is different, notably that there is no <code class="literal">WHERE</code>
61 clause and no table name is specified. All actions refer to the
63 though modifications to other tables may be made using triggers.
65 When <code class="literal">DO NOTHING</code> is specified, the source row is
66 skipped. Since actions are evaluated in their specified order, <code class="literal">DO
67 NOTHING</code> can be handy to skip non-interesting source rows before
68 more fine-grained handling.
70 The optional <code class="literal">RETURNING</code> clause causes <code class="command">MERGE</code>
71 to compute and return value(s) based on each row inserted, updated, or
72 deleted. Any expression using the source or target table's columns, or
73 the <a class="link" href="functions-merge-support.html#MERGE-ACTION"><code class="function">merge_action()</code></a>
74 function can be computed. By default, when an <code class="command">INSERT</code> or
75 <code class="command">UPDATE</code> action is performed, the new values of the target
76 table's columns are used, and when a <code class="command">DELETE</code> is performed,
77 the old values of the target table's columns are used, but it is also
78 possible to explicitly request old and new values. The syntax of the
79 <code class="literal">RETURNING</code> list is identical to that of the output list
80 of <code class="command">SELECT</code>.
82 There is no separate <code class="literal">MERGE</code> privilege.
83 If you specify an update action, you must have the
84 <code class="literal">UPDATE</code> privilege on the column(s)
86 that are referred to in the <code class="literal">SET</code> clause.
87 If you specify an insert action, you must have the <code class="literal">INSERT</code>
88 privilege on the target table.
89 If you specify a delete action, you must have the <code class="literal">DELETE</code>
90 privilege on the target table.
91 If you specify a <code class="literal">DO NOTHING</code> action, you must have
92 the <code class="literal">SELECT</code> privilege on at least one column
94 You will also need <code class="literal">SELECT</code> privilege on any column(s)
95 of the <em class="replaceable"><code>data_source</code></em> and
96 of the target table referred to
97 in any <code class="literal">condition</code> (including <code class="literal">join_condition</code>)
98 or <code class="literal">expression</code>.
99 Privileges are tested once at statement start and are checked
100 whether or not particular <code class="literal">WHEN</code> clauses are executed.
102 <code class="command">MERGE</code> is not supported if the
104 materialized view, foreign table, or if it has any
106 </p></div><div class="refsect1" id="id-1.9.3.156.6"><h2>Parameters</h2><div class="variablelist"><dl class="variablelist"><dt><span class="term"><em class="replaceable"><code>with_query</code></em></span></dt><dd><p>
107 The <code class="literal">WITH</code> clause allows you to specify one or more
108 subqueries that can be referenced by name in the <code class="command">MERGE</code>
109 query. See <a class="xref" href="queries-with.html" title="7.8. WITH Queries (Common Table Expressions)">Section 7.8</a> and <a class="xref" href="sql-select.html" title="SELECT"><span class="refentrytitle">SELECT</span></a>
110 for details. Note that <code class="literal">WITH RECURSIVE</code> is not supported
111 by <code class="command">MERGE</code>.
112 </p></dd><dt><span class="term"><em class="replaceable"><code>target_table_name</code></em></span></dt><dd><p>
113 The name (optionally schema-qualified) of the target table or view to
114 merge into. If <code class="literal">ONLY</code> is specified before a table
115 name, matching rows are updated or deleted in the named table only. If
116 <code class="literal">ONLY</code> is not specified, matching rows are also updated
117 or deleted in any tables inheriting from the named table. Optionally,
118 <code class="literal">*</code> can be specified after the table name to explicitly
119 indicate that descendant tables are included. The
120 <code class="literal">ONLY</code> keyword and <code class="literal">*</code> option do not
121 affect insert actions, which always insert into the named table only.
123 If <em class="replaceable"><code>target_table_name</code></em> is a
124 view, it must either be automatically updatable with no
125 <code class="literal">INSTEAD OF</code> triggers, or it must have
126 <code class="literal">INSTEAD OF</code> triggers for every type of action
127 (<code class="literal">INSERT</code>, <code class="literal">UPDATE</code>, and
128 <code class="literal">DELETE</code>) specified in the <code class="literal">WHEN</code>
129 clauses. Views with rules are not supported.
130 </p></dd><dt><span class="term"><em class="replaceable"><code>target_alias</code></em></span></dt><dd><p>
131 A substitute name for the target table. When an alias is
132 provided, it completely hides the actual name of the table. For
133 example, given <code class="literal">MERGE INTO foo AS f</code>, the remainder of the
134 <code class="command">MERGE</code> statement must refer to this table as
135 <code class="literal">f</code> not <code class="literal">foo</code>.
136 </p></dd><dt><span class="term"><em class="replaceable"><code>source_table_name</code></em></span></dt><dd><p>
137 The name (optionally schema-qualified) of the source table, view, or
138 transition table. If <code class="literal">ONLY</code> is specified before the
139 table name, matching rows are included from the named table only. If
140 <code class="literal">ONLY</code> is not specified, matching rows are also included
141 from any tables inheriting from the named table. Optionally,
142 <code class="literal">*</code> can be specified after the table name to explicitly
143 indicate that descendant tables are included.
144 </p></dd><dt><span class="term"><em class="replaceable"><code>source_query</code></em></span></dt><dd><p>
145 A query (<code class="command">SELECT</code> statement or <code class="command">VALUES</code>
146 statement) that supplies the rows to be merged into the
148 Refer to the <a class="xref" href="sql-select.html" title="SELECT"><span class="refentrytitle">SELECT</span></a>
149 statement or <a class="xref" href="sql-values.html" title="VALUES"><span class="refentrytitle">VALUES</span></a>
150 statement for a description of the syntax.
151 </p></dd><dt><span class="term"><em class="replaceable"><code>source_alias</code></em></span></dt><dd><p>
152 A substitute name for the data source. When an alias is
153 provided, it completely hides the actual name of the table or the fact
154 that a query was issued.
155 </p></dd><dt><span class="term"><em class="replaceable"><code>join_condition</code></em></span></dt><dd><p>
156 <em class="replaceable"><code>join_condition</code></em> is
157 an expression resulting in a value of type
158 <code class="type">boolean</code> (similar to a <code class="literal">WHERE</code>
159 clause) that specifies which rows in the
160 <em class="replaceable"><code>data_source</code></em>
161 match rows in the target table.
162 </p><div class="warning"><h3 class="title">Warning</h3><p>
163 Only columns from the target table
164 that attempt to match <em class="replaceable"><code>data_source</code></em>
165 rows should appear in <em class="replaceable"><code>join_condition</code></em>.
166 <em class="replaceable"><code>join_condition</code></em> subexpressions that
167 only reference the target table's
168 columns can affect which action is taken, often in surprising ways.
170 If both <code class="literal">WHEN NOT MATCHED BY SOURCE</code> and
171 <code class="literal">WHEN NOT MATCHED [BY TARGET]</code> clauses are specified,
172 the <code class="command">MERGE</code> command will perform a <code class="literal">FULL</code>
173 join between <em class="replaceable"><code>data_source</code></em>
174 and the target table. For this to work, at least one
175 <em class="replaceable"><code>join_condition</code></em> subexpression
176 must use an operator that can support a hash join, or all of the
177 subexpressions must use operators that can support a merge join.
178 </p></div></dd><dt><span class="term"><em class="replaceable"><code>when_clause</code></em></span></dt><dd><p>
179 At least one <code class="literal">WHEN</code> clause is required.
181 The <code class="literal">WHEN</code> clause may specify <code class="literal">WHEN MATCHED</code>,
182 <code class="literal">WHEN NOT MATCHED BY SOURCE</code>, or
183 <code class="literal">WHEN NOT MATCHED [BY TARGET]</code>.
184 Note that the <acronym class="acronym">SQL</acronym> standard only defines
185 <code class="literal">WHEN MATCHED</code> and <code class="literal">WHEN NOT MATCHED</code>
186 (which is defined to mean no matching target row).
187 <code class="literal">WHEN NOT MATCHED BY SOURCE</code> is an extension to the
188 <acronym class="acronym">SQL</acronym> standard, as is the option to append
189 <code class="literal">BY TARGET</code> to <code class="literal">WHEN NOT MATCHED</code>, to
190 make its meaning more explicit.
192 If the <code class="literal">WHEN</code> clause specifies <code class="literal">WHEN MATCHED</code>
193 and the candidate change row matches a row in the
194 <em class="replaceable"><code>data_source</code></em> to a row in the
195 target table, the <code class="literal">WHEN</code> clause is executed if the
196 <em class="replaceable"><code>condition</code></em> is
197 absent or it evaluates to <code class="literal">true</code>.
199 If the <code class="literal">WHEN</code> clause specifies
200 <code class="literal">WHEN NOT MATCHED BY SOURCE</code> and the candidate change
201 row represents a row in the target table that does not match a row in the
202 <em class="replaceable"><code>data_source</code></em>, the
203 <code class="literal">WHEN</code> clause is executed if the
204 <em class="replaceable"><code>condition</code></em> is
205 absent or it evaluates to <code class="literal">true</code>.
207 If the <code class="literal">WHEN</code> clause specifies
208 <code class="literal">WHEN NOT MATCHED [BY TARGET]</code> and the candidate change
209 row represents a row in the
210 <em class="replaceable"><code>data_source</code></em> that does not
211 match a row in the target table,
212 the <code class="literal">WHEN</code> clause is executed if the
213 <em class="replaceable"><code>condition</code></em> is
214 absent or it evaluates to <code class="literal">true</code>.
215 </p></dd><dt><span class="term"><em class="replaceable"><code>condition</code></em></span></dt><dd><p>
216 An expression that returns a value of type <code class="type">boolean</code>.
217 If this expression for a <code class="literal">WHEN</code> clause
218 returns <code class="literal">true</code>, then the action for that clause
219 is executed for that row.
221 A condition on a <code class="literal">WHEN MATCHED</code> clause can refer to columns
222 in both the source and the target relations. A condition on a
223 <code class="literal">WHEN NOT MATCHED BY SOURCE</code> clause can only refer to
224 columns from the target relation, since by definition there is no matching
225 source row. A condition on a <code class="literal">WHEN NOT MATCHED [BY TARGET]</code>
226 clause can only refer to columns from
227 the source relation, since by definition there is no matching target row.
228 Only the system attributes from the target table are accessible.
229 </p></dd><dt><span class="term"><em class="replaceable"><code>merge_insert</code></em></span></dt><dd><p>
230 The specification of an <code class="literal">INSERT</code> action that inserts
231 one row into the target table.
232 The target column names can be listed in any order. If no list of
233 column names is given at all, the default is all the columns of the
234 table in their declared order.
236 Each column not present in the explicit or implicit column list will be
237 filled with a default value, either its declared default value
238 or null if there is none.
241 is a partitioned table, each row is routed to the appropriate partition
242 and inserted into it.
244 is a partition, an error will occur if any input row violates the
245 partition constraint.
247 Column names may not be specified more than once.
248 <code class="command">INSERT</code> actions cannot contain sub-selects.
250 Only one <code class="literal">VALUES</code> clause can be specified.
251 The <code class="literal">VALUES</code> clause can only refer to columns from
252 the source relation, since by definition there is no matching target row.
253 </p></dd><dt><span class="term"><em class="replaceable"><code>merge_update</code></em></span></dt><dd><p>
254 The specification of an <code class="literal">UPDATE</code> action that updates
255 the current row of the target table.
256 Column names may not be specified more than once.
258 Neither a table name nor a <code class="literal">WHERE</code> clause are allowed.
259 </p></dd><dt><span class="term"><em class="replaceable"><code>merge_delete</code></em></span></dt><dd><p>
260 Specifies a <code class="literal">DELETE</code> action that deletes the current row
262 Do not include the table name or any other clauses, as you would normally
263 do with a <a class="xref" href="sql-delete.html" title="DELETE"><span class="refentrytitle">DELETE</span></a> command.
264 </p></dd><dt><span class="term"><em class="replaceable"><code>column_name</code></em></span></dt><dd><p>
265 The name of a column in the target table. The column name
266 can be qualified with a subfield name or array subscript, if
267 needed. (Inserting into only some fields of a composite
268 column leaves the other fields null.)
269 Do not include the table's name in the specification
271 </p></dd><dt><span class="term"><code class="literal">OVERRIDING SYSTEM VALUE</code></span></dt><dd><p>
272 Without this clause, it is an error to specify an explicit value
273 (other than <code class="literal">DEFAULT</code>) for an identity column defined
274 as <code class="literal">GENERATED ALWAYS</code>. This clause overrides that
276 </p></dd><dt><span class="term"><code class="literal">OVERRIDING USER VALUE</code></span></dt><dd><p>
277 If this clause is specified, then any values supplied for identity
278 columns defined as <code class="literal">GENERATED BY DEFAULT</code> are ignored
279 and the default sequence-generated values are applied.
280 </p></dd><dt><span class="term"><code class="literal">DEFAULT VALUES</code></span></dt><dd><p>
281 All columns will be filled with their default values.
282 (An <code class="literal">OVERRIDING</code> clause is not permitted in this
284 </p></dd><dt><span class="term"><em class="replaceable"><code>expression</code></em></span></dt><dd><p>
285 An expression to assign to the column. If used in a
286 <code class="literal">WHEN MATCHED</code> clause, the expression can use values
287 from the original row in the target table, and values from the
288 <em class="replaceable"><code>data_source</code></em> row.
289 If used in a <code class="literal">WHEN NOT MATCHED BY SOURCE</code> clause, the
290 expression can only use values from the original row in the target table.
291 If used in a <code class="literal">WHEN NOT MATCHED [BY TARGET]</code> clause, the
292 expression can only use values from the
293 <em class="replaceable"><code>data_source</code></em> row.
294 </p></dd><dt><span class="term"><code class="literal">DEFAULT</code></span></dt><dd><p>
295 Set the column to its default value (which will be <code class="literal">NULL</code>
296 if no specific default expression has been assigned to it).
297 </p></dd><dt><span class="term"><em class="replaceable"><code>sub-SELECT</code></em></span></dt><dd><p>
298 A <code class="literal">SELECT</code> sub-query that produces as many output columns
299 as are listed in the parenthesized column list preceding it. The
300 sub-query must yield no more than one row when executed. If it
301 yields one row, its column values are assigned to the target columns;
302 if it yields no rows, NULL values are assigned to the target columns.
303 If used in a <code class="literal">WHEN MATCHED</code> clause, the sub-query can
304 refer to values from the original row in the target table, and values
305 from the <em class="replaceable"><code>data_source</code></em> row.
306 If used in a <code class="literal">WHEN NOT MATCHED BY SOURCE</code> clause, the
307 sub-query can only refer to values from the original row in the target
309 </p></dd><dt><span class="term"><em class="replaceable"><code>output_alias</code></em></span></dt><dd><p>
310 An optional substitute name for <code class="literal">OLD</code> or
311 <code class="literal">NEW</code> rows in the <code class="literal">RETURNING</code> list.
313 By default, old values from the target table can be returned by writing
314 <code class="literal">OLD.<em class="replaceable"><code>column_name</code></em></code>
315 or <code class="literal">OLD.*</code>, and new values can be returned by writing
316 <code class="literal">NEW.<em class="replaceable"><code>column_name</code></em></code>
317 or <code class="literal">NEW.*</code>. When an alias is provided, these names are
318 hidden and the old or new rows must be referred to using the alias.
319 For example <code class="literal">RETURNING WITH (OLD AS o, NEW AS n) o.*, n.*</code>.
320 </p></dd><dt><span class="term"><em class="replaceable"><code>output_expression</code></em></span></dt><dd><p>
321 An expression to be computed and returned by the <code class="command">MERGE</code>
322 command after each row is changed (whether inserted, updated, or deleted).
323 The expression can use any columns of the source or target tables, or the
324 <a class="link" href="functions-merge-support.html#MERGE-ACTION"><code class="function">merge_action()</code></a>
325 function to return additional information about the action executed.
327 Writing <code class="literal">*</code> will return all columns from the source
328 table, followed by all columns from the target table. Often this will
329 lead to a lot of duplication, since it is common for the source and
330 target tables to have a lot of the same columns. This can be avoided by
331 qualifying the <code class="literal">*</code> with the name or alias of the source
334 A column name or <code class="literal">*</code> may also be qualified using
335 <code class="literal">OLD</code> or <code class="literal">NEW</code>, or the corresponding
336 <em class="replaceable"><code>output_alias</code></em> for
337 <code class="literal">OLD</code> or <code class="literal">NEW</code>, to cause old or new
338 values from the target table to be returned. An unqualified column
339 name from the target table, or a column name or <code class="literal">*</code>
340 qualified using the target table name or alias will return new values
341 for <code class="literal">INSERT</code> and <code class="literal">UPDATE</code> actions, and
342 old values for <code class="literal">DELETE</code> actions.
343 </p></dd><dt><span class="term"><em class="replaceable"><code>output_name</code></em></span></dt><dd><p>
344 A name to use for a returned column.
345 </p></dd></dl></div></div><div class="refsect1" id="id-1.9.3.156.7"><h2>Outputs</h2><p>
346 On successful completion, a <code class="command">MERGE</code> command returns a command
348 </p><pre class="screen">
349 MERGE <em class="replaceable"><code>total_count</code></em>
351 The <em class="replaceable"><code>total_count</code></em> is the total
352 number of rows changed (whether inserted, updated, or deleted).
353 If <em class="replaceable"><code>total_count</code></em> is 0, no rows
354 were changed in any way.
356 If the <code class="command">MERGE</code> command contains a <code class="literal">RETURNING</code>
357 clause, the result will be similar to that of a <code class="command">SELECT</code>
358 statement containing the columns and values defined in the
359 <code class="literal">RETURNING</code> list, computed over the row(s) inserted, updated,
360 or deleted by the command.
361 </p></div><div class="refsect1" id="id-1.9.3.156.8"><h2>Notes</h2><p>
362 The following steps take place during the execution of
363 <code class="command">MERGE</code>.
364 </p><div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><p>
365 Perform any <code class="literal">BEFORE STATEMENT</code> triggers for all
366 actions specified, whether or not their <code class="literal">WHEN</code>
368 </p></li><li class="listitem"><p>
369 Perform a join from source to target table.
370 The resulting query will be optimized normally and will produce
371 a set of candidate change rows. For each candidate change row,
372 </p><div class="orderedlist"><ol class="orderedlist" type="a"><li class="listitem"><p>
373 Evaluate whether each row is <code class="literal">MATCHED</code>,
374 <code class="literal">NOT MATCHED BY SOURCE</code>, or
375 <code class="literal">NOT MATCHED [BY TARGET]</code>.
376 </p></li><li class="listitem"><p>
377 Test each <code class="literal">WHEN</code> condition in the order
378 specified until one returns true.
379 </p></li><li class="listitem"><p>
380 When a condition returns true, perform the following actions:
381 </p><div class="orderedlist"><ol class="orderedlist" type="i"><li class="listitem"><p>
382 Perform any <code class="literal">BEFORE ROW</code> triggers that fire
383 for the action's event type.
384 </p></li><li class="listitem"><p>
385 Perform the specified action, invoking any check constraints on the
387 </p></li><li class="listitem"><p>
388 Perform any <code class="literal">AFTER ROW</code> triggers that fire for
389 the action's event type.
390 </p></li></ol></div><p>
391 If the target relation is a view with <code class="literal">INSTEAD OF ROW</code>
392 triggers for the action's event type, they are used to perform the
394 </p></li></ol></div></li><li class="listitem"><p>
395 Perform any <code class="literal">AFTER STATEMENT</code> triggers for actions
396 specified, whether or not they actually occur. This is similar to the
397 behavior of an <code class="command">UPDATE</code> statement that modifies no rows.
398 </p></li></ol></div><p>
399 In summary, statement triggers for an event type (say,
400 <code class="command">INSERT</code>) will be fired whenever we
401 <span class="emphasis"><em>specify</em></span> an action of that kind.
402 In contrast, row-level triggers will fire only for the specific event type
403 being <span class="emphasis"><em>executed</em></span>.
404 So a <code class="command">MERGE</code> command might fire statement triggers for both
405 <code class="command">UPDATE</code> and <code class="command">INSERT</code>, even though only
406 <code class="command">UPDATE</code> row triggers were fired.
408 You should ensure that the join produces at most one candidate change row
409 for each target row. In other words, a target row shouldn't join to more
410 than one data source row. If it does, then only one of the candidate change
411 rows will be used to modify the target row; later attempts to modify the
412 row will cause an error.
413 This can also occur if row triggers make changes to the target table
414 and the rows so modified are then subsequently also modified by
415 <code class="command">MERGE</code>.
416 If the repeated action is an <code class="command">INSERT</code>, this will
417 cause a uniqueness violation, while a repeated <code class="command">UPDATE</code>
418 or <code class="command">DELETE</code> will cause a cardinality violation; the
419 latter behavior is required by the <acronym class="acronym">SQL</acronym> standard.
420 This differs from historical <span class="productname">PostgreSQL</span>
421 behavior of joins in <code class="command">UPDATE</code> and
422 <code class="command">DELETE</code> statements where second and subsequent
423 attempts to modify the same row are simply ignored.
425 If a <code class="literal">WHEN</code> clause omits an <code class="literal">AND</code>
426 sub-clause, it becomes the final reachable clause of that
427 kind (<code class="literal">MATCHED</code>, <code class="literal">NOT MATCHED BY SOURCE</code>,
428 or <code class="literal">NOT MATCHED [BY TARGET]</code>).
429 If a later <code class="literal">WHEN</code> clause of that kind
430 is specified it would be provably unreachable and an error is raised.
431 If no final reachable clause is specified of either kind, it is
432 possible that no action will be taken for a candidate change row.
434 The order in which rows are generated from the data source is
435 indeterminate by default.
436 A <em class="replaceable"><code>source_query</code></em> can be
437 used to specify a consistent ordering, if required, which might be
438 needed to avoid deadlocks between concurrent transactions.
440 When <code class="command">MERGE</code> is run concurrently with other commands
441 that modify the target table, the usual transaction isolation rules
442 apply; see <a class="xref" href="transaction-iso.html" title="13.2. Transaction Isolation">Section 13.2</a> for an explanation
443 on the behavior at each isolation level.
444 You may also wish to consider using <code class="command">INSERT ... ON CONFLICT</code>
445 as an alternative statement which offers the ability to run an
446 <code class="command">UPDATE</code> if a concurrent <code class="command">INSERT</code>
447 occurs. There are a variety of differences and restrictions between
448 the two statement types and they are not interchangeable.
449 </p></div><div class="refsect1" id="id-1.9.3.156.9"><h2>Examples</h2><p>
450 Perform maintenance on <code class="literal">customer_accounts</code> based
451 upon new <code class="literal">recent_transactions</code>.
453 </p><pre class="programlisting">
454 MERGE INTO customer_account ca
455 USING recent_transactions t
456 ON t.customer_id = ca.customer_id
458 UPDATE SET balance = balance + transaction_value
459 WHEN NOT MATCHED THEN
460 INSERT (customer_id, balance)
461 VALUES (t.customer_id, t.transaction_value);
464 Attempt to insert a new stock item along with the quantity of stock. If
465 the item already exists, instead update the stock count of the existing
466 item. Don't allow entries that have zero stock. Return details of all
468 </p><pre class="programlisting">
470 USING wine_stock_changes s
471 ON s.winename = w.winename
472 WHEN NOT MATCHED AND s.stock_delta > 0 THEN
473 INSERT VALUES(s.winename, s.stock_delta)
474 WHEN MATCHED AND w.stock + s.stock_delta > 0 THEN
475 UPDATE SET stock = w.stock + s.stock_delta
478 RETURNING merge_action(), w.winename, old.stock AS old_stock, new.stock AS new_stock;
481 The <code class="literal">wine_stock_changes</code> table might be, for example, a
482 temporary table recently loaded into the database.
484 Update <code class="literal">wines</code> based on a replacement wine list, inserting
485 rows for any new stock, updating modified stock entries, and deleting any
486 wines not present in the new list.
487 </p><pre class="programlisting">
489 USING new_wine_list s
490 ON s.winename = w.winename
491 WHEN NOT MATCHED BY TARGET THEN
492 INSERT VALUES(s.winename, s.stock)
493 WHEN MATCHED AND w.stock != s.stock THEN
494 UPDATE SET stock = s.stock
495 WHEN NOT MATCHED BY SOURCE THEN
498 </p></div><div class="refsect1" id="id-1.9.3.156.10"><h2>Compatibility</h2><p>
499 This command conforms to the <acronym class="acronym">SQL</acronym> standard.
501 The <code class="literal">WITH</code> clause, <code class="literal">BY SOURCE</code> and
502 <code class="literal">BY TARGET</code> qualifiers to
503 <code class="literal">WHEN NOT MATCHED</code>, <code class="literal">DO NOTHING</code> action,
504 and <code class="literal">RETURNING</code> clause are extensions to the
505 <acronym class="acronym">SQL</acronym> standard.
506 </p></div></div><div class="navfooter"><hr /><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="sql-lock.html" title="LOCK">Prev</a> </td><td width="20%" align="center"><a accesskey="u" href="sql-commands.html" title="SQL Commands">Up</a></td><td width="40%" align="right"> <a accesskey="n" href="sql-move.html" title="MOVE">Next</a></td></tr><tr><td width="40%" align="left" valign="top">LOCK </td><td width="20%" align="center"><a accesskey="h" href="index.html" title="PostgreSQL 18.0 Documentation">Home</a></td><td width="40%" align="right" valign="top"> MOVE</td></tr></table></div></body></html>