Create & Drop a Foreign Key - SQL Query
I) How to create a Foreign Key in SQL?
Using Create table statement.
Step 1: Create a table Supplier.
CREATE TABLE Supplier
( S_Id INT not null,
S_Name varchar2(50) not null,
contact_Person varchar2(50),
CONSTRAINT supplier_pk PRIMARY KEY (S_ID)
);
In the above query the table Supplier is created and primary key is created on column Supplier_id.
Step 2: Create a table Products and create a foreign key on column supplier_id.
CREATE TABLE Products
( Product_id INT not null,
S_Id numeric(10) not null,
CONSTRAINT fk_supplier
FOREIGN KEY (S_Id)
REFERENCES Supplier(S_ID)
);
In the above query the foreign key is created on S_ID column by taking REFERENCES Supplier(S_ID).
II) How to drop foreign key?
ALTER TABLE Products DROP CONSTRAINT fk_supplier;