356
Part III ✦ Nuts and Bolts
Constraints
Constraints are rules about your data that you define at the database level. Constraints
are declarative. You don’t specify the process for enforcing a rule; you simply specify
what that rule is to be. Oracle supports these types of constraints:
✦ Primary key
✦ Unique key
✦ Foreign key
✦ Check
Primary key constraints identify the set of columns whose values uniquely identify
a record in a table. Oracle won’t allow two records to have the same primary key
value. For example, the
ID_NO column is the primary key of the AQUATIC_ANIMAL
table. Because ID_NO has been defined as the primary key, Oracle will not allow two
records to have the same value in that column. Furthermore, primary key columns
become required columns—they can never be null.
Unique key constraints identify sets of columns that must be unique for each row
in a table. Unique key constraints are similar to primary key constraints, and they
often represent alternative primary key choices. The one difference between a
unique key and a primary key is that columns in a unique key may be null.
When you create a primary key or unique key constraint on a table, Oracle will cre-
ate a unique index to enforce that constraint. The name of the index will match
the name that you give the constraint.
Foreign key constraints are used to link two tables that contain related information.
They are most often used in parent-child relationships, such as the one between
the
TANK table and the AQUATIC_ANIMAL table. A foreign key constraint can be
placed on the
AQUATIC_ANIMAL table, requiring that any TANK_NO value match
a record in the
TANK table. In this way, you can prevent erroneous tank numbers
from being entered in the
AQUATIC_ANIMAL table. Foreign keys must be linked to
a corresponding primary or unique key.
Check constraints allow you to define an arbitrary condition that must be true before
a row can be saved in a table. The most common check constraint is the
NOT NULL
constraint, which requires that a column have a value. You can supply almost any
arbitrary expression for a check constraint, provided that it returns a value of
TRUE
or FALSE.