A foreign key constraint enforces referential integrity by linking a column in one table to the primary key of another table.
Explanation:
- Ensures valid relationships between tables.
- Prevents deleting referenced data unless cascading rules are set.
Example SQL Foreign Key Constraint:
sqlCopyEditCREATE TABLE Employees (
emp_id INT PRIMARY KEY,
dept_id INT,
FOREIGN KEY (dept_id) REFERENCES Departments(dept_id) ON DELETE SET NULL
);
Here, if a department is deleted, dept_id
in Employees
will be set to NULL instead of being removed.
Leave a Reply