SQL Foreign Key Constraint

SQL Foreign Key Constraint

SQL FOREIGN KEY Constraint

A FOREIGN KEY is a column (or a set of columns) in one table that refers to the PRIMARY KEY in another table. It creates a relationship between the two tables and ensures referential integrity by restricting actions that would break the link.


Key Features

  1. Referential Integrity:

    • Ensures that the value in the foreign key column matches a value in the referenced primary key column or is NULL.
  2. Parent-Child Relationship:

    • The table containing the foreign key is the child table, and the table with the primary key is the parent table.
  3. Cascading Actions:

    • Allows automatic propagation of changes (e.g., ON DELETE CASCADE or ON UPDATE CASCADE) from the parent table to the child table.

Syntax

1. Inline Definition (During Table Creation)

CREATE TABLE child_table ( column1 DataType, column2 DataType, FOREIGN KEY (column1) REFERENCES parent_table (primary_key_column) );

2. Named Foreign Key Constraint

CREATE TABLE child_table ( column1 DataType, column2 DataType, CONSTRAINT fk_name FOREIGN KEY (column1) REFERENCES parent_table (primary_key_column) );

3. Adding a Foreign Key to an Existing Table

ALTER TABLE child_table ADD CONSTRAINT fk_name FOREIGN KEY (column1) REFERENCES parent_table (primary_key_column);

Example

1. Create Tables with a Foreign Key

Parent Table: Departments
CREATE TABLE Departments ( DepartmentID INT PRIMARY KEY, DepartmentName VARCHAR(50) );
Child Table: Employees
CREATE TABLE Employees ( EmployeeID INT PRIMARY KEY, Name VARCHAR(50), DepartmentID INT, FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID) );

2. Adding Foreign Key to an Existing Table

ALTER TABLE Employees ADD CONSTRAINT fk_department FOREIGN KEY (DepartmentID) REFERENCES Departments (DepartmentID);

3. Cascading Actions

ON DELETE CASCADE

If a row in the parent table is deleted, the corresponding rows in the child table are also deleted.

CREATE TABLE Employees ( EmployeeID INT PRIMARY KEY, Name VARCHAR(50), DepartmentID INT, FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID) ON DELETE CASCADE );
ON UPDATE CASCADE

If the primary key value in the parent table is updated, the foreign key values in the child table are updated accordingly.

CREATE TABLE Employees ( EmployeeID INT PRIMARY KEY, Name VARCHAR(50), DepartmentID INT, FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID) ON UPDATE CASCADE );

Violations and Errors

  1. Insertion Violation:

    • Inserting a row in the child table with a foreign key value that doesn't exist in the parent table results in an error.
    INSERT INTO Employees (EmployeeID, Name, DepartmentID) VALUES (1, 'Alice', 999); -- Error: 999 does not exist in Departments
  2. Deletion Violation:

    • Attempting to delete a row from the parent table that is referenced by the child table causes an error (unless ON DELETE CASCADE is used).

Benefits of FOREIGN KEY

  1. Data Integrity:

    • Ensures consistent and valid relationships between tables.
  2. Error Prevention:

    • Prevents orphaned records (child records without a matching parent).
  3. Simplified Maintenance:

    • Cascading updates and deletions make managing related records easier.

Best Practices

  1. Index Foreign Key Columns:

    • Index foreign key columns to improve query performance.
  2. Use Descriptive Names:

    • Name constraints meaningfully, e.g., fk_employees_departments.
  3. Test Cascades:

    • Ensure cascading actions behave as expected, especially in critical systems.
  4. Avoid Circular References:

    • Prevent situations where foreign key constraints create loops between tables.

Common Use Cases

  1. Parent-Child Relationships:

    • Linking orders to customers, employees to departments, etc.
  2. Data Integrity:

    • Enforcing that orders cannot exist without a valid customer.
  3. Hierarchical Data:

    • Storing organizational structures or category trees.

Conclusion

The FOREIGN KEY constraint is essential for maintaining relational integrity in SQL databases. It enforces valid relationships between tables and prevents actions that could lead to inconsistent data. Cascading actions provide flexibility for managing related records effectively.

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close