The term 'Foreign Key Constraint' is often tossed around. And I just want to clarify it's exact meaning. We have an employees table and a branches table. The employees table was created first but it should have a foreign key constraint on branch_id, which references the primary (surrogate) key of id on branches table:
CREATE TABLE employees (
id INT AUTO_INCREMENT,
first_name VARCHAR(40),
last_name VARCHAR(40),
birth_day DATE,
sex BOOLEAN,
salary INT,
supervisor_id INT,
branch_id INT,
PRIMARY KEY(id)
)
CREATE TABLE branches (
id INT AUTO_INCREMENT,
branch_name VARCHAR(40),
manager_id INT,
manager_start_date DATE,
PRIMARY KEY(id),
FOREIGN KEY(manager_id) REFERENCES employees(id) ON DELETE SET NULL
)
And now we add the Foreign Key Constraints:
ALTER TABLE employees
ADD FOREIGN KEY(branch_id)
REFERENCES branches(id)
ON DELETE SET NULL;
ALTER TABLE employees
ADD FOREIGN KEY(supervisor_id)
REFERENCES employees(id)
ON DELETE SET NULL;
Notice here I use Add Foreign Key
and not Add Constraint constraint_name
. Here would be an example of using ADD CONSTRAINT
:
ALTER TABLE users
ADD CONSTRAINT check_users_age
CHECK (age>=18 AND city='Philadelphia');
Is ADD FOREIGN KEY
and ADD CONSTRAINT constraint_name
synonymous? Does ADD FOREIGN KEY
, in effect, add a constraint without a name? And if ADD FOREIGN KEY
does add a name, how can I find it in mysql?