- Note that the FOREIGN KEY constraints can only reference tables within the same database.
- The structure and data type of the primary key and the foreign key must be the same
parent table (e.g.)
CREATE TABLE departments (
department_id INT PRIMARY KEY,
department_name VARCHAR(20) NOT NULL
);
INSERT INTO departments (department_id, department_name) VALUES
(1, 'IT'),
(2, 'HR'),
(3, 'PR');
child table
namedCREATE TABLE employees (
employee_id INT PRIMARY KEY,
name VARCHAR(60) NOT NULL,
department_id INT,
CONSTRAINT fk_department
FOREIGN KEY (department_id)
REFERENCES departments(department_id)
);
unnamed FK (bad practice)CREATE TABLE employees (
employee_id int PRIMARY KEY,
name VARCHAR(60) NOT NULL,
department_id INT,
FOREIGN KEY (department_id)
REFERENCES departments(department_id)
);
Referential actions
using:
specifying different actions:
CASCADE
:
- if a row in the parent table is deleted or updated,
all matching rows will be deleted or updated automatically;
SET NULL
:
- if a row in the parent table is deleted or updated,
all matching foreign key values in the child table will be set to NULL
;
RESTRICT
:
- if we try to update or delete a row in the parent table,
the operation will be rejected;
SET DEFAULT
:
- if a row with the corresponding value is deleted or updated,
the FK value in the child table will be set to the default value;
NO ACTION
:
- this keyword can mean different actions depending on a dialect.
- In MySQL, it is equivalent to the
RESTRICT
keyword,
so if we create the table employees with one of the queries above,
delete and update actions in the table departments will be forbidden.
CREATE TABLE employees (
employee_id int PRIMARY KEY,
name VARCHAR(60) NOT NULL,
department_id INT,
CONSTRAINT fk_department
FOREIGN KEY (department_id)
REFERENCES departments(department_id)
ON DELETE SET NULL
ON UPDATE CASCADE
);
Add FOREIGN KEY to the existing table
unnamedALTER TABLE employees
ADD FOREIGN KEY (department_id)
REFERENCES departments(department_id);
named or FK-constraint to multiple columnsALTER TABLE employees
ADD CONSTRAINT fk_department
FOREIGN KEY (department_id)
REFERENCES departments(department_id);
If you want to create a table with multiple foreign key columns, just specify multiple columns in the parentheses. You can also add ON UPDATE and ON DELETE actions to these queries if you want to specify them. Drop foreign key
ALTER TABLE employees
DROP FOREIGN KEY fk_department;
In MySQL, we have to know the name of the foreign key to delete it.
This is one of the reasons why using named foreign keys is good practice,
but even if you create an unnamed foreign key constraint,
DBMS will generate the name automatically.
To get the foreign key name in this case, use the following syntax:SHOW CREATE TABLE table_name;
This query will show the autogenerated CREATE TABLE query for your table, and the foreign key name will be a part of this query.