SQL FOREIGN KEY
A FOREIGN KEY is a column in one table that points to the primary key of another table. It establishes relationships between tables and enforces referential integrity ÔÇö preventing invalid or orphaned data.
Complete Python Course with Advance topics:-
SQL Tutorial:-
Example: Employees and Salaries
The Salaries.Emp_Id column references Employees.Emp_Id. Salaries cannot have an Emp_Id that does not exist in Employees.
Defining a FOREIGN KEY on CREATE TABLE
-- MySQL
CREATE TABLE Salaries (
Sal_Id INT NOT NULL PRIMARY KEY,
Amount INT NOT NULL,
Emp_Id INT,
FOREIGN KEY (Emp_Id) REFERENCES Employees(Emp_Id)
);
-- SQL Server / Oracle
CREATE TABLE Salaries (
Sal_Id INT NOT NULL PRIMARY KEY,
Amount INT NOT NULL,
Emp_Id INT FOREIGN KEY REFERENCES Employees(Emp_Id)
);
Adding a FOREIGN KEY with ALTER TABLE
ALTER TABLE Salaries
ADD CONSTRAINT fk_EmpSalaries
FOREIGN KEY (Emp_Id) REFERENCES Employees(Emp_Id);
Dropping a FOREIGN KEY
-- MySQL
ALTER TABLE Salaries DROP FOREIGN KEY fk_EmpSalaries;
-- SQL Server / Oracle
ALTER TABLE Salaries DROP CONSTRAINT fk_EmpSalaries;
Cascade Actions
Control what happens when the parent row changes:
FOREIGN KEY (Emp_Id) REFERENCES Employees(Emp_Id)
ON DELETE CASCADE
ON UPDATE CASCADE;
- CASCADE: Apply the change to child rows automatically.
- SET NULL: Set child foreign key to NULL.
- RESTRICT / NO ACTION: Block the change if children exist.
PRIMARY KEY vs FOREIGN KEY
- NULL: Primary Key ÔÇö No; Foreign Key ÔÇö Yes.
- Uniqueness: Primary always unique; Foreign can repeat.
- Quantity: One Primary Key per table; many Foreign Keys allowed.
Download New Real Time Projects:- Click here
Complete Advance AI topics:-
Conclusion
Foreign keys keep your data consistent and your relationships rock-solid. Use them everywhere you have parent-child data and prevent orphaned records forever. For more SQL tutorials, stay tuned to .
sql foreign key example
sql foreign key w3schools
primary key in sql
foreign key query in sql
foreign key syntax
foreign key in mysql
on delete cascade sql
foreign key references two tables