The PRIMARY KEY of a table exists in another table, but not as a PRIMARY KEY is called as FOREIGN KEY.Let's see the foreign key with an example. Look at the following two tables:
did | dname |
---|---|
101 102 103 |
Development Marketing Testing |
eid | ename | did |
---|---|---|
E101 E102 E103 |
Tapaswini Bandana Akshya |
101 102 103 |
Here in Department table did is the PRIMARY KEY and in Employee table eid is the PRIMARY KEY and did is the FOREIGN KEY.
The following SQL creates a FOREIGN KEY on the "did" column when the
"Employee" table is created:
CREATE TABLE dept
(
d_id int PRIMARY KEY,
d_name varchar2(100)
);
CREATE TABLE employee
(
e_id int PRIMARY KEY,
e_name varchar2(100) NOT NULL,
d_id int,
CONSTRAINT fk_deptemp
FOREIGN KEY(d_id) REFERENCES
dept(d_id)
)
CREATE TABLE Employee
(
eid int NOT NULL,
ename int NOT NULL,
did varchar2(100),
PRIMARY KEY (eid),
FOREIGN KEY (did) REFERENCES Department(did)
)
To create a FOREIGN KEY constraint on the "did" column when the "Employee"
table is already created, use the following SQL:
ALTER TABLE Employee
ADD FOREIGN KEY (did)
REFERENCES Department(did)
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY
constraint on multiple columns, use the following SQL syntax:
ALTER TABLE Employee
ADD CONSTRAINT fk_DeptEmployee
FOREIGN KEY (did)
REFERENCES Persons(did)
To drop a FOREIGN KEY constraint, use the following SQL:
ALTER TABLE Employee
DROP FOREIGN KEY fk_DeptEmployee
Oracle/SQL Server / MS Access:
ALTER TABLE Employee
DROP CONSTRAINT fk_DeptEmployee
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc