- SQL Basics
- SQL Introduction
- SQL Syntax
- SQL Sample Database
- SQL SELECT
- SQL WHERE
- SQL ORDER BY
- SQL DISTINCT
- SQL LIMIT
- SQL FETCH
- SQL AND
- SQL OR
- SQL BETWEEN
- SQL IN
- SQL LIKE
- SQL IS NULL
- SQL Comparison Operators
- SQL Logical Operators
- SQL Alias
- SQL CASE
- Joins and Subqueries
- SQL INNER JOIN
- SQL LEFT JOIN
- SQL RIGHT JOIN
- SQL FULL OUTER JOIN
- SQL SELF JOIN
- SQL CROSS JOIN
- SQL Subquery
- SQL Correlated Subquery
- SQL UNION
- SQL INTERSECT
- SQL EXCEPT
- Aggregate Functions
- SQL AVG
- SQL COUNT
- SQL MAX
- SQL MIN
- SQL SUM
- SQL GROUP BY
- SQL HAVING
- SQL ROLLUP
- SQL CUBE
- SQL GROUPING SETS
- Database Management
- SQL CREATE DATABASE
- SQL ALTER DATABASE
- SQL DROP DATABASE
- SQL BACKUP DATABASE
- SQL SHOW DATABASES
- SQL SELECT DATABASE
- Table Management
- SQL CREATE TABLE
- SQL ALTER TABLE
- SQL ADD COLUMN
- SQL DROP COLUMN
- SQL DROP TABLE
- SQL TRUNCATE TABLE
- SQL SHOW TABLES
- SQL RENAME TABLE
- SQL Constraints
- SQL Primary Key
- SQL Foreign Key
- SQL UNIQUE Constraint
- SQL CHECK Constraint
- SQL NOT NULL Constraint
SQL FOREIGN KEY
In relational databases, data is rarely stored in a single, massive table. Instead, it is organized into smaller, logical tables. A FOREIGN KEY is the "glue" that holds these tables together. It is a constraint that links a column (or a group of columns) in one table to the PRIMARY KEY of another table.
This relationship establishes a parent-child hierarchy. The table containing the primary key is called the Parent (or Referenced) table, and the table containing the foreign key is the Child (or Referencing) table. By enforcing this link, the database ensures referential integrity, meaning you cannot have a child record that points to a non-existent parent.
Orders table "points" to a Users table to identify which customer placed the order.
Key Features of SQL FOREIGN KEY
- Data Consistency: It ensures that values in the child table must already exist in the parent table. You can't assign an order to a Customer ID that doesn't exist.
- Prevents Orphaned Records: It stops developers from accidentally deleting parent records that are still being referenced by other tables.
- Relationship Mapping: It defines how data entities interact, such as One-to-Many or Many-to-Many relationships.
- Multi-Column Support: A foreign key can reference a composite primary key (a key made of multiple columns) in the parent table.
INT, UUID, or VARCHAR) as the Primary Key it references.
SQL FOREIGN KEY Syntax
Creating a FOREIGN KEY in Table Creation
When designing a new schema, you define the foreign key relationship directly within the CREATE TABLE statement. This ensures the rule is active from the moment the table is born.
-- The Parent Table
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
FullName VARCHAR(100) NOT NULL
);
-- The Child Table
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
OrderDate DATE,
EmployeeID INT, -- This will store the link
FOREIGN KEY (EmployeeID) REFERENCES Employees(EmployeeID)
);
- In this example,
EmployeeIDin theOrderstable is the foreign key. - It "references" the
EmployeeIDin theEmployeestable. - The database will reject any attempt to insert an order with an
EmployeeIDthat is not present in theEmployeestable.
FK_ChildTable_ParentTable.
Adding a FOREIGN KEY to an Existing Table
In real-world projects, requirements change. You might need to link two existing tables that were previously independent. We use the ALTER TABLE command for this.
ALTER TABLE Orders
ADD CONSTRAINT FK_Employee_Order
FOREIGN KEY (EmployeeID) REFERENCES Employees(EmployeeID);
Removing a FOREIGN KEY
There are times—such as during a major database refactor or when migrating data—that you might need to drop a constraint.
-- Syntax for SQL Server / Oracle / MySQL
ALTER TABLE Orders
DROP CONSTRAINT FK_Employee_Order;
-- Syntax for MySQL (specifically)
ALTER TABLE Orders
DROP FOREIGN KEY FK_Employee_Order;
ON DELETE and ON UPDATE Actions
What happens to the child record when the parent record is deleted? SQL allows you to define "Referential Actions" to handle these scenarios automatically.
1. Cascade (The "Trickle Down" effect)
If a parent record is deleted, all associated child records are automatically deleted. This is useful for "all-or-nothing" data, like an Order and its individual OrderItems.
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
EmployeeID INT,
FOREIGN KEY (EmployeeID) REFERENCES Employees(EmployeeID)
ON DELETE CASCADE
);
- If Employee #10 is fired and deleted from
Employees, every order they ever handled inOrderswill be permanently wiped out. Use this with caution!
2. Set NULL (The "Detach" effect)
If the parent is deleted, the child record remains, but the reference column is set to NULL. This is common when you want to keep historical records but the association no longer exists.
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
EmployeeID INT,
FOREIGN KEY (EmployeeID) REFERENCES Employees(EmployeeID)
ON DELETE SET NULL
);
- If an employee is deleted, the
EmployeeIDfield inOrdersbecomesNULL, effectively making the order "unassigned" rather than deleting it.
NO ACTION (the default). If you try to delete a parent that has children, the database will simply throw an error and stop you. This is the safest way to prevent accidental data loss.
Summary
- A FOREIGN KEY creates a logical link between two tables, ensuring valid relationships.
- It protects referential integrity, preventing "orphaned" data that points to nothing.
- You can manage constraints during table creation or later using ALTER TABLE.
- Use ON DELETE CASCADE to sync deletions, or SET NULL to preserve child data without a parent.
- Properly indexed Foreign Keys can also significantly improve the performance of
JOINqueries.