Foreign Keys v10
Suppose you want to make sure all employees belong to a valid department. This is called maintaining the referential integrity of your data. In simplistic database systems this would be implemented (if at all) by first looking at the dept
table to check if a matching record exists, and then inserting or rejecting the new employee record. This approach has a number of problems and is very inconvenient. Advanced Server can make it easier for you.
A modified version of the emp
table presented in Creating a New Table is shown in this section with the addition of a foreign key constraint. The modified emp
table looks like the following:
CREATE TABLE emp ( empno NUMBER(4) NOT NULL CONSTRAINT emp_pk PRIMARY KEY, ename VARCHAR2(10), job VARCHAR2(9), mgr NUMBER(4), hiredate DATE, sal NUMBER(7,2), comm NUMBER(7,2), deptno NUMBER(2) CONSTRAINT emp_ref_dept_fk REFERENCES dept(deptno) );
If an attempt is made to issue the following INSERT
command in the sample emp
table, the foreign key constraint, emp_ref_dept_fk
, ensures that department 50
exists in the dept
table. Since it does not, the command is rejected.
INSERT INTO emp VALUES (8000,'JONES','CLERK',7902,'17-AUG-07',1200,NULL,50); ERROR: insert or update on table "emp" violates foreign key constraint "emp_ref_dept_fk" DETAIL: Key (deptno)=(50) is not present in table "dept".
The behavior of foreign keys can be finely tuned to your application. Making correct use of foreign keys will definitely improve the quality of your database applications, so you are strongly encouraged to learn more about them.