DEV Community

Gurpinder Singh
Gurpinder Singh

Posted on

How to assign the foreign key in the existing table.

I have a state_list table with a countryID field, but it's currently set as an index and not a foreign key. Now, I want to change it to be a foreign key referencing the country_list table's countryID primary key. How can I make this change?

To change the existing index on the countryID column in the state_list table to a foreign key that references the countryID primary key column in the country_list table, you can follow these steps in MySQL:

How can I check the existing FOREIGN KEY?

Difference between in Index and Foreign Key

-- First, ensure that there is an index on the `countryID` column in the `state_list` table
SHOW INDEX FROM state_list WHERE Key_name = 'index_name';

-- If there is no index, you can create one using the following command
CREATE INDEX index_name ON state_list (countryID);

-- Then, you can add the foreign key constraint to the `countryID` column in the `state_list` table
ALTER TABLE state_list
ADD CONSTRAINT fk_countryID
FOREIGN KEY (countryID) REFERENCES country_list(countryID)
ON DELETE CASCADE
ON UPDATE CASCADE;

Enter fullscreen mode Exit fullscreen mode

In this script:

Replace index_name with the name of the existing index on the countryID column in the state_list table.
Replace fk_countryID with a suitable name for your foreign key constraint.
ON DELETE CASCADE and ON UPDATE CASCADE are optional clauses that define the action to take when a referenced row in the country_list table is deleted or updated. You can adjust these clauses based on your specific requirements.
After running these SQL commands, the countryID column in the state_list table will be changed to a foreign key that references the countryID primary key column in the country_list table. Make sure to back up your data before making any structural changes to your database.

Thanks for reading,
Dgi Host.com

Top comments (0)