Working with FOREIGN KEY in MySQL 8: A Developer’s Guide

Updated: January 27, 2024 By: Guest Contributor Post a comment

Introduction

When dealing with relational databases, understanding the intricacies of foreign keys is essential for maintaining data integrity and establishing relational links between tables. In this developer’s guide, we will delve into the use of FOREIGN KEY constraints in MySQL 8, covering everything from the basics to more advanced topics with practical examples along the way.

Understanding FOREIGN KEY Constraints

A FOREIGN KEY is a field (or collection of fields) in one table that uniquely identifies a row of another table. It is fundamentally a field that creates a link between two tables. The table containing the foreign key is called the ‘child’ table, and the table containing the candidate key is referred to as the ‘referenced’ or ‘parent’ table.

In MySQL, FOREIGN KEY constraints are used to enforce referential integrity rules to ensure that relationships between records in different tables remain consistent.

CREATE TABLE parent_table (
    id INT PRIMARY KEY,
    name VARCHAR(100)
);

CREATE TABLE child_table (
    id INT PRIMARY KEY,
    parent_id INT,
    FOREIGN KEY (parent_id) REFERENCES parent_table(id)
);

Creating FOREIGN KEY Constraints

To define a FOREIGN KEY constraint during the creation of a table, use the FOREIGN KEY and REFERENCES keywords:

CREATE TABLE orders (
    order_id INT NOT NULL,
    customer_id INT,
    PRIMARY KEY (order_id),
    FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);

This code snippet creates an ‘orders’ table with a FOREIGN KEY that points to the ‘customer_id’ in the ‘customers’ table.

Adding FOREIGN KEY Constraints to Existing Tables

If the table already exists, you can add a FOREIGN KEY constraint using the ALTER TABLE statement:

ALTER TABLE orders
ADD FOREIGN KEY (customer_id)
REFERENCES customers(customer_id);

This SQL command modifies the ‘orders’ table by adding a new FOREIGN KEY constraint on the ‘customer_id’ column.

ON DELETE and ON UPDATE Actions

MySQL allows you to define how foreign key relationships react to deletion or updating of related rows through ON DELETE and ON UPDATE clauses:

CREATE TABLE order_details (
    detail_id INT PRIMARY KEY,
    order_id INT,
    FOREIGN KEY (order_id)
    REFERENCES orders(order_id)
    ON DELETE CASCADE
    ON UPDATE NO ACTION
);

In this example, if an order is deleted, all its related order details are also deleted (CASCADE), while updates to the ‘order_id’ will not trigger any action on the ‘order_details’ rows (NO ACTION).

Checking FOREIGN KEY Constraints Compatibility

When creating FOREIGN KEY constraints, MySQL requires that the data types and lengths of the parent and child columns match. These constraints need to be checked for compatibility:

Parent column data type: INT(11) Child column data type: INT. These match, and therefore, the FOREIGN KEY constraint can be applied.

Resolving FOREIGN KEY Constraint Errors

At times, FOREIGN KEY issues may arise such as when the child table contains values that don’t exist in the parent table. To identify these, you can use diagnostic queries:

SELECT *
FROM child_table
LEFT JOIN parent_table ON child_table.parent_id = parent_table.id
WHERE parent_table.id IS NULL;

This query will identify orphan records in the child table that don’t have corresponding entries in the parent table.

Removing FOREIGN KEY Constraints

To drop a FOREIGN KEY constraint, you’ll need to know the name of the constraint. It can be done using the ALTER TABLE statement followed by DROP FOREIGN KEY:

ALTER TABLE orders
DROP FOREIGN KEY customer_ibfk_1;

This will remove the FOREIGN KEY constraint named ‘customer_ibfk_1’ from the ‘orders’ table.

Composite Foreign Keys

n MySQL, a composite foreign key is a foreign key that consists of two or more columns. This is often used when the foreign key references a primary or unique key consisting of multiple columns. Here’s an example to illustrate how to create and use composite foreign keys in MySQL.

MySQL Example: Creating and Using Composite Foreign Keys

Step 1: Create Parent Table with Composite Primary Key

First, we’ll create a parent table (department) with a composite primary key consisting of two columns.

CREATE TABLE department (
    dept_id INT,
    dept_name VARCHAR(255),
    PRIMARY KEY (dept_id, dept_name)
);

Step 2: Create Child Table with Composite Foreign Key

Next, we create a child table (employee) that references the composite primary key in the department table.

CREATE TABLE employee (
    emp_id INT AUTO_INCREMENT PRIMARY KEY,
    emp_name VARCHAR(255),
    dept_id INT,
    dept_name VARCHAR(255),
    FOREIGN KEY (dept_id, dept_name) REFERENCES department(dept_id, dept_name)
);

In this example:

  • Parent Table – department:
    • Has a composite primary key consisting of dept_id and dept_name.
  • Child Table – employee:
    • Includes columns dept_id and dept_name, which together form a composite foreign key.
    • The FOREIGN KEY constraint is defined to reference the composite primary key in the department table.

Step 3: Inserting Data

Before inserting data into the employee table, make sure to insert the corresponding data into the department table.

-- Insert data into the department table
INSERT INTO department (dept_id, dept_name) VALUES (1, 'Engineering'), (2, 'Human Resources');

-- Insert data into the employee table
INSERT INTO employee (emp_name, dept_id, dept_name) VALUES ('Alice', 1, 'Engineering'), ('Bob', 2, 'Human Resources');

Explantion:

  • The employee table’s foreign key (dept_id, dept_name) references the composite primary key (dept_id, dept_name) of the department table.
  • When inserting data into employee, the values for dept_id and dept_name must exist in the department table, ensuring referential integrity.
  • This setup illustrates a typical scenario where an employee is associated with a department, and the department’s identification involves both an ID and a name.

Composite foreign keys are essential for maintaining data integrity in databases with complex relationships, especially when a single-column foreign key is insufficient to uniquely identify related rows in another table.

Conclusion

The FOREIGN KEY constraint is a powerful tool for database integrity and relationships management. With this guide, you should understand the basics of defining, adding, and troubleshooting foreign keys in MySQL 8, ensuring that your applications handle data responsibly and efficiently.