PostgreSQL: How to Disable or Enable Foreign Key Constraint of a Table

In this post, I am sharing one option to Disable / Enable the Foreign Key Constraint in PostgreSQL.

During data migration and testing purpose, Database Developer requires to disable Foreign key constraint of a Table.

Once you disable constraint, then later you might need to enable again, but during this exercise make sure that all your data changes are correct.

PostgreSQL does not provide any direct command or function to disable / enable the Foreign key constraints.

When you create any Foreign Key on the table, internally It creates a hidden trigger for check data integrity.
You should enable/disable the trigger for achieving disable foreign key constraint.

Create a sample Student Master table:

Insert few sample records in Student Master table:

Create a sample Student Marks table:

Try to insert data with StudID which does not belong to Student Master table:

You will get a below error message:

Disable all hidden triggers of a Student Mark table:

Now Again, try to insert same record:

Once you did with your task, please enable all trigger of a table:


Please share your ideas and opinions about this topic with me, your contribution will add true value to this topic.
If anyone has doubts on this topic then please do let me know by leaving comments or send me an email.

If you like this post, then please share it with others.
Please follow dbrnd.com, I will share my experience towards the success of Database Research and Development Activity.

I put up a post every day, please keep reading and learning.
Discover Yourself, Happy Blogging !
Anvesh M. Patel.

More from dbrnd.com