Foreign key

From Oracle FAQ

Jump to: navigation, search

A foreign key is a column in a table that does NOT uniquely identify rows in that table, but is used as a link to matching columns in other tables to indicate a relationship.

For example, the emp.depto column is a foreign key pointing the the dept table's primary key - dept.deptno.

Contents

[edit] Examples

[edit] Inline and out of line definitions

Define a table with primary key to reference:

CREATE TABLE t1 (c1 NUMBER PRIMARY KEY);

Inline foreign key (part of column definition):

CREATE TABLE t2 (
        c1 NUMBER PRIMARY KEY,
        c2 NUMBER REFERENCES t1(c1) );

Out-of-line foreign key (after column definitions):

CREATE TABLE t3 (
        c1 NUMBER,
        c2 NUMBER,
        CONSTRAINT t1_fk FOREIGN KEY (c1) REFERENCES t1);

[edit] ON DELETE CASCADE

Foreign key with ON DELETE CASCADE:

CREATE TABLE parent (id NUMBER PRIMARY KEY);
CREATE TABLE child  (id NUMBER PRIMARY KEY,
                    pid REFERENCES parent(id) ON DELETE CASCADE);

If rows are deleted from the parent table, referenced rows will automatically be removed from the child table.

[edit] ON DELETE SET NULL

Foreign key with ON DELETE SET NULL:

CREATE TABLE parent (id NUMBER PRIMARY KEY);
CREATE TABLE child  (id NUMBER PRIMARY KEY,
                    pid REFERENCES parent(id) ON DELETE SET NULL);

If rows are deleted from the parent table, referenced rows field will automatically be set to null in the child table.

[edit] Also see

Glossary of Terms
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z #
Personal tools