ItSolutionStuff.com

How to Rename Column Name Foreign Key Constraint in MySQL Query?

By Hardik Savani • November 5, 2023
MySql

This is more one post on mysql query, I don't remember exactly time but i had need to change name of foreign key constraint column field. We can rename field name easily if we didn't set foreign key constraint. But if you set foreign key constraint then you can't rename easily. I had rename directly from my phpmyadmin without mysql query but i found bellow error:

Query error:

#1025 - Error on rename of './learn/#sql-46c_246' to './learn/my_table' (errno: 150)

But i found the solution of mysql rename foreign key constraint using mysql query, First we have to drop the foreign key, then change the column, at last we need to again add the foreign key constraint back in column.

I give you also if you want to create and check what do then first create "my_table" using bellow mysql query and then fire bellow sql query for rename column.

Create Table:

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

);

Rename Column:

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

Try this it will help you sure.....

Tags: MySql
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Import Database in Mysql using Command Line in Ubuntu?

Read Now →

How to add 1 day to the date column in MySQL?

Read Now →

MYSQL Query for Data between Two Dates Example

Read Now →

PHP MySQL Confirmation Before Delete Record using Ajax Example

Read Now →

How to Add MySQL Trigger from Migration in Laravel?

Read Now →

How to Import CSV File using MySQL?

Read Now →

How to fetch this week records in MySql ?

Read Now →

How to Check Empty or Null Data using MySQL Query?

Read Now →

How to Copy One Table Data into Another Table using MySQL?

Read Now →

How to count unique domains from email address field in MySQL ?

Read Now →

Which MySQL Datatype use for Store an IP Address?

Read Now →

Mysql Hexadecimal Color Code Store in Binary Datatype Example

Read Now →