Sunday, February 8, 2009

Oracle: foreign key syntax

let us check the syntax of foreign key with various options:
step 1) first we will create a primary key that will be referred in foreign key constraints:

sys@LION>CREATE TABLE ersh_tab
( emp_id number(10) not null,
emp_name varchar2(50) not null,
address varchar2(50),
CONSTRAINT emp_id_pk PRIMARY KEY (emp_id)
);

Table created

step 2) We will configure the foreign key now.
a) foreign key with create table option
sys@LION> create table ersh_foreign_tab
(id number(10) not null,
email varchar2(32),
constraint emp_id_fk foreign key (id) references ersh_tab(emp_id)
);
Table created

b) foreign key with alter table option
sys@LION>ALTER TABLE ersh_foreign_tab
add CONSTRAINT emp_id_fk
FOREIGN KEY (id) REFERENCES ersh_tab(emp_id);
Table altered

c) Composite primary key with create table:
sys@LION>CREATE TABLE ersh_tab
( emp_id number(10) not null,
emp_name varchar2(50) not null,
address varchar2(50),
CONSTRAINT emp_id_pk PRIMARY KEY (emp_id,emp_name)
);

composite foreign key with create table option
sys@LION> create table ersh_foreign_tab
(id number(10) not null,
email varchar2(32),
constraint emp_id_fk foreign key (id,email) references ersh_tab(emp_id,email)
);


Thanks,
Have a nice day.................

1 comment:

Anonymous said...

just dropping by to say hi