Databases Reference
In-Depth Information
For reference, here's how the parent table DEPT table was created for these examples:
create table dept(
dept_id number primary key,
dept_desc varchar2(30));
A foreign key must reference a column in the parent table that has a primary key or a unique key defined on it.
DEPT is the parent table and has a primary key defined on DEPT_ID .
You can use several methods to create a foreign key constraint. The following example creates a foreign key
constraint on the DEPT_ID column in the EMP table:
create table emp(
emp_id number,
name varchar2(30),
dept_id constraint emp_dept_fk references dept(dept_id));
Note that the DEPT_ID data type isn't explicitly defined. The foreign key constraint derives the data type from the
referenced DEPT_ID column of the DEPT table. You can also explicitly specify the data type when you define a column
(regardless of the foreign key definition):
create table emp(
emp_id number,
name varchar2(30),
dept_id number constraint emp_dept_fk references dept(dept_id));
You can also specify the foreign key definition out of line from the column definition in the CREATE TABLE
statement:
create table emp(
emp_id number,
name varchar2(30),
dept_id number,
constraint emp_dept_fk foreign key (dept_id) references dept(dept_id)
);
And, you can alter an existing table to add a foreign key constraint:
alter table emp
add constraint emp_dept_fk foreign key (dept_id)
references dept(dept_id);
Unlike with primary key and unique key constraints, Oracle doesn't automatically add an index to foreign key
columns; you must explicitly create indexes on them. see Chapter 8 for a discussion on why it's important to create
indexes on foreign key columns and how to detect foreign key columns that don't have associated indexes.
Note
 
Search WWH ::




Custom Search