Saturday, July 23, 2011

Question about using foreign key constraints in Oracle

From Apoorva - I am doing SQL / PLSQL course for Oracle. Right now, I am doing SQL and have came across a problem. Following is the SQL statement :



CREATE TABLE title_copy (
copy_id number(10),
title_id number(10),
status varchar2(15)
CONSTRAINT title_copy_status_nn NOT NULL,
CONSTRAINT title_copy_status_chk CHECK(status IN ('AVAILABLE', 'DESTROYED', 'RENTED', 'RESERVED')),
CONSTRAINT title_copy_titleid_fk FOREIGN KEY(title_id) REFERENCES title_copy(copy_id),
CONSTRAINT title_copy_copyid_titleid_pk PRIMARY KEY(copy_id,title_id));


I am getting following error :
REFERENCES title_copy(copy_id),
*
ERROR at line 12: ORA-02270: no matching unique or primary key for this column-list Please help...


Apoova,

The reason for ther error is that the foreign key constraint has to reference another (different) table. You can't refer to the same table in which you're defining the foreign key constraint as you have done.

The purpose of the foreign key is to ensure that a child record created in a table with a foreign key constraint has a parent record in the referenced table.

For example, let's assume you have a table called DEPARTMENT with columns department_id and department_name to hold details about the different departments in the organisation you work for.

Let's suppose also that you have another table called EMPLOYEE with columns employee_id, department_id and employee_name to hold employee details.

To ensure that you don't assign employees to a non-existant department you would create a foreign key on employee.department_id to reference the department_id column in the department table as follows:-

CREATE TABLE employee (
employee_id NUMBER(10),
department_id NUMBER(10),
employee_name VARCHAR2(60) NOT NULL,
CONSTRAINT emp_fk FOREIGN KEY(department_id) REFERENCES department(department_id)); 


Note also that a foreign key must refer to either a unique key or a primary key in the referenced table. Therefore if, in this case, department_id were not the primary key of the departments table, the constraint creation would fail.

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Deep's | Bloggerized by Deep - Deep's Templates | ElearSQL-Server