Php Flow » Mysql

How To add/Update FOREIGN KEY Constraints

In this post I will described how to alter table and add new FOREIGN KEY constraints on table.Its very easy 3 steps work. After that you can add predefined trigger like on Delete, On updated, Not set etc.
Which is very useful if you want remove/update parent data with all relationship data which is stored in child table.
mysql-constraints


Step 1: first we add Column in child table.

ALTER TABLE Role ADD COLUMN Parent int(11) UNSIGNED DEFAULT NULL;

Step 2: first we add Index on foreign Key, because MySQL says foreign Key must Index.

ALTER TABLE Table1 ADD INDEX ParentTabl(ParentID)

Step 3: Now alter table and add constraints.

ALTER TABLE `ChildTbl` ADD CONSTRAINT `Parent` FOREIGN KEY(`Parent`) REFERENCES `ChildTbl`(`Id`)

Step 4: Now define trigger if you want add with constraints.
ALTER TABLE ` ChildTbl ` ADD CONSTRAINT `Parent` FOREIGN KEY(`Parent`) REFERENCES ` ChildTbl `(`Id`) ON DELETE CASCADE;

Note: If you are finding ‘Errno 150’ thats mean your PK column(s) in the parent table and the FK column(s) in child table is not same data type.

Did you enjoy this article? Share it!

About the Author:

Hi, This is Parvez Alam from India. I am software developer with 4 years’ experience in web development. I have submitted articles on PHP, Mysql, Magento,CSS, HTML, jQuery, web designing and social API. You can subscribe to my blog via RSS/Twitter/Google plus and Facebook.

Random Posts

One thought on “How To add/Update FOREIGN KEY Constraints

  1. Hi Parvez,

    My opinion is that it’s a bad idea to have foreign keys as the database level. In my opinion, this technically means that you’re moving part of your logic to the RDBMS. It’s more or less like using stored procedures.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>