4 MERGE — conditionally insert, update, or delete rows of a table
8 [ WITH with_query [, ...] ]
9 MERGE INTO [ ONLY ] target_table_name [ * ] [ [ AS ] target_alias ]
10 USING data_source ON join_condition
12 [ RETURNING [ WITH ( { OLD | NEW } AS output_alias [, ...] ) ]
13 { * | output_expression [ [ AS ] output_name ] } [, ...] ]
17 { [ ONLY ] source_table_name [ * ] | ( source_query ) } [ [ AS ] source_alia
22 { WHEN MATCHED [ AND condition ] THEN { merge_update | merge_delete | DO NOT
24 WHEN NOT MATCHED BY SOURCE [ AND condition ] THEN { merge_update | merge_d
25 elete | DO NOTHING } |
26 WHEN NOT MATCHED [ BY TARGET ] [ AND condition ] THEN { merge_insert | DO
31 INSERT [( column_name [, ...] )]
32 [ OVERRIDING { SYSTEM | USER } VALUE ]
33 { VALUES ( { expression | DEFAULT } [, ...] ) | DEFAULT VALUES }
37 UPDATE SET { column_name = { expression | DEFAULT } |
38 ( column_name [, ...] ) = [ ROW ] ( { expression | DEFAULT } [,
40 ( column_name [, ...] ) = ( sub-SELECT )
49 MERGE performs actions that modify rows in the target table identified
50 as target_table_name, using the data_source. MERGE provides a single
51 SQL statement that can conditionally INSERT, UPDATE or DELETE rows, a
52 task that would otherwise require multiple procedural language
55 First, the MERGE command performs a join from data_source to the target
56 table producing zero or more candidate change rows. For each candidate
57 change row, the status of MATCHED, NOT MATCHED BY SOURCE, or NOT
58 MATCHED [BY TARGET] is set just once, after which WHEN clauses are
59 evaluated in the order specified. For each candidate change row, the
60 first clause to evaluate as true is executed. No more than one WHEN
61 clause is executed for any candidate change row.
63 MERGE actions have the same effect as regular UPDATE, INSERT, or DELETE
64 commands of the same names. The syntax of those commands is different,
65 notably that there is no WHERE clause and no table name is specified.
66 All actions refer to the target table, though modifications to other
67 tables may be made using triggers.
69 When DO NOTHING is specified, the source row is skipped. Since actions
70 are evaluated in their specified order, DO NOTHING can be handy to skip
71 non-interesting source rows before more fine-grained handling.
73 The optional RETURNING clause causes MERGE to compute and return
74 value(s) based on each row inserted, updated, or deleted. Any
75 expression using the source or target table's columns, or the
76 merge_action() function can be computed. By default, when an INSERT or
77 UPDATE action is performed, the new values of the target table's
78 columns are used, and when a DELETE is performed, the old values of the
79 target table's columns are used, but it is also possible to explicitly
80 request old and new values. The syntax of the RETURNING list is
81 identical to that of the output list of SELECT.
83 There is no separate MERGE privilege. If you specify an update action,
84 you must have the UPDATE privilege on the column(s) of the target table
85 that are referred to in the SET clause. If you specify an insert
86 action, you must have the INSERT privilege on the target table. If you
87 specify a delete action, you must have the DELETE privilege on the
88 target table. If you specify a DO NOTHING action, you must have the
89 SELECT privilege on at least one column of the target table. You will
90 also need SELECT privilege on any column(s) of the data_source and of
91 the target table referred to in any condition (including
92 join_condition) or expression. Privileges are tested once at statement
93 start and are checked whether or not particular WHEN clauses are
96 MERGE is not supported if the target table is a materialized view,
97 foreign table, or if it has any rules defined on it.
102 The WITH clause allows you to specify one or more subqueries
103 that can be referenced by name in the MERGE query. See
104 Section 7.8 and SELECT for details. Note that WITH RECURSIVE is
105 not supported by MERGE.
108 The name (optionally schema-qualified) of the target table or
109 view to merge into. If ONLY is specified before a table name,
110 matching rows are updated or deleted in the named table only. If
111 ONLY is not specified, matching rows are also updated or deleted
112 in any tables inheriting from the named table. Optionally, * can
113 be specified after the table name to explicitly indicate that
114 descendant tables are included. The ONLY keyword and * option do
115 not affect insert actions, which always insert into the named
118 If target_table_name is a view, it must either be automatically
119 updatable with no INSTEAD OF triggers, or it must have INSTEAD
120 OF triggers for every type of action (INSERT, UPDATE, and
121 DELETE) specified in the WHEN clauses. Views with rules are not
125 A substitute name for the target table. When an alias is
126 provided, it completely hides the actual name of the table. For
127 example, given MERGE INTO foo AS f, the remainder of the MERGE
128 statement must refer to this table as f not foo.
131 The name (optionally schema-qualified) of the source table,
132 view, or transition table. If ONLY is specified before the table
133 name, matching rows are included from the named table only. If
134 ONLY is not specified, matching rows are also included from any
135 tables inheriting from the named table. Optionally, * can be
136 specified after the table name to explicitly indicate that
137 descendant tables are included.
140 A query (SELECT statement or VALUES statement) that supplies the
141 rows to be merged into the target table. Refer to the SELECT
142 statement or VALUES statement for a description of the syntax.
145 A substitute name for the data source. When an alias is
146 provided, it completely hides the actual name of the table or
147 the fact that a query was issued.
150 join_condition is an expression resulting in a value of type
151 boolean (similar to a WHERE clause) that specifies which rows in
152 the data_source match rows in the target table.
156 Only columns from the target table that attempt to match
157 data_source rows should appear in join_condition. join_condition
158 subexpressions that only reference the target table's columns
159 can affect which action is taken, often in surprising ways.
161 If both WHEN NOT MATCHED BY SOURCE and WHEN NOT MATCHED [BY
162 TARGET] clauses are specified, the MERGE command will perform a
163 FULL join between data_source and the target table. For this to
164 work, at least one join_condition subexpression must use an
165 operator that can support a hash join, or all of the
166 subexpressions must use operators that can support a merge join.
169 At least one WHEN clause is required.
171 The WHEN clause may specify WHEN MATCHED, WHEN NOT MATCHED BY
172 SOURCE, or WHEN NOT MATCHED [BY TARGET]. Note that the SQL
173 standard only defines WHEN MATCHED and WHEN NOT MATCHED (which
174 is defined to mean no matching target row). WHEN NOT MATCHED BY
175 SOURCE is an extension to the SQL standard, as is the option to
176 append BY TARGET to WHEN NOT MATCHED, to make its meaning more
179 If the WHEN clause specifies WHEN MATCHED and the candidate
180 change row matches a row in the data_source to a row in the
181 target table, the WHEN clause is executed if the condition is
182 absent or it evaluates to true.
184 If the WHEN clause specifies WHEN NOT MATCHED BY SOURCE and the
185 candidate change row represents a row in the target table that
186 does not match a row in the data_source, the WHEN clause is
187 executed if the condition is absent or it evaluates to true.
189 If the WHEN clause specifies WHEN NOT MATCHED [BY TARGET] and
190 the candidate change row represents a row in the data_source
191 that does not match a row in the target table, the WHEN clause
192 is executed if the condition is absent or it evaluates to true.
195 An expression that returns a value of type boolean. If this
196 expression for a WHEN clause returns true, then the action for
197 that clause is executed for that row.
199 A condition on a WHEN MATCHED clause can refer to columns in
200 both the source and the target relations. A condition on a WHEN
201 NOT MATCHED BY SOURCE clause can only refer to columns from the
202 target relation, since by definition there is no matching source
203 row. A condition on a WHEN NOT MATCHED [BY TARGET] clause can
204 only refer to columns from the source relation, since by
205 definition there is no matching target row. Only the system
206 attributes from the target table are accessible.
209 The specification of an INSERT action that inserts one row into
210 the target table. The target column names can be listed in any
211 order. If no list of column names is given at all, the default
212 is all the columns of the table in their declared order.
214 Each column not present in the explicit or implicit column list
215 will be filled with a default value, either its declared default
216 value or null if there is none.
218 If the target table is a partitioned table, each row is routed
219 to the appropriate partition and inserted into it. If the target
220 table is a partition, an error will occur if any input row
221 violates the partition constraint.
223 Column names may not be specified more than once. INSERT actions
224 cannot contain sub-selects.
226 Only one VALUES clause can be specified. The VALUES clause can
227 only refer to columns from the source relation, since by
228 definition there is no matching target row.
231 The specification of an UPDATE action that updates the current
232 row of the target table. Column names may not be specified more
235 Neither a table name nor a WHERE clause are allowed.
238 Specifies a DELETE action that deletes the current row of the
239 target table. Do not include the table name or any other
240 clauses, as you would normally do with a DELETE command.
243 The name of a column in the target table. The column name can be
244 qualified with a subfield name or array subscript, if needed.
245 (Inserting into only some fields of a composite column leaves
246 the other fields null.) Do not include the table's name in the
247 specification of a target column.
249 OVERRIDING SYSTEM VALUE
250 Without this clause, it is an error to specify an explicit value
251 (other than DEFAULT) for an identity column defined as GENERATED
252 ALWAYS. This clause overrides that restriction.
254 OVERRIDING USER VALUE
255 If this clause is specified, then any values supplied for
256 identity columns defined as GENERATED BY DEFAULT are ignored and
257 the default sequence-generated values are applied.
260 All columns will be filled with their default values. (An
261 OVERRIDING clause is not permitted in this form.)
264 An expression to assign to the column. If used in a WHEN MATCHED
265 clause, the expression can use values from the original row in
266 the target table, and values from the data_source row. If used
267 in a WHEN NOT MATCHED BY SOURCE clause, the expression can only
268 use values from the original row in the target table. If used in
269 a WHEN NOT MATCHED [BY TARGET] clause, the expression can only
270 use values from the data_source row.
273 Set the column to its default value (which will be NULL if no
274 specific default expression has been assigned to it).
277 A SELECT sub-query that produces as many output columns as are
278 listed in the parenthesized column list preceding it. The
279 sub-query must yield no more than one row when executed. If it
280 yields one row, its column values are assigned to the target
281 columns; if it yields no rows, NULL values are assigned to the
282 target columns. If used in a WHEN MATCHED clause, the sub-query
283 can refer to values from the original row in the target table,
284 and values from the data_source row. If used in a WHEN NOT
285 MATCHED BY SOURCE clause, the sub-query can only refer to values
286 from the original row in the target table.
289 An optional substitute name for OLD or NEW rows in the RETURNING
292 By default, old values from the target table can be returned by
293 writing OLD.column_name or OLD.*, and new values can be returned
294 by writing NEW.column_name or NEW.*. When an alias is provided,
295 these names are hidden and the old or new rows must be referred
296 to using the alias. For example RETURNING WITH (OLD AS o, NEW AS
300 An expression to be computed and returned by the MERGE command
301 after each row is changed (whether inserted, updated, or
302 deleted). The expression can use any columns of the source or
303 target tables, or the merge_action() function to return
304 additional information about the action executed.
306 Writing * will return all columns from the source table,
307 followed by all columns from the target table. Often this will
308 lead to a lot of duplication, since it is common for the source
309 and target tables to have a lot of the same columns. This can be
310 avoided by qualifying the * with the name or alias of the source
313 A column name or * may also be qualified using OLD or NEW, or
314 the corresponding output_alias for OLD or NEW, to cause old or
315 new values from the target table to be returned. An unqualified
316 column name from the target table, or a column name or *
317 qualified using the target table name or alias will return new
318 values for INSERT and UPDATE actions, and old values for DELETE
322 A name to use for a returned column.
326 On successful completion, a MERGE command returns a command tag of the
330 The total_count is the total number of rows changed (whether inserted,
331 updated, or deleted). If total_count is 0, no rows were changed in any
334 If the MERGE command contains a RETURNING clause, the result will be
335 similar to that of a SELECT statement containing the columns and values
336 defined in the RETURNING list, computed over the row(s) inserted,
337 updated, or deleted by the command.
341 The following steps take place during the execution of MERGE.
342 1. Perform any BEFORE STATEMENT triggers for all actions specified,
343 whether or not their WHEN clauses match.
344 2. Perform a join from source to target table. The resulting query
345 will be optimized normally and will produce a set of candidate
346 change rows. For each candidate change row,
347 a. Evaluate whether each row is MATCHED, NOT MATCHED BY SOURCE,
348 or NOT MATCHED [BY TARGET].
349 b. Test each WHEN condition in the order specified until one
351 c. When a condition returns true, perform the following actions:
352 i. Perform any BEFORE ROW triggers that fire for the
354 ii. Perform the specified action, invoking any check
355 constraints on the target table.
356 iii. Perform any AFTER ROW triggers that fire for the
358 If the target relation is a view with INSTEAD OF ROW triggers
359 for the action's event type, they are used to perform the
361 3. Perform any AFTER STATEMENT triggers for actions specified, whether
362 or not they actually occur. This is similar to the behavior of an
363 UPDATE statement that modifies no rows.
365 In summary, statement triggers for an event type (say, INSERT) will be
366 fired whenever we specify an action of that kind. In contrast,
367 row-level triggers will fire only for the specific event type being
368 executed. So a MERGE command might fire statement triggers for both
369 UPDATE and INSERT, even though only UPDATE row triggers were fired.
371 You should ensure that the join produces at most one candidate change
372 row for each target row. In other words, a target row shouldn't join to
373 more than one data source row. If it does, then only one of the
374 candidate change rows will be used to modify the target row; later
375 attempts to modify the row will cause an error. This can also occur if
376 row triggers make changes to the target table and the rows so modified
377 are then subsequently also modified by MERGE. If the repeated action is
378 an INSERT, this will cause a uniqueness violation, while a repeated
379 UPDATE or DELETE will cause a cardinality violation; the latter
380 behavior is required by the SQL standard. This differs from historical
381 PostgreSQL behavior of joins in UPDATE and DELETE statements where
382 second and subsequent attempts to modify the same row are simply
385 If a WHEN clause omits an AND sub-clause, it becomes the final
386 reachable clause of that kind (MATCHED, NOT MATCHED BY SOURCE, or NOT
387 MATCHED [BY TARGET]). If a later WHEN clause of that kind is specified
388 it would be provably unreachable and an error is raised. If no final
389 reachable clause is specified of either kind, it is possible that no
390 action will be taken for a candidate change row.
392 The order in which rows are generated from the data source is
393 indeterminate by default. A source_query can be used to specify a
394 consistent ordering, if required, which might be needed to avoid
395 deadlocks between concurrent transactions.
397 When MERGE is run concurrently with other commands that modify the
398 target table, the usual transaction isolation rules apply; see
399 Section 13.2 for an explanation on the behavior at each isolation
400 level. You may also wish to consider using INSERT ... ON CONFLICT as an
401 alternative statement which offers the ability to run an UPDATE if a
402 concurrent INSERT occurs. There are a variety of differences and
403 restrictions between the two statement types and they are not
408 Perform maintenance on customer_accounts based upon new
410 MERGE INTO customer_account ca
411 USING recent_transactions t
412 ON t.customer_id = ca.customer_id
414 UPDATE SET balance = balance + transaction_value
415 WHEN NOT MATCHED THEN
416 INSERT (customer_id, balance)
417 VALUES (t.customer_id, t.transaction_value);
419 Attempt to insert a new stock item along with the quantity of stock. If
420 the item already exists, instead update the stock count of the existing
421 item. Don't allow entries that have zero stock. Return details of all
424 USING wine_stock_changes s
425 ON s.winename = w.winename
426 WHEN NOT MATCHED AND s.stock_delta > 0 THEN
427 INSERT VALUES(s.winename, s.stock_delta)
428 WHEN MATCHED AND w.stock + s.stock_delta > 0 THEN
429 UPDATE SET stock = w.stock + s.stock_delta
432 RETURNING merge_action(), w.winename, old.stock AS old_stock, new.stock AS new_s
435 The wine_stock_changes table might be, for example, a temporary table
436 recently loaded into the database.
438 Update wines based on a replacement wine list, inserting rows for any
439 new stock, updating modified stock entries, and deleting any wines not
440 present in the new list.
442 USING new_wine_list s
443 ON s.winename = w.winename
444 WHEN NOT MATCHED BY TARGET THEN
445 INSERT VALUES(s.winename, s.stock)
446 WHEN MATCHED AND w.stock != s.stock THEN
447 UPDATE SET stock = s.stock
448 WHEN NOT MATCHED BY SOURCE THEN
453 This command conforms to the SQL standard.
455 The WITH clause, BY SOURCE and BY TARGET qualifiers to WHEN NOT
456 MATCHED, DO NOTHING action, and RETURNING clause are extensions to the