Today now in this post i will show you How to rename column name foreign key constraint in MySql? Some days ago i was face a problem, I don’t remember the exactly time but i had need to change the name of foreign key constraint column field. Now from here you can rename the field name easily if we didn’t set the foreign key constraint. But if we want to set foreign key constraint then we can’t rename this easily. I had rename the directly from my phpmyadmin without mysql query but i was found the bellow error:
Query error: #1025 - Error on rename of './learn/#sql-46c_246' to './learn/my_table' (errno: 150)
I was try to find a solution. And i was found the solution of mysql rename foreign key constraint by using mysql query, at First we need to drop the foreign key, then change the column, so at last we need to do again add the foreign key constraint back in the column.
So here I will give you a example also if you want to create and check what we do then first need to create “my_table” by using bellow mysql query and then need to fire bellow sql query for rename column.
CREATE TABLE my_table ( id int unsigned not null AUTO_INCREMENT key, name VARCHAR(255) default null, user_id int unsigned not null, CONSTRAINT `my_table_user_id_fk` FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE ON UPDATE CASCADE );
ALTER TABLE `my_table` DROP FOREIGN KEY `my_table_user_id_fk`, CHANGE COLUMN user_id sender_id int unsigned not null, ADD CONSTRAINT `my_table_sender_id_fk` FOREIGN KEY (`sender_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
Thanks for read. I hope it help you. For more you can follow us on facebook.