CREATE TRIGGER
SQL - Language Statements
CREATE TRIGGER
Creates a new trigger
1998-04-15
CREATE TRIGGER name { BEFORE | AFTER }
{ event [OR ...] }
ON table FOR EACH { ROW | STATEMENT }
EXECUTE PROCEDURE funcname ( arguments )
1998-04-15
Inputs
name
The name of an existing trigger.
table
The name of a table.
event
One of INSERT, DELETE or UPDATE.
funcname
A user-supplied function.
1998-04-15
Outputs
CREATE
This message is returned if the trigger is successfully created.
1998-04-15
Description
CREATE TRIGGER will enter a new trigger into the current
data base. The trigger will be associated with the relation
relname and will execute
the specified function funcname.
Only the relation owner may create a trigger on this relation.
At release 6.3.2, STATEMENT triggers are not implemented.
The trigger can be specified to fire either before the
operation is attempted on a tuple (before constraints
are checked and the INSERT, UPDATE or DELETE is attempted) or
after the operation has been attempted (e.g. after constraints
are checked and the INSERT, UPDATE or DELETE has completed). If the
trigger fires before the event, the trigger may
skip the operation for the current tuple, or change the tuple
being inserted (for INSERT and UPDATE operations only). If
the trigger fires after the event, all changes, including the
last INSERTion, UPDATE or DELETion, are "visible" to the trigger.
Refer to the SPI and trigger programming guides for more
information.
1998-04-15
Notes
CREATE TRIGGER statement is a PostgreSQL language extension.
Refer to the DROP TRIGGER statement for information on how to
remove triggers.
Usage
Check if the specified distributor code exists in the distributors
table before appending or updating a row in the table films:
CREATE TRIGGER if_dist_exists
BEFORE INSERT OR UPDATE ON films FOR EACH ROW
EXECUTE PROCEDURE check_primary_key ('did', 'distributors', 'did');
Before cancelling a distributor or updating its code, remove every
reference to the table films:
CREATE TRIGGER if_film_exists
BEFORE DELETE OR UPDATE ON distributors FOR EACH ROW
EXECUTE PROCEDURE check_foreign_key (1, 'CASCADE', 'did', 'films', 'did');
Compatibility
1998-04-15
SQL92
There is no CREATE TRIGGER statement in SQL92.
The second example above may also be done by using a FOREIGN KEY
constraint as in:
CREATE TABLE distributors (
did DECIMAL(3),
name VARCHAR(40),
CONSTRAINT if_film_exists FOREIGN KEY(did) REFERENCES films
ON UPDATE CASCADE ON DELETE CASCADE
);
However, foreign keys are not yet implemented at version 6.3.2 of
PostgreSQL.