You are on page 1of 1

24 Chapter 1: Creating

A PRIMARY KEY constraint is different from a unique index because an


index allows NULL values and a PRIMARY KEY does not.

1.10.4 Foreign Key Column Constraint


A foreign key column constraint uses the REFERENCES clause to define a
relationship between this table (called the child or foreign table) and
another table (called the parent or primary table). Foreign key constraints
are used to represent one-to-many relationships between parent and child tables,
as in this example where one country may contain multiple offices:
CREATE TABLE country (
country_code VARCHAR ( 2 ) PRIMARY KEY,
name VARCHAR ( 100 ) NOT NULL );

CREATE TABLE office (


office_code VARCHAR ( 10 ) PRIMARY KEY,
country_code VARCHAR ( 2 ) NULL
CONSTRAINT "office.country_code must be valid or NULL"
REFERENCES country ( country_code )
ON UPDATE CASCADE ON DELETE SET NULL );
In this example the country_code column in office may be NULL. If it is not
NULL, then it must contain a value that matches the country_code column in
the country table. Thats what the REFERENCES clause is for; it points to the
parent table and its PRIMARY KEY column by name.
The REFERENCES clause is used to identify a single row in the parent
table that matches this row in the child table. It can point to the PRIMARY
KEY column or to a parent column with a UNIQUE constraint. Either one will
do, but PRIMARY KEY columns are almost always used, and they are the
default if the parent column name is omitted from the REFERENCES clause.
The example above includes a name for the foreign key constraint. This
name will appear in the error message if the constraint fails; for example, the
fourth INSERT below will fail with the error message No primary key value
for foreign key 'office.country_code must be valid or NULL' in table 'office'.
INSERT country VALUES ( 'CA', 'Canada' );
INSERT office VALUES ( '001', 'CA' ); -- OK
INSERT office VALUES ( '002', NULL ); -- OK
INSERT office VALUES ( '003', 'XX' ); -- fails
Foreign key constraints can fail for two main reasons: An attempt was made to
INSERT or UPDATE a child row with a value that doesnt satisfy the constraint,
or an attempt was made to UPDATE or DELETE a parent row in a way that
causes one or more child rows to suddenly violate the constraint. Theres noth-
ing you can do to bypass errors caused by changes to the child table, but
violations caused by changes in the parent table can be repaired on-the-fly with
the ON UPDATE and ON DELETE clauses.
The ON UPDATE clause says that when the parent column changes in
value, one of three different actions will be taken in all the corresponding child
rows that would now violate the foreign key constraint. ON UPDATE
CASCADE makes the same change to the child column so it matches the new
parent column. ON UPDATE SET NULL changes the child column to NULL so
at least it doesnt violate the constraint. ON UPDATE SET DEFAULT changes

You might also like