Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to alter a MySQL table's foreign key using the command line

How to alter an existing table in MySQL, setting foreign key to another table, using the command line?

like image 903
el ninho Avatar asked Jun 17 '12 18:06

el ninho


People also ask

How can I change foreign key in MySQL?

Here is how you would do that: ALTER TABLE my_table ADD FOREIGN KEY (key) REFERENCES other_table(id) ON DELETE SET NULL; And that's it!! That's how you change a foreign key constraint in MySQL!

How do I add a foreign key constraint in MySQL using alter command?

Here's the syntax to create foreign key in MySQL. ALTER TABLE table_name ADD CONSTRAINT constraint_name FOREIGN KEY (foreign_key_name,...) REFERENCES parent_table(column_name,...); In the above query, table_name is the the table where you want to add foreign key.

Can we ALTER TABLE to add foreign key?

Here, you will see how to make the student_id attribute foreign key in the exam table which is the primary key in the student table as follows. ALTER TABLE exam ADD FOREIGN KEY(student_id) REFERENCES student(student_id);


1 Answers

You have to drop existing foreign key and create another one. For example like this:

ALTER TABLE my_table DROP FOREIGN KEY my_key;
ALTER TABLE my_table ADD CONSTRAINT my_key FOREIGN KEY ('some_id') 
REFERENCES some_new_table ('some_other_id') ON UPDATE CASCADE ON DELETE CASCADE;
like image 94
WojtekT Avatar answered Oct 24 '22 14:10

WojtekT