Foreign Key in SQL
? Foreign Key in SQL
A Foreign Key is a constraint used to link two tables together. It enforces a relationship between columns in two tables, ensuring referential integrity by restricting the values in the child table to only those that exist in the parent table.
? Key Concepts:
Parent Table: The table with the primary key (or unique key).
Child Table: The table with the foreign key referencing the parent.
Ensures that the child table cannot have values in the foreign key column that do not exist in the parent table.
? Syntax for Creating a Foreign Key:
When creating a table:
CREATE TABLE Orders ( OrderID int PRIMARY KEY, CustomerID int, FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID));Adding a foreign key to an existing table:
ALTER TABLE OrdersADD CONSTRAINT fk_customerFOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID);? Example:
Suppose you have two tables:
CREATE TABLE Customers ( CustomerID int PRIMARY KEY, CustomerName varchar(100));CREATE TABLE Orders ( OrderID int PRIMARY KEY, CustomerID int, OrderDate date, FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID));CustomerIDinOrdersmust match aCustomerIDinCustomers.You cannot insert an order with a
CustomerIDthat does not exist inCustomers.
? Foreign Key Actions (optional):
You can specify what happens on DELETE or UPDATE of the parent row:
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)ON DELETE CASCADEON UPDATE CASCADE;CASCADE: Automatically delete/update child rows.
SET NULL: Set child foreign key to NULL.
RESTRICT: Prevent the delete/update if there is a child row (default in many systems).
? Benefits of Foreign Keys:
Maintains data integrity.
Prevents orphan records.
Defines relationships between tables for joins.
If you want, I can help you write foreign keys for your specific table structure or explain how to handle cascading options!