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

INSERT

INSERT <refpurpose>create new rows in a table</refpurpose> — テーブルに新しい行を作成する

概要

[ WITH [ RECURSIVE ] with_query [, ...] ]
INSERT INTO table_name [ AS alias ] [ ( column_name [, ...] ) ]
    [ OVERRIDING { SYSTEM | USER } VALUE ]
    { DEFAULT VALUES | VALUES ( { expression | DEFAULT } [, ...] ) [, ...] | query }
    [ ON CONFLICT [ conflict_target ] conflict_action ]
    [ RETURNING * | output_expression [ [ AS ] output_name ] [, ...] ]


<phrase>where <replaceable class="parameter">conflict_target</replaceable> can be one of:</phrase>

ここでconflict_targetは以下のいずれかです。

    ( { index_column_name | ( index_expression ) } [ COLLATE collation ] [ opclass ] [, ...] ) [ WHERE index_predicate ]
    ON CONSTRAINT constraint_name


<phrase>and <replaceable class="parameter">conflict_action</replaceable> is one of:</phrase>

またconflict_actionは以下のいずれかです。

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

説明

<title>Description</title>

<command>INSERT</command> inserts new rows into a table. One can insert one or more rows specified by value expressions, or zero or more rows resulting from a query. INSERTはテーブルに新しい行を挿入します。 値式を使用して行(複数可)を挿入すること、および、問い合わせの結果を使って0行以上の行を挿入することができます。

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; or the first <replaceable>N</replaceable> column names, if there are only <replaceable>N</replaceable> columns supplied by the <literal>VALUES</literal> clause or <replaceable>query</replaceable>. The values supplied by the <literal>VALUES</literal> clause or <replaceable>query</replaceable> are associated with the explicit or implicit column list left-to-right. 対象の列名はどのような順番でも指定できます。 列名リストが指定されなかった場合は、テーブル内の全ての列を宣言時の順番に並べたものがデフォルトとして使われます。 また、VALUES句やqueryN列のみが与えられた場合は、先頭のN列の名前が指定されたものとみなされます。 VALUES句やqueryで提供される値は、明示的または暗黙的な列リストと左から右への順で関連付けられます。

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 expression for any column is not of the correct data type, automatic type conversion will be attempted. 各列の式が正しいデータ型でない場合は、自動的に型の変換が行われます。

<command>INSERT</command> into tables that lack unique indexes will not be blocked by concurrent activity. Tables with unique indexes might block if concurrent sessions perform actions that lock or modify rows matching the unique index values being inserted; the details are covered in <xref linkend="index-unique-checks"/>. <literal>ON CONFLICT</literal> can be used to specify an alternative action to raising a unique constraint or exclusion constraint violation error. (See <xref linkend="sql-on-conflict"/> below.) 一意インデックスのないテーブルへのINSERTは同時実行中の処理によりブロックされることはありません。 挿入される一意インデックスの値と一致する行をロックまたは修正する動作を同時実行中のセッションがしている場合には、一意インデックスのあるテーブルはブロックします。詳細は64.5で扱っています。 ON CONFLICTは一意制約または排他制約について、違反のエラーを発生させるのに代わる動作を指定するのに使うことができます。 (以下のON CONFLICT句を参照してください。)

The optional <literal>RETURNING</literal> clause causes <command>INSERT</command> to compute and return value(s) based on each row actually inserted (or updated, if an <literal>ON CONFLICT DO UPDATE</literal> clause was used). This is primarily useful for obtaining values that were supplied by defaults, such as a serial sequence number. However, any expression using the table's columns is allowed. The syntax of the <literal>RETURNING</literal> list is identical to that of the output list of <command>SELECT</command>. Only rows that were successfully inserted or updated will be returned. For example, if a row was locked but not updated because an <literal>ON CONFLICT DO UPDATE ... WHERE</literal> clause <replaceable class="parameter">condition</replaceable> was not satisfied, the row will not be returned. RETURNING句を指定すると、INSERTは実際に挿入された(あるいはON CONFLICT DO UPDATE句によって更新された)各行に基づいて計算された値を返すようになります。 これは、通番のシーケンス番号など、デフォルトで与えられた値を取り出す時に主に便利です。 しかし、そのテーブルの列を使用した任意の式を指定することができます。 RETURNINGリストの構文はSELECTの出力リストと同一です。 挿入または更新に成功した行だけが返されます。 例えば、行がロックされていて、ON CONFLICT DO UPDATE ... WHERE句の conditionが満たされなかったために更新されなかった行は返されません。

You must have <literal>INSERT</literal> privilege on a table in order to insert into it. If <literal>ON CONFLICT DO UPDATE</literal> is present, <literal>UPDATE</literal> privilege on the table is also required. テーブルに行を追加するには、そのテーブルに対してINSERT権限を持っている必要があります。 ON CONFLICT DO UPDATEがある場合は、テーブルのUPDATE権限も必要です。

If a column list is specified, you only need <literal>INSERT</literal> privilege on the listed columns. Similarly, when <literal>ON CONFLICT DO UPDATE</literal> is specified, you only need <literal>UPDATE</literal> privilege on the column(s) that are listed to be updated. However, <literal>ON CONFLICT DO UPDATE</literal> also requires <literal>SELECT</literal> privilege on any column whose values are read in the <literal>ON CONFLICT DO UPDATE</literal> expressions or <replaceable>condition</replaceable>. 列リストを指定する場合は、列挙された列に対するINSERT権限のみが必要です。 同様に、ON CONFLICT DO UPDATEが指定されている場合、更新対象として列挙されている列についてのみ、UPDATE権限が必要です。 しかし、ON CONFLICT DO UPDATEは、値がON CONFLICT DO UPDATE式あるいはconditionで読み取られるすべての列についてSELECT権限も必要です。

Use of the <literal>RETURNING</literal> clause requires <literal>SELECT</literal> privilege on all columns mentioned in <literal>RETURNING</literal>. If you use the <replaceable class="parameter">query</replaceable> clause to insert rows from a query, you of course need to have <literal>SELECT</literal> privilege on any table or column used in the query. RETURNING句を使用するには、RETURNINGで使用するすべての列に対するSELECT権限が必要です。 queryを使用して問い合わせ結果を元に行を挿入する場合は当然ながら、その問い合わせ内で使われる全てのテーブルまたは列に対してSELECT権限を持っている必要があります。

パラメータ

<title>Parameters</title>

挿入

<title>Inserting</title>

This section covers parameters that may be used when only inserting new rows. Parameters <emphasis>exclusively</emphasis> used with the <literal>ON CONFLICT</literal> clause are described separately. この節では新しい行を挿入するときにのみ使われるパラメータについて説明します。 ON CONFLICT句においてのみ使われるパラメータについては、別に説明します。

with_query

The <literal>WITH</literal> clause allows you to specify one or more subqueries that can be referenced by name in the <command>INSERT</command> query. See <xref linkend="queries-with"/> and <xref linkend="sql-select"/> for details. WITH句により、INSERT問い合わせ内で名前により参照することができる1つ以上の副問い合わせを指定することができます。 詳しくは7.8SELECTを参照してください。

It is possible for the <replaceable class="parameter">query</replaceable> (<command>SELECT</command> statement) to also contain a <literal>WITH</literal> clause. In such a case both sets of <replaceable>with_query</replaceable> can be referenced within the <replaceable class="parameter">query</replaceable>, but the second one takes precedence since it is more closely nested. querySELECT文)でもまた、WITH句を含めることができます。 こうした場合、with_queryの集合との両方をquery内で参照することができます。 しかし、第二の問い合わせがより近くにネストされているため優先します。

table_name

The name (optionally schema-qualified) of an existing table. 既存のテーブルの名前です(スキーマ修飾名も可)。

alias

A substitute name for <replaceable class="parameter">table_name</replaceable>. When an alias is provided, it completely hides the actual name of the table. This is particularly useful when <literal>ON CONFLICT DO UPDATE</literal> targets a table named <varname>excluded</varname>, since that will otherwise be taken as the name of the special table representing the row proposed for insertion. table_nameの代替名です。 aliasを指定すると、テーブルの実際の名前が完全に隠されます。 これは、excludedという名前のテーブルをON CONFLICT DO UPDATEが対象にしている場合、これを指定しなければ、それが挿入で処理される行を表現する特別なテーブルの名前とみなされるため、特に有用となります。

column_name

The name of a column in the table named by <replaceable class="parameter">table_name</replaceable>. 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.) When referencing a column with <literal>ON CONFLICT DO UPDATE</literal>, do not include the table's name in the specification of a target column. For example, <literal>INSERT INTO table_name ... ON CONFLICT DO UPDATE SET table_name.col = 1</literal> is invalid (this follows the general behavior for <command>UPDATE</command>). table_nameで指名されたテーブル内の列名です。 必要なら列名を副フィールドの名前や配列の添え字で修飾することができます。 (複合型の列の一部のフィールドのみを挿入すると他のフィールドはNULLになります。) ON CONFLICT DO UPDATEで列を参照する場合、対象列の指定にテーブル名を含めてはいけません。 例えば、INSERT INTO table_name ... ON CONFLICT DO UPDATE SET table_name.col = 1は無効です(これはUPDATEの一般的な動作に従います)。

OVERRIDING SYSTEM VALUE

If this clause is specified, then any values supplied for identity columns will override the default sequence-generated values. この句が指定されると、IDENTITY列について指定された値がシーケンスが生成したデフォルト値に優先します。

For an identity column defined as <literal>GENERATED ALWAYS</literal>, it is an error to insert an explicit value (other than <literal>DEFAULT</literal>) without specifying either <literal>OVERRIDING SYSTEM VALUE</literal> or <literal>OVERRIDING USER VALUE</literal>. (For an identity column defined as <literal>GENERATED BY DEFAULT</literal>, <literal>OVERRIDING SYSTEM VALUE</literal> is the normal behavior and specifying it does nothing, but <productname>PostgreSQL</productname> allows it as an extension.) GENERATED ALWAYSと定義されているIDENTITY列に対しては、OVERRIDING SYSTEM VALUEOVERRIDING USER VALUEを指定せずに(DEFAULT以外の)明示的な値を挿入するのはエラーです。 (GENERATED BY DEFAULTと定義されているIDENTITY列に対しては、OVERRIDING SYSTEM VALUEが通常の振る舞いであり、指定したとしても何もしませんが、PostgreSQLは拡張として許容します。)

OVERRIDING USER VALUE

If this clause is specified, then any values supplied for identity columns are ignored and the default sequence-generated values are applied. この句が指定されると、IDENTITY列について指定された値はすべて無視されて、シーケンスが生成したデフォルト値が適用されます。

This clause is useful for example when copying values between tables. Writing <literal>INSERT INTO tbl2 OVERRIDING USER VALUE SELECT * FROM tbl1</literal> will copy from <literal>tbl1</literal> all columns that are not identity columns in <literal>tbl2</literal> while values for the identity columns in <literal>tbl2</literal> will be generated by the sequences associated with <literal>tbl2</literal>. この句は例えばテーブル間で値をコピーする時に有用です。 INSERT INTO tbl2 OVERRIDING USER VALUE SELECT * FROM tbl1とすると、tbl1の列でtbl2のIDENTITY列でないものがすべてコピーされる一方、tbl2のIDENTITY列の値は、tbl2に紐付けられたシーケンスによって生成されます。

DEFAULT VALUES

All columns will be filled with their default values, as if <literal>DEFAULT</literal> were explicitly specified for each column. (An <literal>OVERRIDING</literal> clause is not permitted in this form.) 各列に対してDEFAULTが明示的に指定されたかのように、すべての列にそれぞれのデフォルト値が設定されます。 (OVERRIDINGはこの構文では使用できません。)

expression

An expression or value to assign to the corresponding column. 対応する列に代入する式または値を指定します。

DEFAULT

The corresponding column will be filled with its default value. An identity column will be filled with a new value generated by the associated sequence. For a generated column, specifying this is permitted but merely specifies the normal behavior of computing the column from its generation expression. 対応する列にデフォルト値を設定します。 IDENTITY列には関連付けられた列により新しく生成された値が書き込まれます。 生成列に対して、これを指定することは許されていますが、単に生成式から列を計算するという普通の振る舞いを指定するだけです。

query

A query (<command>SELECT</command> statement) that supplies the rows to be inserted. Refer to the <xref linkend="sql-select"/> statement for a description of the syntax. 挿入する行を提供する問い合わせ(SELECT文)を指定します。 構文の説明についてはSELECT文を参照してください。

output_expression

An expression to be computed and returned by the <command>INSERT</command> command after each row is inserted or updated. The expression can use any column names of the table named by <replaceable class="parameter">table_name</replaceable>. Write <literal>*</literal> to return all columns of the inserted or updated row(s). 各行が挿入または更新された後、INSERTにより計算され、返される式です。 この式にはtable_nameで指名されたテーブルの任意の列名を使用することができます。 挿入または更新された行のすべての列を返す場合は*と記載してください。

output_name

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

<refsect2 id="sql-on-conflict" xreflabel="ON CONFLICT Clause"> <title><literal>ON CONFLICT</literal> Clause</title>

ON CONFLICT

The optional <literal>ON CONFLICT</literal> clause specifies an alternative action to raising a unique violation or exclusion constraint violation error. For each individual row proposed for insertion, either the insertion proceeds, or, if an <emphasis>arbiter</emphasis> constraint or index specified by <parameter>conflict_target</parameter> is violated, the alternative <parameter>conflict_action</parameter> is taken. <literal>ON CONFLICT DO NOTHING</literal> simply avoids inserting a row as its alternative action. <literal>ON CONFLICT DO UPDATE</literal> updates the existing row that conflicts with the row proposed for insertion as its alternative action. オプションのON CONFLICT句では、一意制約や排他制約の違反について、エラーを発生させる代替となる動作を指定します。 挿入しようとされた各行について、挿入の処理が進められるか、あるいは、conflict_targetにより指定された競合制約またはインデックスに違反した場合の代替のconflict_actionが実行されるか、のいずれかです。 ON CONFLICT DO NOTHINGは代替の動作として、単に行の挿入をしなくなるだけです。 ON CONFLICT DO UPDATEは代替の動作として、挿入されようとしていた行と競合する既存の行を更新します。

<parameter>conflict_target</parameter> can perform <emphasis>unique index inference</emphasis>. When performing inference, it consists of one or more <replaceable class="parameter">index_column_name</replaceable> columns and/or <replaceable class="parameter">index_expression</replaceable> expressions, and an optional <replaceable class="parameter">index_predicate</replaceable>. All <replaceable class="parameter">table_name</replaceable> unique indexes that, without regard to order, contain exactly the <parameter>conflict_target</parameter>-specified columns/expressions are inferred (chosen) as arbiter indexes. If an <replaceable class="parameter">index_predicate</replaceable> is specified, it must, as a further requirement for inference, satisfy arbiter indexes. Note that this means a non-partial unique index (a unique index without a predicate) will be inferred (and thus used by <literal>ON CONFLICT</literal>) if such an index satisfying every other criteria is available. If an attempt at inference is unsuccessful, an error is raised. conflict_target一意インデックスの推定を実行することができます。 推定を実行するとき、それは1つ以上のindex_column_name列、またはindex_expression式、あるいはその両方、およびオプションでindex_predicateから構成されます。 table_nameの一意インデックスでconflict_targetで指定された列と式を(順序は関係なく)正確に含むものは、すべて競合解決インデックスとして推定されます(選ばれます)。 index_predicateが指定されている場合は、推定のさらなる条件として、それは競合解決インデックスを満たさなければなりません。 これは、部分インデックスでない一意インデックス(述語のない一意インデックス)は、それが他のすべての条件を満たすのであれば推定される(従ってON CONFLICTで使用される)ことを意味することに注意して下さい。 推定に失敗した時は、エラーが発生します。

<literal>ON CONFLICT DO UPDATE</literal> guarantees an atomic <command>INSERT</command> or <command>UPDATE</command> outcome; provided there is no independent error, one of those two outcomes is guaranteed, even under high concurrency. This is also known as <firstterm>UPSERT</firstterm> &mdash; <quote>UPDATE or INSERT</quote>. ON CONFLICT DO UPDATEINSERTまたはUPDATEの原子的な結果を保証します。 無関係のエラーが発生しなければ、多数の同時実行がある状況においてさえも、それら2つの結果のうちの1つになります。 これはUPSERT、つまりUPDATE or INSERTとしても知られています。

conflict_target

Specifies which conflicts <literal>ON CONFLICT</literal> takes the alternative action on by choosing <firstterm>arbiter indexes</firstterm>. Either performs <emphasis>unique index inference</emphasis>, or names a constraint explicitly. For <literal>ON CONFLICT DO NOTHING</literal>, it is optional to specify a <parameter>conflict_target</parameter>; when omitted, conflicts with all usable constraints (and unique indexes) are handled. For <literal>ON CONFLICT DO UPDATE</literal>, a <parameter>conflict_target</parameter> <emphasis>must</emphasis> be provided. ON CONFLICT競合解決インデックスを選ぶことで代替の動作をするときの競合を指定します。 一意インデックスの推定を実行するか、あるいは制約を明示的に指定するかのいずれかです。 ON CONFLICT DO NOTHINGではconflict_targetを指定するのはオプションです。 省略すると、利用可能なすべての制約(および一意インデックス)との競合が処理されます。 ON CONFLICT DO UPDATEではconflict_targetを指定しなければなりません

conflict_action

<parameter>conflict_action</parameter> specifies an alternative <literal>ON CONFLICT</literal> action. It can be either <literal>DO NOTHING</literal>, or a <literal>DO UPDATE</literal> clause specifying the exact details of the <literal>UPDATE</literal> action to be performed in case of a conflict. The <literal>SET</literal> and <literal>WHERE</literal> clauses in <literal>ON CONFLICT DO UPDATE</literal> have access to the existing row using the table's name (or an alias), and to the row proposed for insertion using the special <varname>excluded</varname> table. <literal>SELECT</literal> privilege is required on any column in the target table where corresponding <varname>excluded</varname> columns are read. conflict_actionではON CONFLICTの代替の動作を指定します。 これはDO NOTHINGあるいはDO UPDATE句のいずれかをとることができ、後者では競合が発生した場合に実行されるUPDATEの動作の正確な詳細を記述します。 ON CONFLICT DO UPDATESET句とWHEREは既存の行にテーブルの名前(または別名)を使ってアクセスでき、また挿入されようとしていた行には、特別なexcludedテーブルを使ってアクセスできます。 excludedの列を読み取るときには、対象テーブルの対応する列のSELECT権限が必要です。

Note that the effects of all per-row <literal>BEFORE INSERT</literal> triggers are reflected in <varname>excluded</varname> values, since those effects may have contributed to the row being excluded from insertion. すべての行レベルのBEFORE INSERTトリガーの結果がexcludedの値に反映されることに注意して下さい。 これらの結果として、行が挿入から除外されることになったかもしれないからです。

index_column_name

The name of a <replaceable class="parameter">table_name</replaceable> column. Used to infer arbiter indexes. Follows <command>CREATE INDEX</command> format. <literal>SELECT</literal> privilege on <replaceable class="parameter">index_column_name</replaceable> is required. table_nameの列の名前です。 競合解決インデックスを推定するのに使われます。 CREATE INDEXの形式に従います。 index_column_nameSELECTが必要です。

index_expression

Similar to <replaceable class="parameter">index_column_name</replaceable>, but used to infer expressions on <replaceable class="parameter">table_name</replaceable> columns appearing within index definitions (not simple columns). Follows <command>CREATE INDEX</command> format. <literal>SELECT</literal> privilege on any column appearing within <replaceable class="parameter">index_expression</replaceable> is required. index_column_nameと似ていますが、インデックスの定義に現れるtable_nameの列の式(単純な列ではない)の推定に使われます。 CREATE INDEXの形式に従います。 index_expressionに現れるすべての列のSELECT権限が必要です。

collation

When specified, mandates that corresponding <replaceable class="parameter">index_column_name</replaceable> or <replaceable class="parameter">index_expression</replaceable> use a particular collation in order to be matched during inference. Typically this is omitted, as collations usually do not affect whether or not a constraint violation occurs. Follows <command>CREATE INDEX</command> format. これを指定すると、推定時に、対応するindex_column_nameあるいはindex_expressionをマッチさせるときに、特定の照合順序を指定することになります。 普通は照合順序は制約違反が発生するかどうかに関係しないので、通常は省略されます。 CREATE INDEXの形式に従います。

opclass

When specified, mandates that corresponding <replaceable class="parameter">index_column_name</replaceable> or <replaceable class="parameter">index_expression</replaceable> use particular operator class in order to be matched during inference. Typically this is omitted, as the <emphasis>equality</emphasis> semantics are often equivalent across a type's operator classes anyway, or because it's sufficient to trust that the defined unique indexes have the pertinent definition of equality. Follows <command>CREATE INDEX</command> format. これを指定すると、推定時に、対応するindex_column_nameあるいはindex_expressionをマッチさせるときに、特定の演算子クラスを指定することになります。 等価の意味は、いずれにせよ、型の演算子クラスをまたがって同等であることが多いですし、また定義された一意インデックスは等価を適切に定義していると信頼すれば十分なので、通常はこれは省略されます。 CREATE INDEXの形式に従います。

index_predicate

Used to allow inference of partial unique indexes. Any indexes that satisfy the predicate (which need not actually be partial indexes) can be inferred. Follows <command>CREATE INDEX</command> format. <literal>SELECT</literal> privilege on any column appearing within <replaceable class="parameter">index_predicate</replaceable> is required. 部分一意インデックスの推定を可能にします。 述語を満たすすべてのインデックス(実際に部分インデックスである必要はありません)は推定可能になります。 CREATE INDEXの形式に従います。 index_predicateに現れるすべての列についてSELECT権限が必要です。

constraint_name

Explicitly specifies an arbiter <emphasis>constraint</emphasis> by name, rather than inferring a constraint or index. 競合解決の制約を制約やインデックスの推定によるのではなく、明示的に名前で指定します。

condition

An expression that returns a value of type <type>boolean</type>. Only rows for which this expression returns <literal>true</literal> will be updated, although all rows will be locked when the <literal>ON CONFLICT DO UPDATE</literal> action is taken. Note that <replaceable>condition</replaceable> is evaluated last, after a conflict has been identified as a candidate to update. boolean型の値を返す式です。 この式がtrueを返す行のみが更新されます。 ただし、ON CONFLICT DO UPDATEの動作が行われるときは、すべての行がロックされます。 conditionは最後に評価される、競合が更新対象候補として特定された後であることに注意して下さい。

Note that exclusion constraints are not supported as arbiters with <literal>ON CONFLICT DO UPDATE</literal>. In all cases, only <literal>NOT DEFERRABLE</literal> constraints and unique indexes are supported as arbiters. 排他制約はON CONFLICT DO UPDATEの競合解決としてはサポートされないことに注意して下さい。 すべての場合について、NOT DEFERRABLEである制約と一意インデックスのみが競合解決としてサポートされます。

<command>INSERT</command> with an <literal>ON CONFLICT DO UPDATE</literal> clause is a <quote>deterministic</quote> statement. This means that the command will not be allowed to affect any single existing row more than once; a cardinality violation error will be raised when this situation arises. Rows proposed for insertion should not duplicate each other in terms of attributes constrained by an arbiter index or constraint. ON CONFLICT DO UPDATE句のあるINSERT決定論的な文です。 これは、そのコマンドが既存のどの行に対しても、2回以上影響を与えることが許されない、ということを意味します。 これに反する状況が発生した時は、カーディナリティ違反のエラーが発生します。 挿入されようとする行は、競合解決インデックスあるいは制約により制限される属性の観点で、複製されてはなりません。

Note that it is currently not supported for the <literal>ON CONFLICT DO UPDATE</literal> clause of an <command>INSERT</command> applied to a partitioned table to update the partition key of a conflicting row such that it requires the row be moved to a new partition. パーティションテーブルに適用されたINSERTON CONFLICT DO UPDATE句に対しては、その行を新しいパーティションに移動する必要のあるような競合する行のパーティションキーを更新することは現在サポートされていないことに注意してください。

ヒント

It is often preferable to use unique index inference rather than naming a constraint directly using <literal>ON CONFLICT ON CONSTRAINT</literal> <replaceable class="parameter"> constraint_name</replaceable>. Inference will continue to work correctly when the underlying index is replaced by another more or less equivalent index in an overlapping way, for example when using <literal>CREATE UNIQUE INDEX ... CONCURRENTLY</literal> before dropping the index being replaced. ON CONFLICT ON CONSTRAINT constraint_nameを使って制約を直接指定するより、一意インデックスの推定を使う方が望ましいことが多いです。 背景にあるインデックスが、他のほぼ同等のインデックスと重なり合う形で置換されるとき、推定は正しく動作し続けます。 例えば、置換されるインデックスを削除する前にCREATE UNIQUE INDEX ... CONCURRENTLYを使う場合です。

出力

<title>Outputs</title>

On successful completion, an <command>INSERT</command> command returns a command tag of the form 正常に終了すると、INSERTは以下のようなコマンドタグを返します。

INSERT oid count

The <replaceable class="parameter">count</replaceable> is the number of rows inserted or updated. <replaceable>oid</replaceable> is always 0 (it used to be the <acronym>OID</acronym> assigned to the inserted row if <replaceable>count</replaceable> was exactly one and the target table was declared <literal>WITH OIDS</literal> and 0 otherwise, but creating a table <literal>WITH OIDS</literal> is not supported anymore). countは挿入または更新された行数です。 oidは常に0です(countが正確に1であり、対象のテーブルがWITH OIDSと宣言されていた場合、挿入された行にOIDが、そうでなければ0が割り当てられていましたが、WITH OIDSでテーブルを作成することは今はもうサポートされていません)。

If the <command>INSERT</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 or updated by the command. INSERTコマンドがRETURNING句を持つ場合、その結果は、RETURNINGリストで定義した列と値を持ち、そのコマンドで挿入または更新された行全体に対して計算を行うSELECT文の結果と似たものになるでしょう。

注釈

<title>Notes</title>

If the specified table is a partitioned table, each row is routed to the appropriate partition and inserted into it. If the specified table is a partition, an error will occur if one of the input rows violates the partition constraint. 指定したテーブルがパーティションテーブルの場合、各行は適切なパーティションに回され、そちらに挿入されます。 指定したテーブルがパーティションの場合、挿入行にパーティションの制約に違反するものがあれば、エラーが発生します。

You may also wish to consider using <command>MERGE</command>, since that allows mixing <command>INSERT</command>, <command>UPDATE</command>, and <command>DELETE</command> within a single statement. See <xref linkend="sql-merge"/>. MERGEを使用すると、単一の文内でINSERTUPDATEDELETEを混在させることができます。 MERGEを参照してください。

<title>Examples</title>

Insert a single row into table <literal>films</literal>: filmsテーブルに1行を挿入します。

INSERT INTO films VALUES
    ('UA502', 'Bananas', 105, '1971-07-13', 'Comedy', '82 minutes');

In this example, the <literal>len</literal> column is omitted and therefore it will have the default value: 次の例では、len列を省略しています。 したがって、ここにはデフォルト値が入ります。

INSERT INTO films (code, title, did, date_prod, kind)
    VALUES ('T_601', 'Yojimbo', 106, '1961-06-16', 'Drama');

This example uses the <literal>DEFAULT</literal> clause for the date columns rather than specifying a value: 次の例では、日付列に対して値を指定する代わりにDEFAULTを使用します。

INSERT INTO films VALUES
    ('UA502', 'Bananas', 105, DEFAULT, 'Comedy', '82 minutes');
INSERT INTO films (code, title, did, date_prod, kind)
    VALUES ('T_601', 'Yojimbo', 106, DEFAULT, 'Drama');

To insert a row consisting entirely of default values: 全てデフォルト値からなる行を挿入します。

INSERT INTO films DEFAULT VALUES;

To insert multiple rows using the multirow <command>VALUES</command> syntax: 複数行のVALUES構文を使用して複数行を挿入します。

INSERT INTO films (code, title, did, date_prod, kind) VALUES
    ('B6717', 'Tampopo', 110, '1985-02-10', 'Comedy'),
    ('HG120', 'The Dinner Game', 140, DEFAULT, 'Comedy');

This example inserts some rows into table <literal>films</literal> from a table <literal>tmp_films</literal> with the same column layout as <literal>films</literal>: 次の例では、filmsテーブルと同じ列レイアウトを持つtmp_filmsテーブルからfilmsテーブルへいくつか行を挿入します。

INSERT INTO films SELECT * FROM tmp_films WHERE date_prod < '2004-05-07';

This example inserts into array columns: 次の例では、配列型の列に挿入します。


&#45;- Create an empty 3x3 gameboard for noughts-and-crosses

-- 三目並べ用の3×3マスのゲーム盤を作成します。
INSERT INTO tictactoe (game, board[1:3][1:3])
    VALUES (1, '{{" "," "," "},{" "," "," "},{" "," "," "}}');

&#45;- The subscripts in the above example aren't really needed

--上の例の添え字は本当は必要ありません。
INSERT INTO tictactoe (game, board)
    VALUES (2, '{{X," "," "},{" ",O," "},{" ",X," "}}');

Insert a single row into table <literal>distributors</literal>, returning the sequence number generated by the <literal>DEFAULT</literal> clause: distributorsテーブルに一行を挿入し、そのDEFAULT句により生成されたシーケンス番号を返します。

INSERT INTO distributors (did, dname) VALUES (DEFAULT, 'XYZ Widgets')
   RETURNING did;

Increment the sales count of the salesperson who manages the account for Acme Corporation, and record the whole updated row along with current time in a log table: Acme社の顧客を担当する営業担当者の売り上げ数を増やし、ログテーブルに更新行全体と更新時刻を記録します。

WITH upd AS (
  UPDATE employees SET sales_count = sales_count + 1 WHERE id =
    (SELECT sales_person FROM accounts WHERE name = 'Acme Corporation')
    RETURNING *
)
INSERT INTO employees_log SELECT *, current_timestamp FROM upd;

Insert or update new distributors as appropriate. Assumes a unique index has been defined that constrains values appearing in the <literal>did</literal> column. Note that the special <varname>excluded</varname> table is used to reference values originally proposed for insertion: 新しい販売店(distributors)を適切に挿入または更新します。 did列に現れる値を制限する一意インデックスが定義されているものとします。 元々挿入されようとしていた値を参照するために、特別なexcludedテーブルが使用されていることに注意して下さい。

INSERT INTO distributors (did, dname)
    VALUES (5, 'Gizmo Transglobal'), (6, 'Associated Computing, Inc')
    ON CONFLICT (did) DO UPDATE SET dname = EXCLUDED.dname;

Insert a distributor, or do nothing for rows proposed for insertion when an existing, excluded row (a row with a matching constrained column or columns after before row insert triggers fire) exists. Example assumes a unique index has been defined that constrains values appearing in the <literal>did</literal> column: 販売店を挿入するか、あるいは挿入しようとした行について既存の除外行(before insertの行トリガを実行した後で制約列にマッチした行)がある場合は何もしません。 例ではdid列に現れる値を制限する一意インデックスがあるものとしています。

INSERT INTO distributors (did, dname) VALUES (7, 'Redline GmbH')
    ON CONFLICT (did) DO NOTHING;

Insert or update new distributors as appropriate. Example assumes a unique index has been defined that constrains values appearing in the <literal>did</literal> column. <literal>WHERE</literal> clause is used to limit the rows actually updated (any existing row not updated will still be locked, though): 新しい販売店を適切に挿入または更新します。 例ではdid列に現れる値を制限する一意インデックスがあるものとしています。 実際に更新される行を制限するためにWHERE句が使われています(ただし、更新されない既存の行もすべてロックされます)。


&#45;- Don't update existing distributors based in a certain ZIP code

-- 特定の郵便番号については既存の販売店を更新しません
INSERT INTO distributors AS d (did, dname) VALUES (8, 'Anvil Distribution')
    ON CONFLICT (did) DO UPDATE
    SET dname = EXCLUDED.dname || ' (formerly ' || d.dname || ')'
    WHERE d.zipcode <> '21201';


&#45;- Name a constraint directly in the statement (uses associated
&#45;- index to arbitrate taking the DO NOTHING action)

-- 文中で制約を直接指定します(DO NOTHINGの動作をする競合解決のため
-- 関連するインデックスを指定します)
INSERT INTO distributors (did, dname) VALUES (9, 'Antwerp Design')
    ON CONFLICT ON CONSTRAINT distributors_pkey DO NOTHING;

Insert new distributor if possible; otherwise <literal>DO NOTHING</literal>. Example assumes a unique index has been defined that constrains values appearing in the <literal>did</literal> column on a subset of rows where the <literal>is_active</literal> Boolean column evaluates to <literal>true</literal>: 可能であれば新しい販売店を挿入しますが、できないときはDO NOTHINGとします。 この例では、is_activeという論理値の列がtrueである行という条件で、did列に一意インデックスが定義されているものとしています。


&#45;- This statement could infer a partial unique index on "did"
&#45;- with a predicate of "WHERE is_active", but it could also
&#45;- just use a regular unique constraint on "did"

-- この文は"WHERE is_active"という述語を使って、部分インデックスを
-- 推定できますが、単に"did"上の通常の一意制約を使うこともできます
INSERT INTO distributors (did, dname) VALUES (10, 'Conrad International')
    ON CONFLICT (did) WHERE is_active DO NOTHING;

互換性

<title>Compatibility</title>

<command>INSERT</command> conforms to the SQL standard, except that the <literal>RETURNING</literal> clause is a <productname>PostgreSQL</productname> extension, as is the ability to use <literal>WITH</literal> with <command>INSERT</command>, and the ability to specify an alternative action with <literal>ON CONFLICT</literal>. Also, the case in which a column name list is omitted, but not all the columns are filled from the <literal>VALUES</literal> clause or <replaceable>query</replaceable>, is disallowed by the standard. If you prefer a more SQL standard conforming statement than <literal>ON CONFLICT</literal>, see <xref linkend="sql-merge"/>. INSERTは標準SQLに準拠します。 ただし、RETURNING句、INSERTWITHが可能であること、ON CONFLICTで代替の動作を指定できることはPostgreSQLの拡張です。 また、標準SQLでは、列名リストが省略された時に、VALUES句またはqueryで一部の列のみを指定することはできません。 ON CONFLICTよりも標準SQLにより準拠した文がお望みであれば、MERGEを参照してください。

The SQL standard specifies that <literal>OVERRIDING SYSTEM VALUE</literal> can only be specified if an identity column that is generated always exists. PostgreSQL allows the clause in any case and ignores it if it is not applicable. 標準SQLでは、必ず値を生成するIDENTITY列が存在する場合にのみOVERRIDING SYSTEM VALUEを指定できるとしています。 PostgreSQLではこの句はどのような場合でも指定でき、それが適用できないときには無視します。

Possible limitations of the <replaceable class="parameter">query</replaceable> clause are documented under <xref linkend="sql-select"/>. query句の制限については、SELECTにて記述されています。