MySQL Add Foreign Key in MySQL Command Console

Posted on

This is an article which is specifically written to show how to add foreign key in MySQL Database Server. There are lots of means or utilities which can be utilized in order to add foreign key. In MySQL Database Server, add foreign key can be done by executing a certain query in MySQL Command Console or in a MySQL Editor based on GUI.

The query which is specifically executed to add a foreign key in a table can be shown in the following pattern :

mysql> alter table table_name add constraint foreign_key_name foreign key(id_field_name) references other_table_name(id_field_name) on update cascade on delete cascade;

Description : 
alter table : It is the reserved keyword which is used as part of MySQL Query command to alter table by adding a foreign key. 
table_name : The current table which is going to be added with a new foreign key
add constraint : It is the reserved keyword which is used as part of MySQL Query command to alter table by adding a foreign key. 
foreign_key_name : It is the parameter value for 'add constraint' MySQL passed for adding foreign key.
foreign key(id_field_name) : It is the combination of reserved keyword 'foreign key' with a field name or column name which is going to be altered or modified as a foreign key. The name of the field or the column is 'id_field_name'. 
references other_table_name(id_field_name) : It is the combination of reserved keyword 'references' with the field or column which is going to be used as reference for adding new foreign key which is located in the table named 'other_table_name' and the field or column named 'id_field_name'
on update cascade on delete cascade : It is the reserved keyword which is used as part of MySQL Query command to alter table by adding a foreign key. 

The example can be shown as follows :

mysql> alter table server_db add constraint fk_db_server foreign key(id_server) references server(id_server) on update cascade on delete cascade;
Query OK, 0 rows affected (0,03 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql>

The connection or the relationship between two tables for simulating on how to add foreign key can be drawn in form or Entity Relationship Diagram as follows :

As shown in the above Entity Relationship Diagram, the table named ‘server_db’ as a foreign key named ‘id_server’ which is referred from another table named ‘server’ with the column named ‘id_server’.

2 thoughts on “MySQL Add Foreign Key in MySQL Command Console

Leave a Reply