Monday, 21 August 2017

Foreign Key in Constraints


Foreign Key:

  • Foriegn Key is referential integrity.
  • It refers primary key on unique constraints on another table.
  • It accept null values.
  • It accept duplicates. 

Syntax

Create table t4(cid number, cname Varchar(10), constraints c12 primary key (cid));

Table Created;

insert into t4 values (1, 'alex');
insert into t4 values (2, 'arun');

select * from t4;

Cid Cname
1 Alex
2 Arun

create table t112 (sid number, sname varchar(10),cid number, constraints c14 foreign key(cid) references t4(cid));  

Table created

Here Cid is foreign key Its refers to the t4 table primary key.

insert into t112 values (10, 'alex',2 );

1 row inserted

cid= 2 is in the t4 table

insert into t112 values (10, 'alex',3 );

ORA-02291: integrity constraint (HR.C14) violated - parent key not found

Note : Here in the t4 table there is no cid value as 3 so its redirect to error

No comments:

Post a Comment