Monday, 24 September 2018

How to Set up a Foreign Key Constraint in MySQL

The following is a simple example that illustrates Foreign Key constraints:


Creating a table for manager:
CREATE TABLE manager (id integer primary key auto_increment, name text) ENGINE=InnoDB;

Creating a table for club and creating a foreign key constraint for manager_id with key 'manager_id_reference':
CREATE TABLE club (id integer primary key auto_increment, is_accessible char, manager_id integer NOT NULL) ENGINE=InnoDB;
ALTER TABLE club ADD CONSTRAINT manager_id_reference FOREIGN KEY(manager_id) REFERENCES manager (id); 

Inserting some managers:
INSERT INTO manager(name) VALUES('Pritom');
INSERT INTO manager(name) VALUES('Kumar');

Inserting some clubs:
INSERT INTO club(is_accessible, manager_id) VALUES(true, 1);
INSERT INTO club(is_accessible, manager_id) VALUES(false, 2);

Let see manager table data (SELECT * FROM manager):
IDNAME
1Pritom
2Kumar

Let see club table data (SELECT * FROM club):
IDIS_ACCESSIBLEMANAGER_ID
111
202
Let see manager table structure (DESCRIBE manager):
FIELDTYPENULLKEYDEFAULTEXTRA
idint(11)NOPRI(null)auto_increment
nametextYES(null)
Let see club table structure (DESCRIBE club):
FIELDTYPENULLKEYDEFAULTEXTRA
idint(11)NOPRI(null)auto_increment
is_accessiblechar(1)YES(null)
manager_idint(11)NOMUL(null)

Now try to delete manager:
DELETE FROM USER WHERE id = 1;

will error as:
Schema Creation Failed: Cannot delete or update a parent row: a foreign key constraint fails (`db_2_8d4a1`.`club`, CONSTRAINT `manager_id_reference` FOREIGN KEY (`manager_id`) REFERENCES `manager` (`id`)):

This happens because the data in the manager table depends on the data in the club table.

Full sqlFiddle

0 comments:

Post a Comment