Use the CREATE TRIGGER command to add a trigger to a database. When a trigger is added
to the database, it is associated with the
specified in the
ON clause. When the specified
"fires" the trigger, the
function you specified will be executed.
Note: A trigger may only be created on a table by the table's owner, or by a superuser.
When you create a trigger, you must specify whether it is to be fired before or after the
is attempted (or completed). If the trigger is set to fire
BEFORE one of those events, it may skip the operation for the current tuple, or change the
tuple being inserted. If you have set the trigger to fire AFTER the event, it will be aware
of all changes that were made during the event (including the last insertion, update, or deletion).
The following example defines a trigger that is invoked when an existing row in the authors table is updated:
CREATE TRIGGER sync_authors_books
FOR EACH ROW
EXECUTE PROCEDURE sync_authors_and_books();
The sync_authors_and_books() function is a PL/pgSQL function defined to update the value of the author_id column in the books table if the id value in the authors table is updated. It therefore keeps the books table in sync with the authors table. A similar effect could be achieved with a FOREIGN KEY constraint (see Chapter 7).