バージョンごとのドキュメント一覧

MERGE

MERGE <refpurpose>conditionally insert, update, or delete rows of a table</refpurpose> — テーブルの行を条件付きでINSERT、UPDATE、DELETEする

概要

[ WITH with_query [, ...] ]
MERGE INTO [ ONLY ] target_table_name [ * ] [ [ AS ] target_alias ]
USING data_source ON join_condition
when_clause [...]
[ RETURNING { * | output_expression [ [ AS ] output_name ] } [, ...] ]

where data_source is:

{ [ ONLY ] source_table_name [ * ] | ( source_query ) } [ [ AS ] source_alias ]

and when_clause is:

{ WHEN MATCHED [ AND condition ] THEN { merge_update | merge_delete | DO NOTHING } |
  WHEN NOT MATCHED BY SOURCE [ AND condition ] THEN { merge_update | merge_delete | DO NOTHING } |
  WHEN NOT MATCHED [ BY TARGET ] [ AND condition ] THEN { merge_insert | DO NOTHING } }

and merge_insert is:

INSERT [( column_name [, ...] )]
[ OVERRIDING { SYSTEM | USER } VALUE ]
{ VALUES ( { expression | DEFAULT } [, ...] ) | DEFAULT VALUES }

and merge_update is:

UPDATE SET { column_name = { expression | DEFAULT } |
             ( column_name [, ...] ) = [ ROW ] ( { expression | DEFAULT } [, ...] ) |
             ( column_name [, ...] ) = ( sub-SELECT )
           } [, ...]

and merge_delete is:

DELETE

説明

<title>Description</title>

<command>MERGE</command> performs actions that modify rows in the target table identified as <replaceable class="parameter">target_table_name</replaceable>, using the <replaceable class="parameter">data_source</replaceable>. <command>MERGE</command> provides a single <acronym>SQL</acronym> statement that can conditionally <command>INSERT</command>, <command>UPDATE</command> or <command>DELETE</command> rows, a task that would otherwise require multiple procedural language statements. MERGEは、data_sourceを使用して、target_table_nameで指定された対象テーブルの行を変更するアクションを実行します。 MERGEは、条件付きで行のINSERTUPDATEまたはDELETEを実行できる単一のSQL文を提供します。 これがないと、複数の手続き言語文が必要になります。

First, the <command>MERGE</command> command performs a join from <replaceable class="parameter">data_source</replaceable> to the target table producing zero or more candidate change rows. For each candidate change row, the status of <literal>MATCHED</literal>, <literal>NOT MATCHED BY SOURCE</literal>, or <literal>NOT MATCHED [BY TARGET]</literal> is set just once, after which <literal>WHEN</literal> clauses are evaluated in the order specified. For each candidate change row, the first clause to evaluate as true is executed. No more than one <literal>WHEN</literal> clause is executed for any candidate change row. 最初に、MERGEコマンドはdata_sourceから対象テーブルへの結合を実行し、0以上の変更候補行を生成します。 各変更候補行に対して、MATCHEDNOT MATCHED BY SOURCEまたはNOT MATCHED [BY TARGET]の状態が一度だけ設定され、その後WHEN句が指定された順序で評価されます。 各変更候補行に対して、真と評価される最初の句が実行されます。 どの変更候補行に対しても、1つのWHEN句しか実行されません。

<command>MERGE</command> actions have the same effect as regular <command>UPDATE</command>, <command>INSERT</command>, or <command>DELETE</command> commands of the same names. The syntax of those commands is different, notably that there is no <literal>WHERE</literal> clause and no table name is specified. All actions refer to the target table, though modifications to other tables may be made using triggers. MERGEアクションは、同じ名前の通常のUPDATEINSERTまたはDELETEコマンドと同じ効果を持ちます。 これらのコマンドの構文は異なり、WHERE句がなく、テーブル名が指定されていません。 すべてのアクションは対象テーブルを参照しますが、他のテーブルへの変更はトリガを使用して行うことができます。

When <literal>DO NOTHING</literal> is specified, the source row is skipped. Since actions are evaluated in their specified order, <literal>DO NOTHING</literal> can be handy to skip non-interesting source rows before more fine-grained handling. DO NOTHINGが指定されている場合、元となる行はスキップされます。 アクションは指定された順序で評価されるため、DO NOTHINGは、より詳細な処理の前に、関心のない元となる行をスキップする場合に便利です。

The optional <literal>RETURNING</literal> clause causes <command>MERGE</command> to compute and return value(s) based on each row inserted, updated, or deleted. Any expression using the source or target table's columns, or the <link linkend="merge-action"><function>merge_action()</function></link> function can be computed. When an <command>INSERT</command> or <command>UPDATE</command> action is performed, the new values of the target table's columns are used. When a <command>DELETE</command> is performed, the old values of the target table's columns are used. The syntax of the <literal>RETURNING</literal> list is identical to that of the output list of <command>SELECT</command>. オプションのRETURNING句は、挿入、更新、削除された各行に基づいて値を計算し、返すようにMERGEを設定します。 元となるテーブルまたは対象テーブルの列、あるいはmerge_action()関数を使用する式が計算可能です。 INSERTまたはUPDATEアクションが実行されると、対象テーブルの列の新しい値が使用されます。 DELETEが実行されると、対象テーブルの列の古い値が使用されます。 RETURNINGリストの構文は、SELECTの出力リストと同じです。

There is no separate <literal>MERGE</literal> privilege. If you specify an update action, you must have the <literal>UPDATE</literal> privilege on the column(s) of the target table that are referred to in the <literal>SET</literal> clause. If you specify an insert action, you must have the <literal>INSERT</literal> privilege on the target table. If you specify a delete action, you must have the <literal>DELETE</literal> privilege on the target table. If you specify a <literal>DO NOTHING</literal> action, you must have the <literal>SELECT</literal> privilege on at least one column of the target table. You will also need <literal>SELECT</literal> privilege on any column(s) of the <replaceable class="parameter">data_source</replaceable> and of the target table referred to in any <literal>condition</literal> (including <literal>join_condition</literal>) or <literal>expression</literal>. Privileges are tested once at statement start and are checked whether or not particular <literal>WHEN</literal> clauses are executed. 別個のMERGE権限はありません。 更新アクションを指定する場合、SET句で参照される対象テーブルの列に対するUPDATE権限が必要です。 挿入アクションを指定する場合、対象テーブルに対するINSERT権限が必要です。 削除アクションを指定する場合、対象テーブルに対するDELETE権限が必要です。 DO NOTHINGアクションを指定する場合、対象テーブルの少なくとも1つの列に対するSELECT権限が必要です。 また、data_sourceの任意の列とconditionjoin_conditionを含む)またはexpressionで参照される対象テーブルの任意の列に対するSELECT権限も必要です。 権限は文の開始時に一度テストされ、特定のWHEN句が実行されるかどうかがチェックされます。

<command>MERGE</command> is not supported if the target table is a materialized view, foreign table, or if it has any rules defined on it. 対象テーブルがマテリアライズドビュー、外部テーブルである場合、またはテーブルにルールが定義されている場合、MERGEはサポートされません。

パラメータ

<title>Parameters</title>
with_query

The <literal>WITH</literal> clause allows you to specify one or more subqueries that can be referenced by name in the <command>MERGE</command> query. See <xref linkend="queries-with"/> and <xref linkend="sql-select"/> for details. Note that <literal>WITH RECURSIVE</literal> is not supported by <command>MERGE</command>. WITH句を使用すると、MERGE問い合わせで名前で参照できる1つ以上の副問い合わせを指定できます。 詳細は7.8SELECTを参照してください。 WITH RECURSIVEMERGEではサポートされていないことに注意してください。

target_table_name

The name (optionally schema-qualified) of the target table or view to merge into. If <literal>ONLY</literal> is specified before a table name, matching rows are updated or deleted in the named table only. If <literal>ONLY</literal> is not specified, matching rows are also updated or deleted in any tables inheriting from the named table. Optionally, <literal>*</literal> can be specified after the table name to explicitly indicate that descendant tables are included. The <literal>ONLY</literal> keyword and <literal>*</literal> option do not affect insert actions, which always insert into the named table only. マージ先の対象テーブルもしくはビューの名前です(スキーマ修飾名も可)。 テーブル名の前にONLYを指定すると、指定したテーブルでのみ一致する行が更新または削除されます。 ONLYを指定しないと、指定したテーブルを継承するテーブルでも一致する行が更新または削除されます。 オプションで、テーブル名の後に*を指定して、子孫のテーブルが含まれることを明示的に示すことができます。 ONLYキーワードおよび*オプションは、挿入操作には影響しません。挿入操作では、常に指定したテーブルにのみ挿入します。

If <replaceable class="parameter">target_table_name</replaceable> is a view, it must either be automatically updatable with no <literal>INSTEAD OF</literal> triggers, or it must have <literal>INSTEAD OF</literal> triggers for every type of action (<literal>INSERT</literal>, <literal>UPDATE</literal>, and <literal>DELETE</literal>) specified in the <literal>WHEN</literal> clauses. Views with rules are not supported. target_table_nameがビューの場合、INSTEAD OFトリガを使用せずに自動的に更新可能であるか、WHEN句で指定されたすべてのアクション(INSERTUPDATEDELETE)に対してINSTEAD OFトリガを持つ必要があります。 ルール付きビューはサポートされていません。

target_alias

A substitute name for the target table. When an alias is provided, it completely hides the actual name of the table. For example, given <literal>MERGE INTO foo AS f</literal>, the remainder of the <command>MERGE</command> statement must refer to this table as <literal>f</literal> not <literal>foo</literal>. 対象テーブルの代替名です。 別名を指定すると、テーブルの実際の名前が完全に非表示になります。 たとえば、MERGE INTO foo AS fを指定した場合、MERGE文の残りの部分は、このテーブルをfooではなくfとして参照する必要があります。

source_table_name

The name (optionally schema-qualified) of the source table, view, or transition table. If <literal>ONLY</literal> is specified before the table name, matching rows are included from the named table only. If <literal>ONLY</literal> is not specified, matching rows are also included from any tables inheriting from the named table. Optionally, <literal>*</literal> can be specified after the table name to explicitly indicate that descendant tables are included. 元となるテーブル、ビュー、または遷移テーブルの名前(スキーマ修飾名も可)。 テーブル名の前にONLYを指定すると、指定したテーブルのみからの一致する行が含まれます。 ONLYを指定しないと、指定したテーブルを継承するすべてのテーブルからも一致する行が含まれます。 オプションで、テーブル名の後に*を指定して、子孫のテーブルが含まれることを明示的に示すことができます。

source_query

A query (<command>SELECT</command> statement or <command>VALUES</command> statement) that supplies the rows to be merged into the target table. Refer to the <xref linkend="sql-select"/> statement or <xref linkend="sql-values"/> statement for a description of the syntax. 対象テーブルにマージされる行を提供する問い合わせ(SELECT文またはVALUES文)です。 構文の説明は、SELECT文またはVALUES文を参照してください。

source_alias

A substitute name for the data source. When an alias is provided, it completely hides the actual name of the table or the fact that a query was issued. データソースの代替名です。 別名を指定すると、テーブルの実際の名前や問い合わせが発行された事実が完全に隠されます。

join_condition

<replaceable class="parameter">join_condition</replaceable> is an expression resulting in a value of type <type>boolean</type> (similar to a <literal>WHERE</literal> clause) that specifies which rows in the <replaceable class="parameter">data_source</replaceable> match rows in the target table. join_conditionboolean型の値を返す式です(WHERE句に似ています)。この式は、data_sourceのどの行が対象テーブルの行と一致するかを指定します。

警告

Only columns from the target table that attempt to match <replaceable class="parameter">data_source</replaceable> rows should appear in <replaceable class="parameter">join_condition</replaceable>. <replaceable class="parameter">join_condition</replaceable> subexpressions that only reference the target table's columns can affect which action is taken, often in surprising ways. join_conditionには、data_source行に一致しようとする対象テーブルの列のみが表示されます。 対象テーブルの列のみを参照するjoin_condition副式は、実行されるアクションに影響を与える可能性があり、多くの場合驚くべき方法で影響を与えます。

If both <literal>WHEN NOT MATCHED BY SOURCE</literal> and <literal>WHEN NOT MATCHED [BY TARGET]</literal> clauses are specified, the <command>MERGE</command> command will perform a <literal>FULL</literal> join between <replaceable class="parameter">data_source</replaceable> and the target table. For this to work, at least one <replaceable class="parameter">join_condition</replaceable> subexpression must use an operator that can support a hash join, or all of the subexpressions must use operators that can support a merge join. WHEN NOT MATCHED BY SOURCEWHEN NOT MATCHED [BY TARGET]の両方の句が指定された場合、MERGEコマンドはdata_sourceと対象テーブルの間でFULL結合を実行します。 これを機能させるには、少なくとも1つのjoin_condition副式がハッシュ結合をサポートできる演算子を使用するか、すべての副式がマージ結合をサポートできる演算子を使用する必要があります。

when_clause

At least one <literal>WHEN</literal> clause is required. 少なくとも1つのWHEN句が必要です。

The <literal>WHEN</literal> clause may specify <literal>WHEN MATCHED</literal>, <literal>WHEN NOT MATCHED BY SOURCE</literal>, or <literal>WHEN NOT MATCHED [BY TARGET]</literal>. Note that the <acronym>SQL</acronym> standard only defines <literal>WHEN MATCHED</literal> and <literal>WHEN NOT MATCHED</literal> (which is defined to mean no matching target row). <literal>WHEN NOT MATCHED BY SOURCE</literal> is an extension to the <acronym>SQL</acronym> standard, as is the option to append <literal>BY TARGET</literal> to <literal>WHEN NOT MATCHED</literal>, to make its meaning more explicit. WHEN句は、WHEN MATCHEDWHEN NOT MATCHED BY SOURCEまたはWHEN NOT MATCHED [BY TARGET]を指定できます。 標準SQLでは、WHEN MATCHEDWHEN NOT MATCHED(一致する対象行がないことを意味するものとして定義されている)のみを定義していることに注意してください。 WHEN NOT MATCHED BY SOURCEは標準SQLの拡張です。その意味をより明確にする、WHEN NOT MATCHEDBY TARGETを付加するオプションも同様に拡張です。

If the <literal>WHEN</literal> clause specifies <literal>WHEN MATCHED</literal> and the candidate change row matches a row in the <replaceable class="parameter">data_source</replaceable> to a row in the target table, the <literal>WHEN</literal> clause is executed if the <replaceable class="parameter">condition</replaceable> is absent or it evaluates to <literal>true</literal>. WHEN句でWHEN MATCHEDが指定され、変更候補行がdata_sourceの行と対象テーブルの行と一致する場合、conditionが存在しないかtrueと評価されるとWHEN句が実行されます。

If the <literal>WHEN</literal> clause specifies <literal>WHEN NOT MATCHED BY SOURCE</literal> and the candidate change row represents a row in the target table that does not match a row in the <replaceable class="parameter">data_source</replaceable>, the <literal>WHEN</literal> clause is executed if the <replaceable class="parameter">condition</replaceable> is absent or it evaluates to <literal>true</literal>. WHEN句でWHEN NOT MATCHED BY SOURCEが指定され、候補変更行がdata_sourceの行と一致しない対象テーブルの行を表す場合、conditionが存在しないかtrueと評価された場合にWHEN句が実行されます。

If the <literal>WHEN</literal> clause specifies <literal>WHEN NOT MATCHED [BY TARGET]</literal> and the candidate change row represents a row in the <replaceable class="parameter">data_source</replaceable> that does not match a row in the target table, the <literal>WHEN</literal> clause is executed if the <replaceable class="parameter">condition</replaceable> is absent or it evaluates to <literal>true</literal>. WHEN句でWHEN NOT MATCHED [BY TARGET]が指定され、候補変更行がdata_sourceの行を表し、その行が対象テーブルの行と一致しない場合、conditionが存在しないかtrueと評価された場合にWHEN句が実行されます。

condition

An expression that returns a value of type <type>boolean</type>. If this expression for a <literal>WHEN</literal> clause returns <literal>true</literal>, then the action for that clause is executed for that row. boolean型の値を返す式。 WHEN句のこの式がtrueを返す場合、その句のアクションがその行に対して実行されます。

A condition on a <literal>WHEN MATCHED</literal> clause can refer to columns in both the source and the target relations. A condition on a <literal>WHEN NOT MATCHED BY SOURCE</literal> clause can only refer to columns from the target relation, since by definition there is no matching source row. A condition on a <literal>WHEN NOT MATCHED [BY TARGET]</literal> clause can only refer to columns from the source relation, since by definition there is no matching target row. Only the system attributes from the target table are accessible. WHEN MATCHED句の条件は、元となるリレーションと対象リレーションの両方の列を参照できます。 WHEN NOT MATCHED BY SOURCE句の条件は、対象リレーションの列のみを参照できます。これは、定義上、一致する元となる行がないためです。 WHEN NOT MATCHED [BY TARGET]句の条件は、元となるリレーションの列のみを参照できます。これは、定義上、一致する対象行がないためです。 対象テーブルのシステム属性のみにアクセスできます。

merge_insert

The specification of an <literal>INSERT</literal> action that inserts one row into the target table. The target column names can be listed in any order. If no list of column names is given at all, the default is all the columns of the table in their declared order. 対象テーブルに1つの行を挿入するINSERTアクションの指定。 対象列名は任意の順序でリストできます。 列名のリストがまったく指定されていない場合、デフォルトではテーブルのすべての列が宣言された順序になります。

Each column not present in the explicit or implicit column list will be filled with a default value, either its declared default value or null if there is none. 明示的または暗黙的な列リストにない各列にはデフォルト値(デフォルト値が宣言されていればその値、未宣言ならばNULL)が挿入されます。

If the target table is a partitioned table, each row is routed to the appropriate partition and inserted into it. If the target table is a partition, an error will occur if any input row violates the partition constraint. 対象テーブルがパーティションテーブルの場合、各行は適切なパーティションにルーティングされ、パーティションに挿入されます。 対象テーブルがパーティションの場合、入力行がパーティション制約に違反するとエラーが発生します。

Column names may not be specified more than once. <command>INSERT</command> actions cannot contain sub-selects. 列名を複数回指定することはできません。 INSERTアクションに副SELECTを含めることはできません。

Only one <literal>VALUES</literal> clause can be specified. The <literal>VALUES</literal> clause can only refer to columns from the source relation, since by definition there is no matching target row. VALUES句は1つしか指定できません。 VALUES句は元となるリレーションの列のみを参照できます。 これは、定義上、一致する対象行がないためです。

merge_update

The specification of an <literal>UPDATE</literal> action that updates the current row of the target table. Column names may not be specified more than once. 対象テーブルの現在の行を更新するUPDATEアクションの指定。 列名は2回以上指定できません。

Neither a table name nor a <literal>WHERE</literal> clause are allowed. テーブル名もWHERE句も使用できません。

merge_delete

Specifies a <literal>DELETE</literal> action that deletes the current row of the target table. Do not include the table name or any other clauses, as you would normally do with a <xref linkend="sql-delete"/> command. 対象テーブルの現在の行を削除するDELETEアクションを指定します。 DELETEコマンドで通常行うように、テーブル名やその他の句は含めないでください。

column_name

The name of a column in the target table. The column name can be qualified with a subfield name or array subscript, if needed. (Inserting into only some fields of a composite column leaves the other fields null.) Do not include the table's name in the specification of a target column. 対象テーブルの列名。 列名は、必要に応じてサブフィールド名または配列の添字で修飾できます。 (複合列の一部のフィールドにのみ挿入すると、他のフィールドはNULLになります。) 対象列の指定には、テーブルの名前を含めないでください。

OVERRIDING SYSTEM VALUE

Without this clause, it is an error to specify an explicit value (other than <literal>DEFAULT</literal>) for an identity column defined as <literal>GENERATED ALWAYS</literal>. This clause overrides that restriction. この句を使用しない場合、GENERATED ALWAYSとして定義されたID列に対して明示的な値(DEFAULT以外)を指定するとエラーになります。 この句は、この制限を上書きします。

OVERRIDING USER VALUE

If this clause is specified, then any values supplied for identity columns defined as <literal>GENERATED BY DEFAULT</literal> are ignored and the default sequence-generated values are applied. この句を指定した場合、GENERATED BY DEFAULTとして定義されたID列に提供された値は無視され、シーケンスで生成されたデフォルト値が適用されます。

DEFAULT VALUES

All columns will be filled with their default values. (An <literal>OVERRIDING</literal> clause is not permitted in this form.) すべての列にデフォルト値が設定されます。 (このフォームではOVERRIDING句は使用できません。)

expression

An expression to assign to the column. If used in a <literal>WHEN MATCHED</literal> clause, the expression can use values from the original row in the target table, and values from the <replaceable class="parameter">data_source</replaceable> row. If used in a <literal>WHEN NOT MATCHED BY SOURCE</literal> clause, the expression can only use values from the original row in the target table. If used in a <literal>WHEN NOT MATCHED [BY TARGET]</literal> clause, the expression can only use values from the <replaceable class="parameter">data_source</replaceable> row. 列に割り当てる式。 WHEN MATCHED句で使用する場合、式は対象テーブルの元の行からの値とdata_source行からの値を使用できます。 WHEN NOT MATCHED BY SOURCE句で使用する場合、式は対象テーブルの元の行からの値のみを使用できます。 WHEN NOT MATCHED [BY TARGET]句で使用する場合、式はdata_source行からの値のみを使用できます。

DEFAULT

Set the column to its default value (which will be <literal>NULL</literal> if no specific default expression has been assigned to it). 列をデフォルト値に設定します(特定のデフォルト式が割り当てられていない場合はNULLになります)。

sub-SELECT

A <literal>SELECT</literal> sub-query that produces as many output columns as are listed in the parenthesized column list preceding it. The sub-query must yield no more than one row when executed. If it yields one row, its column values are assigned to the target columns; if it yields no rows, NULL values are assigned to the target columns. If used in a <literal>WHEN MATCHED</literal> clause, the sub-query can refer to values from the original row in the target table, and values from the <replaceable class="parameter">data_source</replaceable> row. If used in a <literal>WHEN NOT MATCHED BY SOURCE</literal> clause, the sub-query can only refer to values from the original row in the target table. それに先行する括弧付きの列リストに列挙されている出力列と同じ数の出力列を生成するSELECT副問い合わせ。 副問い合わせは、実行時に2行以上生成してはいけません。 行が1つ返されると、その列の値が対象列に割り当てられます。 行が返されない場合は、NULL値が対象列に割り当てられます。 WHEN MATCHED句で使用する場合、副問い合わせは、対象テーブルの元の行からの値とdata_source行からの値を参照できます。 WHEN NOT MATCHED BY SOURCE句で使用する場合、副問い合わせは、対象テーブルの元の行からの値のみを参照できます。

output_expression

An expression to be computed and returned by the <command>MERGE</command> command after each row is changed (whether inserted, updated, or deleted). The expression can use any columns of the source or target tables, or the <link linkend="merge-action"><function>merge_action()</function></link> function to return additional information about the action executed. 各行が変更(挿入、更新、削除)された後にMERGEコマンドによって計算され、返される式です。 式には、元となるテーブルまたは対象テーブルの任意の列、あるいは実行されたアクションに関する追加情報を返すmerge_action()関数を使用できます。

Writing <literal>*</literal> will return all columns from the source table, followed by all columns from the target table. Often this will lead to a lot of duplication, since it is common for the source and target tables to have a lot of the same columns. This can be avoided by qualifying the <literal>*</literal> with the name or alias of the source or target table. *を指定すると、元となるテーブルのすべての列が返され、その後に対象テーブルのすべての列が返されます。 多くの場合、元となるテーブルと対象テーブルは同じ列を多く持つため、この方法では重複が多くなります。 この問題を回避するには、元となるテーブルまたは対象テーブルの名前または別名で*を修飾します。

output_name

A name to use for a returned column. 返される列で使用される名前です。

出力

<title>Outputs</title>

On successful completion, a <command>MERGE</command> command returns a command tag of the form 正常に完了すると、MERGEコマンドは以下の形式のコマンドタグを返します。

MERGE total_count

The <replaceable class="parameter">total_count</replaceable> is the total number of rows changed (whether inserted, updated, or deleted). If <replaceable class="parameter">total_count</replaceable> is 0, no rows were changed in any way. total_countは変更された行の合計数です(挿入、更新、または削除のいずれか)。 total_countが0の場合、行はまったく変更されていません。

If the <command>MERGE</command> command contains a <literal>RETURNING</literal> clause, the result will be similar to that of a <command>SELECT</command> statement containing the columns and values defined in the <literal>RETURNING</literal> list, computed over the row(s) inserted, updated, or deleted by the command. MERGEコマンドがRETURNING句を含む場合、結果はRETURNINGリストに定義された列と値を含むSELECT文と同様になります。この場合、コマンドにより挿入、更新、削除された行に対して計算されます。

注釈

<title>Notes</title>

The following steps take place during the execution of <command>MERGE</command>. 次のステップは、MERGEの実行中に行われます。

  1. Perform any <literal>BEFORE STATEMENT</literal> triggers for all actions specified, whether or not their <literal>WHEN</literal> clauses match. WHEN句が一致するかどうかに関係なく、指定されたすべてのアクションに対してBEFORE STATEMENTトリガを実行します。

  2. Perform a join from source to target table. The resulting query will be optimized normally and will produce a set of candidate change rows. For each candidate change row, 元となるテーブルから対象テーブルへの結合を実行します。 結果の問合せは通常どおり最適化され、一連の変更候補行が生成されます。 各変更候補行について、

    1. Evaluate whether each row is <literal>MATCHED</literal>, <literal>NOT MATCHED BY SOURCE</literal>, or <literal>NOT MATCHED [BY TARGET]</literal>. 各行がMATCHEDNOT MATCHED BY SOURCE、またはNOT MATCHED [BY TARGET]のいずれであるかを評価します。

    2. Test each <literal>WHEN</literal> condition in the order specified until one returns true. 真が返されるまで、各WHEN条件を指定された順序でテストします。

    3. When a condition returns true, perform the following actions: 条件が真を返す場合は、次のアクションを実行します。

      1. Perform any <literal>BEFORE ROW</literal> triggers that fire for the action's event type. アクションのイベントタイプに対して起動するBEFORE ROWトリガを実行します。

      2. Perform the specified action, invoking any check constraints on the target table. 指定されたアクションを実行し、対象テーブルの検査制約を呼び出します。

      3. Perform any <literal>AFTER ROW</literal> triggers that fire for the action's event type. アクションのイベントタイプに対して起動するAFTER ROWトリガを実行します。

      If the target relation is a view with <literal>INSTEAD OF ROW</literal> triggers for the action's event type, they are used to perform the action instead. 対象リレーションがアクションのイベントタイプに対してINSTEAD OF ROWトリガを持つビューである場合、それらは代わりにアクションを実行するために使われます。

  3. Perform any <literal>AFTER STATEMENT</literal> triggers for actions specified, whether or not they actually occur. This is similar to the behavior of an <command>UPDATE</command> statement that modifies no rows. アクションが実際に発生するかどうかに関係なく、指定されたアクションに対してAFTER STATEMENTトリガを実行します。 これは、行を変更しないUPDATE文の動作に似ています。

In summary, statement triggers for an event type (say, <command>INSERT</command>) will be fired whenever we <emphasis>specify</emphasis> an action of that kind. In contrast, row-level triggers will fire only for the specific event type being <emphasis>executed</emphasis>. So a <command>MERGE</command> command might fire statement triggers for both <command>UPDATE</command> and <command>INSERT</command>, even though only <command>UPDATE</command> row triggers were fired. 要約するとイベントタイプの文トリガ(たとえば、INSERTなど)は、その種類のアクションを指定 するたびに起動されます。 対照的に、行レベルトリガは、実行される特定のイベントタイプに対してのみ起動されます。 したがって、MERGEコマンドでは、UPDATE行トリガのみが起動された場合でも、UPDATEINSERTの両方に対して文トリガを起動する可能性があります。

You should ensure that the join produces at most one candidate change row for each target row. In other words, a target row shouldn't join to more than one data source row. If it does, then only one of the candidate change rows will be used to modify the target row; later attempts to modify the row will cause an error. This can also occur if row triggers make changes to the target table and the rows so modified are then subsequently also modified by <command>MERGE</command>. If the repeated action is an <command>INSERT</command>, this will cause a uniqueness violation, while a repeated <command>UPDATE</command> or <command>DELETE</command> will cause a cardinality violation; the latter behavior is required by the <acronym>SQL</acronym> standard. This differs from historical <productname>PostgreSQL</productname> behavior of joins in <command>UPDATE</command> and <command>DELETE</command> statements where second and subsequent attempts to modify the same row are simply ignored. 結合では、各対象行に対して最大1つの変更候補行が生成されるようにする必要があります。 つまり、対象行は複数のデータソース行に結合できません。 結合する場合、変更候補行の1つだけが対象行の変更に使用されます。 後で行を変更しようとするとエラーが発生します。 これは、行トリガが対象テーブルを変更し、変更された行が後でMERGEによっても変更される場合にも発生する可能性があります。 繰り返されるアクションがINSERTの場合、一意性違反が発生しますが、UPDATEまたはDELETEを繰り返すとカーディナリティ違反が発生します。 後者の動作は標準SQLで要求されています。 これは、PostgreSQLUPDATEおよびDELETE文における結合の歴史的な動作とは異なります。 この動作では、2回目以降の同じ行の変更は単純に無視されます。

If a <literal>WHEN</literal> clause omits an <literal>AND</literal> sub-clause, it becomes the final reachable clause of that kind (<literal>MATCHED</literal>, <literal>NOT MATCHED BY SOURCE</literal>, or <literal>NOT MATCHED [BY TARGET]</literal>). If a later <literal>WHEN</literal> clause of that kind is specified it would be provably unreachable and an error is raised. If no final reachable clause is specified of either kind, it is possible that no action will be taken for a candidate change row. WHEN句でAND副句が省略された場合、その句はその種類の最終到達可能句(MATCHEDNOT MATCHED BY SOURCEまたはNOT MATCHED [BY TARGET])になります。 その種類の後のWHEN句が指定された場合、到達不能である可能性があり、エラーが発生します。 いずれの種類の最終到達可能句も指定されていない場合、候補変更行に対してアクションが実行されない可能性があります。

The order in which rows are generated from the data source is indeterminate by default. A <replaceable class="parameter">source_query</replaceable> can be used to specify a consistent ordering, if required, which might be needed to avoid deadlocks between concurrent transactions. デフォルトでは、データソースから行が生成される順序は不定です。 source_queryを使用して、必要に応じて一貫した順序を指定できます。これは、並行しているトランザクション間のデッドロックを回避するために必要になる場合があります。

When <command>MERGE</command> is run concurrently with other commands that modify the target table, the usual transaction isolation rules apply; see <xref linkend="transaction-iso"/> for an explanation on the behavior at each isolation level. You may also wish to consider using <command>INSERT ... ON CONFLICT</command> as an alternative statement which offers the ability to run an <command>UPDATE</command> if a concurrent <command>INSERT</command> occurs. There are a variety of differences and restrictions between the two statement types and they are not interchangeable. MERGEを対象テーブルを変更する他のコマンドと同時に実行すると、通常のトランザクション分離規則が適用されます。 各分離レベルでの動作の説明は13.2を参照してください。 また、INSERT ... ON CONFLICTを代替文として使用することも検討できます。 この文は、同時INSERTが発生した場合にUPDATEを実行する機能を提供します。 2つの文タイプの間には様々な違いや制限があり、相互に交換することはできません。

<title>Examples</title>

Perform maintenance on <literal>customer_accounts</literal> based upon new <literal>recent_transactions</literal>. 新規recent_transactionsに基づいて、customer_accountsのメンテナンスを実行します。

MERGE INTO customer_account ca
USING recent_transactions t
ON t.customer_id = ca.customer_id
WHEN MATCHED THEN
  UPDATE SET balance = balance + transaction_value
WHEN NOT MATCHED THEN
  INSERT (customer_id, balance)
  VALUES (t.customer_id, t.transaction_value);

Notice that this would be exactly equivalent to the following statement because the <literal>MATCHED</literal> result does not change during execution. MATCHEDの結果は実行中に変更されないため、これは次の文とまったく同じになることに注意してください。

MERGE INTO customer_account ca
USING (SELECT customer_id, transaction_value FROM recent_transactions) AS t
ON t.customer_id = ca.customer_id
WHEN MATCHED THEN
  UPDATE SET balance = balance + transaction_value
WHEN NOT MATCHED THEN
  INSERT (customer_id, balance)
  VALUES (t.customer_id, t.transaction_value);

Attempt to insert a new stock item along with the quantity of stock. If the item already exists, instead update the stock count of the existing item. Don't allow entries that have zero stock. Return details of all changes made. 在庫数量とともに新規在庫品目を挿入しようとします。 品目がすでに存在する場合は、既存品目の在庫数を更新します。 在庫数が0のエントリは許可しません。 実行されたすべての変更の詳細を返します。

MERGE INTO wines w
USING wine_stock_changes s
ON s.winename = w.winename
WHEN NOT MATCHED AND s.stock_delta > 0 THEN
  INSERT VALUES(s.winename, s.stock_delta)
WHEN MATCHED AND w.stock + s.stock_delta > 0 THEN
  UPDATE SET stock = w.stock + s.stock_delta
WHEN MATCHED THEN
  DELETE
RETURNING merge_action(), w.*;

The <literal>wine_stock_changes</literal> table might be, for example, a temporary table recently loaded into the database. wine_stock_changesテーブルは、たとえば、最近データベースにロードされた一時テーブルです。

Update <literal>wines</literal> based on a replacement wine list, inserting rows for any new stock, updating modified stock entries, and deleting any wines not present in the new list. 置換ワインリストに基づいてwinesを更新し、新しい在庫の行を挿入し、変更された在庫エントリを更新し、新しいリストにないワインを削除します。

MERGE INTO wines w
USING new_wine_list s
ON s.winename = w.winename
WHEN NOT MATCHED BY TARGET THEN
  INSERT VALUES(s.winename, s.stock)
WHEN MATCHED AND w.stock != s.stock THEN
  UPDATE SET stock = s.stock
WHEN NOT MATCHED BY SOURCE THEN
  DELETE;

互換性

<title>Compatibility</title>

This command conforms to the <acronym>SQL</acronym> standard. このコマンドは標準SQLに準拠しています。

The <literal>WITH</literal> clause, <literal>BY SOURCE</literal> and <literal>BY TARGET</literal> qualifiers to <literal>WHEN NOT MATCHED</literal>, <literal>DO NOTHING</literal> action, and <literal>RETURNING</literal> clause are extensions to the <acronym>SQL</acronym> standard. WITH句、WHEN NOT MATCHEDBY SOURCEおよびBY TARGET修飾子、DO NOTHINGアクションおよびRETURNING句は、標準SQLの拡張です。