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

CREATE TRIGGER

CREATE TRIGGER <refpurpose>define a new trigger</refpurpose> — 新しいトリガを定義する

概要

CREATE [ OR REPLACE ] [ CONSTRAINT ] TRIGGER name { BEFORE | AFTER | INSTEAD OF } { event [ OR ... ] }
    ON table_name
    [ FROM referenced_table_name ]
    [ NOT DEFERRABLE | [ DEFERRABLE ] [ INITIALLY IMMEDIATE | INITIALLY DEFERRED ] ]
    [ REFERENCING { { OLD | NEW } TABLE [ AS ] transition_relation_name } [ ... ] ]
    [ FOR [ EACH ] { ROW | STATEMENT } ]
    [ WHEN ( condition ) ]
    EXECUTE { FUNCTION | PROCEDURE } function_name ( arguments )


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


ここでeventは以下のいずれかを取ることができます。


    INSERT
    UPDATE [ OF column_name [, ... ] ]
    DELETE
    TRUNCATE

説明

<title>Description</title>

<command>CREATE TRIGGER</command> creates a new trigger. <command>CREATE OR REPLACE TRIGGER</command> will either create a new trigger, or replace an existing trigger. The trigger will be associated with the specified table, view, or foreign table and will execute the specified function <replaceable class="parameter">function_name</replaceable> when certain operations are performed on that table. CREATE TRIGGERは新しいトリガを作成します。 CREATE OR REPLACE TRIGGERは新しいトリガを作成、または、既存のトリガを置き換えます。 作成したトリガは指定したテーブル、ビューまたは外部テーブルと関連付けられ、そのテーブルに特定の操作が行われた時に指定した関数function_nameを実行します。

To replace the current definition of an existing trigger, use <command>CREATE OR REPLACE TRIGGER</command>, specifying the existing trigger's name and parent table. All other properties are replaced. 既存トリガの現在の定義を置き換えるには、既存のトリガ名と親テーブルを指定してCREATE OR REPLACE TRIGGERを使用してください。 その他の属性はすべて置き換えられます。

The trigger can be specified to fire before the operation is attempted on a row (before constraints are checked and the <command>INSERT</command>, <command>UPDATE</command>, or <command>DELETE</command> is attempted); or after the operation has completed (after constraints are checked and the <command>INSERT</command>, <command>UPDATE</command>, or <command>DELETE</command> has completed); or instead of the operation (in the case of inserts, updates or deletes on a view). If the trigger fires before or instead of the event, the trigger can skip the operation for the current row, or change the row being inserted (for <command>INSERT</command> and <command>UPDATE</command> operations only). If the trigger fires after the event, all changes, including the effects of other triggers, are <quote>visible</quote> to the trigger. トリガでは、起動のタイミングとして、行への操作が開始される前(制約条件のチェックとINSERTUPDATEまたはDELETEが行われる前)、操作が完了した後(制約条件がチェックされ、INSERTUPDATEまたはDELETEが完了した後)、操作の代わり(ビューにおける挿入、更新、削除の場合)のいずれかを指定することができます。 イベントの前または代わりにトリガが起動する場合、そのトリガは対象行に対する操作を省略したり、(INSERTUPDATEの操作時のみ)挿入する行を変更したりすることができます。 イベントの後にトリガが起動する場合、他のトリガの影響を含む全ての変更が、トリガに対して可視状態となります。

A trigger that is marked <literal>FOR EACH ROW</literal> is called once for every row that the operation modifies. For example, a <command>DELETE</command> that affects 10 rows will cause any <literal>ON DELETE</literal> triggers on the target relation to be called 10 separate times, once for each deleted row. In contrast, a trigger that is marked <literal>FOR EACH STATEMENT</literal> only executes once for any given operation, regardless of how many rows it modifies (in particular, an operation that modifies zero rows will still result in the execution of any applicable <literal>FOR EACH STATEMENT</literal> triggers). FOR EACH ROW付きのトリガは、その操作によって変更される行ごとに1回ずつ呼び出されます。 例えば、10行に影響を与えるDELETE操作は、対象リレーション上のすべてのON DELETEトリガを、削除される各行について1回ずつ、個別に10回呼び出すことになります。 反対に、FOR EACH STATEMENT付きのトリガは、その操作によって何行変更されたかにかかわらず、任意の操作ごとに1回のみ実行されます (変更対象が0行となる操作でも、適用できるすべてのFOR EACH STATEMENTトリガが実行されます)。

Triggers that are specified to fire <literal>INSTEAD OF</literal> the trigger event must be marked <literal>FOR EACH ROW</literal>, and can only be defined on views. <literal>BEFORE</literal> and <literal>AFTER</literal> triggers on a view must be marked as <literal>FOR EACH STATEMENT</literal>. トリガイベントのINSTEAD OFとして発行されるように指定されたトリガはFOR EACH ROW印を付けなければなりません。 またビュー上にのみ定義することができます。 ビューに対するBEFOREおよびAFTERトリガはFOR EACH STATEMENT印を付けなければなりません。

In addition, triggers may be defined to fire for <command>TRUNCATE</command>, though only <literal>FOR EACH STATEMENT</literal>. さらに、FOR EACH STATEMENTのみですが、トリガをTRUNCATEに対して発行するように定義することができます。

The following table summarizes which types of triggers may be used on tables, views, and foreign tables: 以下の表にどの種類のトリガがテーブル、ビュー、外部テーブルに対して使用できるかをまとめます。

いつイベント行レベル文レベル
BEFOREINSERT/UPDATE/DELETEテーブルおよび外部テーブルテーブル、ビューおよび外部テーブル
TRUNCATEテーブルおよび外部テーブル
AFTERINSERT/UPDATE/DELETEテーブルおよび外部テーブルテーブル、ビューおよび外部テーブル
TRUNCATEテーブルおよび外部テーブル
INSTEAD OFINSERT/UPDATE/DELETEビュー
TRUNCATE

Also, a trigger definition can specify a Boolean <literal>WHEN</literal> condition, which will be tested to see whether the trigger should be fired. In row-level triggers the <literal>WHEN</literal> condition can examine the old and/or new values of columns of the row. Statement-level triggers can also have <literal>WHEN</literal> conditions, although the feature is not so useful for them since the condition cannot refer to any values in the table. またトリガ定義では、論理値のWHEN条件を指定することができ、これによってトリガを発行すべきかどうかが判定されます。 行レベルのトリガでは、WHEN条件は行の列の古い値、新しい値、またはその両方で検証することができます。 文レベルのトリガでもWHEN条件を持たせることができますが、条件としてテーブル内のどの値も参照することができませんので、この機能はあまり有用ではありません

If multiple triggers of the same kind are defined for the same event, they will be fired in alphabetical order by name. 同一イベントに同じ種類の複数のトリガが定義された場合、名前のアルファベット順で実行されます。

When the <literal>CONSTRAINT</literal> option is specified, this command creates a <firstterm>constraint trigger</firstterm>.<indexterm><primary>trigger</primary> <secondary>constraint trigger</secondary></indexterm> This is the same as a regular trigger except that the timing of the trigger firing can be adjusted using <link linkend="sql-set-constraints"><command>SET CONSTRAINTS</command></link>. Constraint triggers must be <literal>AFTER ROW</literal> triggers on plain tables (not foreign tables). They can be fired either at the end of the statement causing the triggering event, or at the end of the containing transaction; in the latter case they are said to be <firstterm>deferred</firstterm>. A pending deferred-trigger firing can also be forced to happen immediately by using <command>SET CONSTRAINTS</command>. Constraint triggers are expected to raise an exception when the constraints they implement are violated. CONSTRAINTオプションが指定された場合、このコマンドは制約トリガを作成します。 これは、SET CONSTRAINTSを使用してトリガを発行するタイミングを調整することができるという点を除き、通常のトリガと同じです。 制約トリガは(外部テーブルではない)普通のテーブルのAFTER ROWトリガでなければなりません。 トリガイベントを引き起こした文の最後、またはそれを含むトランザクションの最後のいずれかで発行することができます。 後者の場合、遅延と呼ばれます。 SET CONSTRAINTSを使用することで、強制的に待機中の遅延トリガの発行を即座に行わせることができます。 制約トリガは、実装する制約に違反した時に例外を発生するものと想定されています。

The <literal>REFERENCING</literal> option enables collection of <firstterm>transition relations</firstterm>, which are row sets that include all of the rows inserted, deleted, or modified by the current SQL statement. This feature lets the trigger see a global view of what the statement did, not just one row at a time. This option is only allowed for an <literal>AFTER</literal> trigger that is not a constraint trigger; also, if the trigger is an <literal>UPDATE</literal> trigger, it must not specify a <replaceable class="parameter">column_name</replaceable> list. <literal>OLD TABLE</literal> may only be specified once, and only for a trigger that can fire on <literal>UPDATE</literal> or <literal>DELETE</literal>; it creates a transition relation containing the <firstterm>before-images</firstterm> of all rows updated or deleted by the statement. Similarly, <literal>NEW TABLE</literal> may only be specified once, and only for a trigger that can fire on <literal>UPDATE</literal> or <literal>INSERT</literal>; it creates a transition relation containing the <firstterm>after-images</firstterm> of all rows updated or inserted by the statement. REFERENCINGオプションは遷移リレーションの収集を有効にします。 遷移リレーションとは現在のSQL文によって挿入、削除または修正されたすべての行を含む行集合です。 この機能により、トリガはSQL文によって行われたことを、一度に1行ずつだけではなく、全体のビューとして参照することができます。 このオプションは、制約トリガではないAFTERトリガについてのみ使うことができます。 また、トリガがUPDATEトリガの場合、column_nameのリストを指定してはいけません。 OLD TABLEは一度だけ指定することができ、UPDATEまたはDELETEのときに実行されるトリガにのみ指定できます。 これは文によって更新または削除されるすべての行の更新前イメージを含む遷移リレーションを作成します。 同様に、NEW TABLEは一度だけ指定することができ、UPDATEまたはINSERTのときに実行されるトリガにのみ指定できます。 これは、文によって更新または挿入されるすべての行の更新後イメージを含む遷移リレーションを作成します。

<command>SELECT</command> does not modify any rows so you cannot create <command>SELECT</command> triggers. Rules and views may provide workable solutions to problems that seem to need <command>SELECT</command> triggers. SELECTはまったく行を変更しないため、SELECTトリガを作成することはできません。 SELECTトリガが必要に見える問題には、ルールやビューが現実的な解決策を提供できるでしょう。

Refer to <xref linkend="triggers"/> for more information about triggers. トリガに関するより詳細については、第39章を参照してください。

パラメータ

<title>Parameters</title>
name

The name to give the new trigger. This must be distinct from the name of any other trigger for the same table. The name cannot be schema-qualified &mdash; the trigger inherits the schema of its table. For a constraint trigger, this is also the name to use when modifying the trigger's behavior using <command>SET CONSTRAINTS</command>. 新しいトリガに付与する名前です。 同じテーブルの他のトリガと異なる名前にする必要があります。 名前をスキーマ修飾することはできません。 トリガはそのテーブルのスキーマを引き継ぎます。 制約トリガの場合、この名前がSET CONSTRAINTSを使用してトリガの動作を変更する時に使用されます。

BEFORE
AFTER
INSTEAD OF

Determines whether the function is called before, after, or instead of the event. A constraint trigger can only be specified as <literal>AFTER</literal>. 関数の呼び出しをイベントの前に行うか後に行うか、それとも代替として行うかを決定します。 制約トリガではAFTERとしてしか指定することができません。

event

One of <literal>INSERT</literal>, <literal>UPDATE</literal>, <literal>DELETE</literal>, or <literal>TRUNCATE</literal>; this specifies the event that will fire the trigger. Multiple events can be specified using <literal>OR</literal>, except when transition relations are requested. INSERTUPDATEDELETETRUNCATEのいずれかが入ります。 このパラメータは、トリガを起動するイベントを指定します。 遷移リレーションが要求される場合を除き、ORを使用して、複数のイベントを指定することができます。

For <literal>UPDATE</literal> events, it is possible to specify a list of columns using this syntax: UPDATEイベントでは、以下の構文を使用して列リストを指定することができます。

UPDATE OF column_name1 [, column_name2 ... ]

The trigger will only fire if at least one of the listed columns is mentioned as a target of the <command>UPDATE</command> command or if one of the listed columns is a generated column that depends on a column that is the target of the <command>UPDATE</command>. このトリガは、UPDATEコマンドの対象として列挙された列のいずれか少なくとも1つの列が指定された場合に、もしくは列挙された列の1つがUPDATEの対象の列に依存する生成列である場合に、発行されます。

<literal>INSTEAD OF UPDATE</literal> events do not allow a list of columns. A column list cannot be specified when requesting transition relations, either. INSTEAD OF UPDATEイベントでは列リストを使用できません。 遷移リレーションを要求する場合も列リストを指定することはできません。

table_name

The name (optionally schema-qualified) of the table, view, or foreign table the trigger is for. トリガを作成するテーブル、ビューまたは外部テーブルの名前です(スキーマ修飾名も可)。

referenced_table_name

The (possibly schema-qualified) name of another table referenced by the constraint. This option is used for foreign-key constraints and is not recommended for general use. This can only be specified for constraint triggers. 制約で参照される他のテーブルの名前(スキーマ修飾可)です。 このオプションは外部キー制約で使用されるものであり、一般利用を推奨しません。 これは制約トリガでのみ指定することができます。

DEFERRABLE
NOT DEFERRABLE
INITIALLY IMMEDIATE
INITIALLY DEFERRED

The default timing of the trigger. See the <xref linkend="sql-createtable"/> documentation for details of these constraint options. This can only be specified for constraint triggers. トリガのデフォルトのタイミングです。 これらの制約オプションについてはCREATE TABLE文書を参照してください。 これは制約トリガでのみ指定することができます。

REFERENCING

This keyword immediately precedes the declaration of one or two relation names that provide access to the transition relations of the triggering statement. このキーワードは、トリガの文の遷移リレーションへのアクセスを提供する1つまたは2つのリレーション名の宣言の直前に起きます。

OLD TABLE
NEW TABLE

This clause indicates whether the following relation name is for the before-image transition relation or the after-image transition relation. この句は、それに続くリレーション名が更新前イメージの遷移リレーションなのか、更新後イメージの遷移リレーションなのかを示します。

transition_relation_name

The (unqualified) name to be used within the trigger for this transition relation. この遷移リレーションについて、トリガ内で使用される(修飾されていない)名前です。

FOR EACH ROW
FOR EACH STATEMENT

This specifies whether the trigger function should be fired once for every row affected by the trigger event, or just once per SQL statement. If neither is specified, <literal>FOR EACH STATEMENT</literal> is the default. Constraint triggers can only be specified <literal>FOR EACH ROW</literal>. このパラメータは、トリガ関数を、トリガイベントによって影響を受ける行ごとに1回起動するか、SQL文ごとに1回のみ起動するかを指定します。 どちらも指定されない場合は、FOR EACH STATEMENTがデフォルトです。 制約トリガはFOR EACH ROWのみ指定することができます。

condition

A Boolean expression that determines whether the trigger function will actually be executed. If <literal>WHEN</literal> is specified, the function will only be called if the <replaceable class="parameter">condition</replaceable> returns <literal>true</literal>. In <literal>FOR EACH ROW</literal> triggers, the <literal>WHEN</literal> condition can refer to columns of the old and/or new row values by writing <literal>OLD.<replaceable class="parameter">column_name</replaceable></literal> or <literal>NEW.<replaceable class="parameter">column_name</replaceable></literal> respectively. Of course, <literal>INSERT</literal> triggers cannot refer to <literal>OLD</literal> and <literal>DELETE</literal> triggers cannot refer to <literal>NEW</literal>. トリガ関数を実際に実行するか否かを決定する論理式です。 WHENが指定された場合、conditiontrueを返す場合のみ関数が呼び出されます。 FOR EACH ROWトリガでは、WHEN条件で、それぞれOLD.column_nameNEW.column_nameと記述することで、古い行の値、新しい行の値、またはその両方の列を参照することができます。 当然ながらINSERTトリガではOLDを参照することはできませんし、DELETEトリガではNEWを参照することはできません。

<para><literal>INSTEAD OF</literal> triggers do not support <literal>WHEN</literal> conditions.

INSTEAD OFトリガはWHEN条件をサポートしません。

Currently, <literal>WHEN</literal> expressions cannot contain subqueries. 現時点ではWHEN条件に副問い合わせを含めることはできません。

Note that for constraint triggers, evaluation of the <literal>WHEN</literal> condition is not deferred, but occurs immediately after the row update operation is performed. If the condition does not evaluate to true then the trigger is not queued for deferred execution. 制約トリガでは、WHEN条件の評価は遅延されず、行の更新操作が行われた直後に発生することに注意してください。 この条件が真と評価されなかった場合、トリガは遅延実行用のキューに入りません。

function_name

A user-supplied function that is declared as taking no arguments and returning type <literal>trigger</literal>, which is executed when the trigger fires. ユーザが提供する関数です。この関数は、引数を取らずtrigger型を返すよう定義されます。トリガが起動した時に実行されます。

In the syntax of <literal>CREATE TRIGGER</literal>, the keywords <literal>FUNCTION</literal> and <literal>PROCEDURE</literal> are equivalent, but the referenced function must in any case be a function, not a procedure. The use of the keyword <literal>PROCEDURE</literal> here is historical and deprecated. CREATE TRIGGERの構文では、キーワードFUNCTIONPROCEDUREは等価ですが、参照されている関数はどちらの場合でも関数でなければならず、プロシージャであってはなりません。 ここでキーワードPROCEDUREを使うことは、歴史的なものであり廃止予定です。

arguments

An optional comma-separated list of arguments to be provided to the function when the trigger is executed. The arguments are literal string constants. Simple names and numeric constants can be written here, too, but they will all be converted to strings. Please check the description of the implementation language of the trigger function to find out how these arguments can be accessed within the function; it might be different from normal function arguments. トリガ実行時に関数に渡される引数をカンマで区切ったリストで、省略可能です。 引数として指定するのは、リテラル文字列定数です。 単純な名前および数値定数を記述できますが、全て文字列に変換されます。 関数内でこれらの引数にアクセスする方法について調べるためには、トリガ関数を実装した言語の説明を参照してください。 通常の関数引数とは異なる場合があります。

注釈

<title>Notes</title>

To create or replace a trigger on a table, the user must have the <literal>TRIGGER</literal> privilege on the table. The user must also have <literal>EXECUTE</literal> privilege on the trigger function. テーブルに対してトリガを作成もしくは変更するには、ユーザがそのテーブルに対しTRIGGER権限を持っている必要があります。 またユーザはトリガ関数に対しEXECUTE権限を持たなければなりません。

Use <link linkend="sql-droptrigger"><command>DROP TRIGGER</command></link> to remove a trigger. トリガを削除するためにはDROP TRIGGERを使用してください。

Creating a row-level trigger on a partitioned table will cause an identical <quote>clone</quote> trigger to be created on each of its existing partitions; and any partitions created or attached later will have an identical trigger, too. If there is a conflictingly-named trigger on a child partition already, an error occurs unless <command>CREATE OR REPLACE TRIGGER</command> is used, in which case that trigger is replaced with a clone trigger. When a partition is detached from its parent, its clone triggers are removed. パーティションテーブルに行レベルのトリガを作ると、存在するパーティションすべてに同一のクローントリガがつくられます。そして、後から作られたり追加されるパーティションも同一のトリガを含みます。 子パーティションに名前が衝突するトリガがすでにある場合には、CREATE OR REPLACE TRIGGERによってそのトリガをクローントリガで置き換えない限りエラーになります。 パーティションが親から切り離された場合、クローントリガは削除されます。

A column-specific trigger (one defined using the <literal>UPDATE OF <replaceable>column_name</replaceable></literal> syntax) will fire when any of its columns are listed as targets in the <command>UPDATE</command> command's <literal>SET</literal> list. It is possible for a column's value to change even when the trigger is not fired, because changes made to the row's contents by <literal>BEFORE UPDATE</literal> triggers are not considered. Conversely, a command such as <literal>UPDATE ... SET x = x ...</literal> will fire a trigger on column <literal>x</literal>, even though the column's value did not change. 列指定のトリガ(UPDATE OF column_name構文で定義されたトリガ)は、列挙された列のいずれかがUPDATEコマンドのSETリスト内に対象として指定された場合に発行されます。 BEFORE UPDATEトリガにより行の内容になされた変更は考慮されないため、トリガが発行されない場合であっても、列の値が変更されることはあります。 反対に、UPDATE ... SET x = x ...のようなコマンドは、列の値が変更されませんが、x列に対するトリガが発行されます。

In a <literal>BEFORE</literal> trigger, the <literal>WHEN</literal> condition is evaluated just before the function is or would be executed, so using <literal>WHEN</literal> is not materially different from testing the same condition at the beginning of the trigger function. Note in particular that the <literal>NEW</literal> row seen by the condition is the current value, as possibly modified by earlier triggers. Also, a <literal>BEFORE</literal> trigger's <literal>WHEN</literal> condition is not allowed to examine the system columns of the <literal>NEW</literal> row (such as <literal>ctid</literal>), because those won't have been set yet. BEFOREトリガにおいてWHEN条件は関数が実行される、またはされそうな直前に評価されます。 このためWHENの使用はトリガ関数の先頭で同一の条件を試験することと実質的に違いはありません。 この条件で確認できるNEW行が現在の値であり、それまでのトリガで変更されている可能性があることに、特に注意して下さい。 またBEFOREトリガのWHEN条件では、NEW行のシステム列(ctidなど)はまだ設定されていないので、検査することができません。

In an <literal>AFTER</literal> trigger, the <literal>WHEN</literal> condition is evaluated just after the row update occurs, and it determines whether an event is queued to fire the trigger at the end of statement. So when an <literal>AFTER</literal> trigger's <literal>WHEN</literal> condition does not return true, it is not necessary to queue an event nor to re-fetch the row at end of statement. This can result in significant speedups in statements that modify many rows, if the trigger only needs to be fired for a few of the rows. AFTERトリガにおいて、WHEN条件は行の更新を行った直後に評価され、文の最後でトリガを発行するためにイベントを保持すべきかどうかを決定します。 このためAFTERトリガのWHEN条件は真を返さない場合、イベントを保持する必要もありませんし、文の最後の行を再度取り出す必要もありません。 これにより、トリガをわずかな行のみに対して発行する必要がある場合、多くの行を変更する文を非常に高速にすることができます。

In some cases it is possible for a single SQL command to fire more than one kind of trigger. For instance an <command>INSERT</command> with an <literal>ON CONFLICT DO UPDATE</literal> clause may cause both insert and update operations, so it will fire both kinds of triggers as needed. The transition relations supplied to triggers are specific to their event type; thus an <command>INSERT</command> trigger will see only the inserted rows, while an <command>UPDATE</command> trigger will see only the updated rows. 場合によっては1つのSQLコマンドが2種類以上のトリガを発行することがあります。 例えば、ON CONFLICT DO UPDATE句のあるINSERTでは、挿入と更新の両方の操作が発生するかもしれないので、必要に応じて両方の種類のトリガを発行します。 トリガに提供される遷移リレーションはトリガのイベント種類毎に個別のものです。 従って、INSERTトリガには挿入された行だけが見え、一方でUPDATEトリガには更新された行だけが見えます。

Row updates or deletions caused by foreign-key enforcement actions, such as <literal>ON UPDATE CASCADE</literal> or <literal>ON DELETE SET NULL</literal>, are treated as part of the SQL command that caused them (note that such actions are never deferred). Relevant triggers on the affected table will be fired, so that this provides another way in which an SQL command might fire triggers not directly matching its type. In simple cases, triggers that request transition relations will see all changes caused in their table by a single original SQL command as a single transition relation. However, there are cases in which the presence of an <literal>AFTER ROW</literal> trigger that requests transition relations will cause the foreign-key enforcement actions triggered by a single SQL command to be split into multiple steps, each with its own transition relation(s). In such cases, any statement-level triggers that are present will be fired once per creation of a transition relation set, ensuring that the triggers see each affected row in a transition relation once and only once. ON UPDATE CASCADEON DELETE SET NULLなど外部キーを強制する動作によって起こる行の更新や削除は、それを起こしたSQLコマンドの一部であるとみなされます(このような動作は決して遅延実行されないことに注意してください)。 影響を受けたテーブルの関連するトリガが発行されるため、これはSQLコマンドの種類と直接には一致しないトリガが発行される別のケースとなります。 単純な場合、遷移リレーションを要求するトリガは、元となる1つのSQLコマンドによって起こされたテーブルへのすべての変更を、一つの遷移リレーションとして見ることになります。 しかし、遷移リレーションを要求するAFTER ROWトリガの存在により、一つのSQLコマンドによって発生する外部キーを強制する動作が複数のステップに分割され、各ステップがそれぞれの遷移リレーションを持つという場合もあります。 そのような場合、すべての文レベルのトリガは1つの遷移リレーションの集合の作成に対して1度ずつ呼び出され、それによりトリガが遷移リレーション内の変更された行をちょうど一度だけ見ることを確実にしています。

Statement-level triggers on a view are fired only if the action on the view is handled by a row-level <literal>INSTEAD OF</literal> trigger. If the action is handled by an <literal>INSTEAD</literal> rule, then whatever statements are emitted by the rule are executed in place of the original statement naming the view, so that the triggers that will be fired are those on tables named in the replacement statements. Similarly, if the view is automatically updatable, then the action is handled by automatically rewriting the statement into an action on the view's base table, so that the base table's statement-level triggers are the ones that are fired. ビューに付けられている文レベルのトリガは、ビューに対する操作が行レベルのINSTEAD OFトリガによって取り扱われた時にのみ発行されます。 ビューに対する操作がINSTEAD OFルールによって取り扱われる場合は、ビューを指定した元の文の代わりに、そのルールが出力した文が実行されます。 それにより、発行されるトリガは、置き換えられた文によって指定されたテーブルに付けられたトリガとなります。 同様に、ビューが自動更新可能ならば、操作は、ビューの基底テーブル上の操作に自動的に書き換えられる文によって取り扱われます。 その結果、発行されるのは基底テーブルの文レベルのトリガとなります。

Modifying a partitioned table or a table with inheritance children fires statement-level triggers attached to the explicitly named table, but not statement-level triggers for its partitions or child tables. In contrast, row-level triggers are fired on the rows in affected partitions or child tables, even if they are not explicitly named in the query. If a statement-level trigger has been defined with transition relations named by a <literal>REFERENCING</literal> clause, then before and after images of rows are visible from all affected partitions or child tables. In the case of inheritance children, the row images include only columns that are present in the table that the trigger is attached to. パーティションテーブルや継承した子テーブルがあるテーブルを変更したとき、明示的に指定されたテーブルに付けられている文レベルのトリガが発行されますが、パーティションや子テーブルに付けられている文レベルのトリガは発行されません。 対照的に、問合せ中で明示的に指定されていなくても、行レベルのトリガはすべての変更されたパーティションや子テーブルに対して発行されます。 REFERENCING句で指定された遷移リレーションのある文レベルのトリガが定義されている場合、行の変更前イメージおよび変更後イメージは、変更されたすべてのパーティションおよび子テーブルから見ることができます。 継承された子テーブルの場合、行イメージはトリガが付けられたテーブルに存在する列だけしか含みません。

Currently, row-level triggers with transition relations cannot be defined on partitions or inheritance child tables. Also, triggers on partitioned tables may not be <literal>INSTEAD OF</literal>. 現在のところ、遷移リレーションのある行レベルトリガは、パーティションや継承した子テーブルには定義できません。 また、パーティションテーブルのトリガはINSTEAD OFとすることはできません。

Currently, the <literal>OR REPLACE</literal> option is not supported for constraint triggers. 現在のところ、OR REPLACEオプションは制約トリガに対してはサポートされていません。

Replacing an existing trigger within a transaction that has already performed updating actions on the trigger's table is not recommended. Trigger firing decisions, or portions of firing decisions, that have already been made will not be reconsidered, so the effects could be surprising. トリガのテーブルに対してすでに更新動作を実行したトランザクション内で、既存のトリガを置き換えることはお勧めしません。 既に決定されたトリガ発行、もしくは発行の判断のうち既に決定された部分は再考されることはありませんので、結果は驚くべきものになるかもしれません。

There are a few built-in trigger functions that can be used to solve common problems without having to write your own trigger code; see <xref linkend="functions-trigger"/>. 自身でトリガのコードを書かなくても、よくある問題を解決するために使うことのできる組み込みのトリガ関数が多少あります。9.28を参照してください。

<title>Examples</title>

Execute the function <function>check_account_update</function> whenever a row of the table <literal>accounts</literal> is about to be updated: テーブルaccountsの行が更新される直前に関数check_account_updateを実行します。

CREATE TRIGGER check_update
    BEFORE UPDATE ON accounts
    FOR EACH ROW
    EXECUTE FUNCTION check_account_update();

Modify that trigger definition to only execute the function if column <literal>balance</literal> is specified as a target in the <command>UPDATE</command> command: UPDATEコマンドでbalance列が対象として指定されている場合にのみ関数を実行するよう、そのトリガ定義を修正します。

CREATE OR REPLACE TRIGGER check_update
    BEFORE UPDATE OF balance ON accounts
    FOR EACH ROW
    EXECUTE FUNCTION check_account_update();

This form only executes the function if column <literal>balance</literal> has in fact changed value: 以下の構文では、列balanceが実際に変更された場合のみ関数が実行されます。

CREATE TRIGGER check_update
    BEFORE UPDATE ON accounts
    FOR EACH ROW
    WHEN (OLD.balance IS DISTINCT FROM NEW.balance)
    EXECUTE FUNCTION check_account_update();

Call a function to log updates of <literal>accounts</literal>, but only if something changed: 何か変更された場合のみにaccountsの更新のログを取る関数を呼び出します。

CREATE TRIGGER log_update
    AFTER UPDATE ON accounts
    FOR EACH ROW
    WHEN (OLD.* IS DISTINCT FROM NEW.*)
    EXECUTE FUNCTION log_account_update();

Execute the function <function>view_insert_row</function> for each row to insert rows into the tables underlying a view: ビューの背後にあるテーブルに行を挿入するために、各行に対して関数view_insert_rowを実行します。

CREATE TRIGGER view_insert
    INSTEAD OF INSERT ON my_view
    FOR EACH ROW
    EXECUTE FUNCTION view_insert_row();

Execute the function <function>check_transfer_balances_to_zero</function> for each statement to confirm that the <literal>transfer</literal> rows offset to a net of zero: 各文に対して関数check_transfer_balances_to_zeroを実行して、transferの行が相殺してゼロになることを確認します。

CREATE TRIGGER transfer_insert
    AFTER INSERT ON transfer
    REFERENCING NEW TABLE AS inserted
    FOR EACH STATEMENT
    EXECUTE FUNCTION check_transfer_balances_to_zero();

Execute the function <function>check_matching_pairs</function> for each row to confirm that changes are made to matching pairs at the same time (by the same statement): 各行に対して関数check_matching_pairsを実行して、対応する組み合わせに対して同じ時に(同じ文により)変更されていることを確認します。

CREATE TRIGGER paired_items_update
    AFTER UPDATE ON paired_items
    REFERENCING NEW TABLE AS newtab OLD TABLE AS oldtab
    FOR EACH ROW
    EXECUTE FUNCTION check_matching_pairs();

<xref linkend="trigger-example"/> contains a complete example of a trigger function written in C. 39.4には、C言語で作成されたトリガ関数の完全な例があります。

互換性

<title>Compatibility</title> It's not clear whether SQL/MED contemplates triggers on foreign tables. Its <drop basic column definition> General Rules do mention the possibility of a reference from a trigger column list. On the other hand, nothing overrides the fact that CREATE TRIGGER only targets base tables. For now, do not document the compatibility status of triggers on foreign tables.

The <command>CREATE TRIGGER</command> statement in <productname>PostgreSQL</productname> implements a subset of the <acronym>SQL</acronym> standard. The following functionalities are currently missing: PostgreSQLにおけるCREATE TRIGGER文は標準SQLのサブセットを実装したものです 現在は、PostgreSQLには、次の機能がありません。

  • While transition table names for <literal>AFTER</literal> triggers are specified using the <literal>REFERENCING</literal> clause in the standard way, the row variables used in <literal>FOR EACH ROW</literal> triggers may not be specified in a <literal>REFERENCING</literal> clause. They are available in a manner that is dependent on the language in which the trigger function is written, but is fixed for any one language. Some languages effectively behave as though there is a <literal>REFERENCING</literal> clause containing <literal>OLD ROW AS OLD NEW ROW AS NEW</literal>. AFTERトリガの遷移テーブル名はREFERENCING句を使って標準SQLの方法で指定できますが、FOR EACH ROWトリガで使用される行変数はREFERENCING句で指定することができません。 それはトリガ関数が書かれる言語に依存する方法で利用できますが、各言語によって決まった方法になります。 一部の言語は、REFERENCING句がOLD ROW AS OLD NEW ROW AS NEWとなっているかのように動作します。

  • The standard allows transition tables to be used with column-specific <literal>UPDATE</literal> triggers, but then the set of rows that should be visible in the transition tables depends on the trigger's column list. This is not currently implemented by <productname>PostgreSQL</productname>. 標準SQLでは列を指定したUPDATEトリガでも遷移テーブルを使うことができますが、その場合遷移テーブルで見ることができる行の集合はトリガの列リストに依存します。 これは現在のところPostgreSQLでは実装されていません。

  • <productname>PostgreSQL</productname> only allows the execution of a user-defined function for the triggered action. The standard allows the execution of a number of other SQL commands, such as <command>CREATE TABLE</command>, as the triggered action. This limitation is not hard to work around by creating a user-defined function that executes the desired commands. PostgreSQLでは、トリガ動作として、ユーザ定義関数の実行しか認めていません。 標準では、多数の他のSQLコマンドを実行させることができます。 例えば、トリガ動作としてCREATE TABLEを実行させることも可能です。 この制限を回避する方法は簡単です。必要なコマンドを実行するユーザ定義関数を作成すればよいのです。

SQL specifies that multiple triggers should be fired in time-of-creation order. <productname>PostgreSQL</productname> uses name order, which was judged to be more convenient. SQLでは、複数のトリガは、作成時刻順に起動すべきであると規定しています。 PostgreSQLでは名前順です。この方が便利だと考えられるからです。

SQL specifies that <literal>BEFORE DELETE</literal> triggers on cascaded deletes fire <emphasis>after</emphasis> the cascaded <literal>DELETE</literal> completes. The <productname>PostgreSQL</productname> behavior is for <literal>BEFORE DELETE</literal> to always fire before the delete action, even a cascading one. This is considered more consistent. There is also nonstandard behavior if <literal>BEFORE</literal> triggers modify rows or prevent updates during an update that is caused by a referential action. This can lead to constraint violations or stored data that does not honor the referential constraint. SQLでは、数珠繋ぎの削除に対するBEFORE DELETEは、数珠繋ぎのDELETEが完了した後に発行するものと規定しています。 PostgreSQLでは、BEFORE DELETEは常に削除操作よりも前に、それも起点となる削除よりも前に行われます。 この方がより一貫性があると考えられいます。 また、参照整合性に関する動作により引き起こされる更新を実行している間に、BEFOREトリガが行を更新し、更新を妨げるような場合の動作も標準に従わないものがあります。 これは、制約違反となるかもしれませんし、参照整合性制約に合わないデータを格納してしまうかもしれません。

The ability to specify multiple actions for a single trigger using <literal>OR</literal> is a <productname>PostgreSQL</productname> extension of the SQL standard. ORを使用して単一トリガに複数の動作を指定する機能は、標準SQLに対するPostgreSQLの拡張です。

The ability to fire triggers for <command>TRUNCATE</command> is a <productname>PostgreSQL</productname> extension of the SQL standard, as is the ability to define statement-level triggers on views. TRUNCATEでのトリガ発行機能、および、ビューに対する文レベルのトリガの定義機能は標準SQLに対するPostgreSQLの拡張です。

<command>CREATE CONSTRAINT TRIGGER</command> is a <productname>PostgreSQL</productname> extension of the <acronym>SQL</acronym> standard. So is the <literal>OR REPLACE</literal> option. CREATE CONSTRAINT TRIGGERは標準SQLに対するPostgreSQLの拡張です。 OR REPLACEオプションも同じです。

関連項目

<title>See Also</title> ALTER TRIGGER, DROP TRIGGER, CREATE FUNCTION, SET CONSTRAINTS