Você está na página 1de 1

Chapter 1: Creating 29

Tip: Always specify a PRIMARY KEY, or at least a UNIQUE constraint or


non-NULL unique index. This keeps the transaction log small because the row
can be uniquely identified by the key or index entry. Without this identification the
entire row must be written to the transaction log for every change. This inflates
the log file and slows down the server.

1.13.3 FOREIGN KEY Table Constraint


FOREIGN KEY table constraints have more options than the corresponding
column constraint, but they also require more work because you must specify
the list of column names that comprise the foreign key.
<foreign_key_table_constraint> ::= [ <constraint_or_prefix> ]
[ NOT NULL ]
FOREIGN KEY [ <role_name> ]
"(" <column_name_list> ")"
REFERENCES [ <owner_name> "." ] <table_name>
[ "(" <column_name_list> ")" ]
[ <on_action> ]
[ CHECK ON COMMIT ]
[ <clustering> ]
<constraint_or_prefix> ::= CONSTRAINT
| CONSTRAINT <constraint_name>
| <constraint_name>
<role_name> ::= <identifier>
Here is an example of a three-level hierarchy where the primary and foreign
keys grow in size with each level:
CREATE TABLE country (
country_code VARCHAR ( 2 ),
name VARCHAR ( 100 ),
PRIMARY KEY ( country_code ) );

CREATE TABLE office (


country_code VARCHAR ( 2 ),
office_code VARCHAR ( 10 ),
address VARCHAR ( 1000 ),
PRIMARY KEY ( country_code, office_code ),
FOREIGN KEY ( country_code ) REFERENCES country );

CREATE TABLE representative (


country_code VARCHAR ( 2 ),
office_code VARCHAR ( 10 ),
representative_id INTEGER,
name VARCHAR ( 100 ),
PRIMARY KEY ( country_code, office_code, representative_id ),
FOREIGN KEY ( country_code, office_code ) REFERENCES office );
You can specify a constraint name in one of two places: as a leading name (with
or without the CONSTRAINT keyword), or as a role name following the
FOREIGN KEY keywords. Either way, this name will appear in any error mes-
sages so its an opportunity for you to make the messages more meaningful.
The NOT NULL clause is a way of specifying that all the foreign key col-
umns must be NOT NULL regardless of whether the individual columns are
defined as NULL or NOT NULL.
The REFERENCES clause must specify the parent table name. The list of
column names is optional; the default is the parent table primary key columns.
If you want to reference a parent table UNIQUE constraint instead of the

Você também pode gostar