.\\" auto-generated by docbook2man-spec $Revision: 1.25 $
.TH "CREATE TRIGGER" "" "29 March 2001" "SQL - Language Statements" "SQL Commands"
.SH NAME
CREATE TRIGGER \- Creates a new trigger
.SH SYNOPSIS
.sp
.nf
CREATE TRIGGER \fIname\fR { BEFORE | AFTER } { \fIevent\fR [OR ...] }
    ON \fItable\fR FOR EACH { ROW | STATEMENT }
    EXECUTE PROCEDURE \fIfunc\fR ( \fIarguments\fR )
  
.sp
.fi
.SS "INPUTS"
.PP
.TP
\fB\fIname\fB\fR
The name of an existing trigger.
.TP
\fB\fItable\fB\fR
The name of a table.
.TP
\fB\fIevent\fB\fR
One of INSERT, DELETE or UPDATE.
.TP
\fB\fIfunc\fB\fR
A user-supplied function.
.PP
.SS "OUTPUTS"
.PP
.TP
\fBCREATE\fR
This message is returned if the trigger is successfully created.
.PP
.SH "DESCRIPTION"
.PP
\fBCREATE TRIGGER\fR will enter a new trigger into the current
data base. The trigger will be associated with the relation
\fItable\fR and will execute
the specified function \fIfunc\fR.
.PP
The trigger can be specified to fire either before BEFORE the
operation is attempted on a tuple (before constraints
are checked and the \fBINSERT\fR, \fBUPDATE\fR or
\fBDELETE\fR is attempted) or
AFTER the operation has been attempted (e.g., after constraints
are checked and the \fBINSERT\fR,
\fBUPDATE\fR or \fBDELETE\fR 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 \fBINSERT\fR and
\fBUPDATE\fR operations only). If
the trigger fires after the event, all changes, including the
last insertion, update, or deletion, are "visible" to the trigger.
.PP
Refer to the chapters on SPI and Triggers in the
\fIPostgreSQL Programmer's Guide\fR for more
information.
.SS "NOTES"
.PP
\fBCREATE TRIGGER\fR is a Postgres
language extension.
.PP
Only the relation owner may create a trigger on this relation.
.PP
As of the current release (v7.0), STATEMENT triggers are not implemented.
.PP
Refer to \fBDROP TRIGGER\fR for information on how to 
remove triggers.
.SH "USAGE"
.PP
Check if the specified distributor code exists in the distributors
table before appending or updating a row in the table films:
.sp
.nf
CREATE TRIGGER if_dist_exists
    BEFORE INSERT OR UPDATE ON films FOR EACH ROW
    EXECUTE PROCEDURE check_primary_key ('did', 'distributors', 'did');
   
.sp
.fi
.PP
Before cancelling a distributor or updating its code, remove every
reference to the table films:
.sp
.nf
CREATE TRIGGER if_film_exists 
    BEFORE DELETE OR UPDATE ON distributors FOR EACH ROW
    EXECUTE PROCEDURE check_foreign_key (1, 'CASCADE', 'did', 'films', 'did');
   
.sp
.fi
.SH "COMPATIBILITY"
.SS "SQL92"
.PP
There is no \fBCREATE TRIGGER\fR in SQL92.
.PP
The second example above may also be done by using a FOREIGN KEY
constraint as in:
.sp
.nf
CREATE TABLE distributors (
    did      DECIMAL(3),
    name     VARCHAR(40),
    CONSTRAINT if_film_exists
    FOREIGN KEY(did) REFERENCES films
    ON UPDATE CASCADE ON DELETE CASCADE  
);
    
.sp
.fi
