1--Column ID of table A is primary key:
2
3CREATE TABLE A (
4	ID	int4 not null
5);
6CREATE UNIQUE INDEX AI ON A (ID);
7
8--Columns REFB of table B and REFC of C are foreign keys referenting ID of A:
9
10CREATE TABLE B (
11	REFB	int4
12);
13CREATE INDEX BI ON B (REFB);
14
15CREATE TABLE C (
16	REFC	int4
17);
18CREATE INDEX CI ON C (REFC);
19
20--Trigger for table A:
21
22CREATE TRIGGER AT BEFORE DELETE OR UPDATE ON A FOR EACH ROW
23EXECUTE PROCEDURE
24check_foreign_key (2, 'cascade', 'ID', 'B', 'REFB', 'C', 'REFC');
25/*
262	- means that check must be performed for foreign keys of 2 tables.
27cascade	- defines that corresponding keys must be deleted.
28ID	- name of primary key column in triggered table (A). You may
29	  use as many columns as you need.
30B	- name of (first) table with foreign keys.
31REFB	- name of foreign key column in this table. You may use as many
32	  columns as you need, but number of key columns in referenced
33	  table (A) must be the same.
34C	- name of second table with foreign keys.
35REFC	- name of foreign key column in this table.
36*/
37
38--Trigger for table B:
39
40CREATE TRIGGER BT BEFORE INSERT OR UPDATE ON B FOR EACH ROW
41EXECUTE PROCEDURE
42check_primary_key ('REFB', 'A', 'ID');
43
44/*
45REFB	- name of foreign key column in triggered (B) table. You may use as
46	  many columns as you need, but number of key columns in referenced
47	  table must be the same.
48A	- referenced table name.
49ID	- name of primary key column in referenced table.
50*/
51
52--Trigger for table C:
53
54CREATE TRIGGER CT BEFORE INSERT OR UPDATE ON C FOR EACH ROW
55EXECUTE PROCEDURE
56check_primary_key ('REFC', 'A', 'ID');
57
58-- Now try
59
60INSERT INTO A VALUES (10);
61INSERT INTO A VALUES (20);
62INSERT INTO A VALUES (30);
63INSERT INTO A VALUES (40);
64INSERT INTO A VALUES (50);
65
66INSERT INTO B VALUES (1);	-- invalid reference
67INSERT INTO B VALUES (10);
68INSERT INTO B VALUES (30);
69INSERT INTO B VALUES (30);
70
71INSERT INTO C VALUES (11);	-- invalid reference
72INSERT INTO C VALUES (20);
73INSERT INTO C VALUES (20);
74INSERT INTO C VALUES (30);
75
76DELETE FROM A WHERE ID = 10;
77DELETE FROM A WHERE ID = 20;
78DELETE FROM A WHERE ID = 30;
79
80SELECT * FROM A;
81SELECT * FROM B;
82SELECT * FROM C;
83