Database Research & Development

  • Home
  • NoSQL
    • NoSQL
    • Cassandra
  • Databases
    • Database Theory
    • Database Designing
    • SQL Server Coding Standards
    • SQL Server
    • PostgreSQL
    • MySQL
    • Greenplum
    • Linux
  • Interviews
    • SQL Server Interviews
    • MySQL Interviews
    • SQL Puzzles
  • DBA Scripts
    • SQL Server DBA Scripts
    • PostgreSQL DBA Scripts
    • MySQL DBA Scripts
    • Greenplum DBA Scripts
  • Home
  • Blog Archives !
  • (: Laugh@dbrnd :)
  • Contact Me !
sqlserverinterviews
Home 2017 February PostgreSQL: How to Disable or Enable Foreign Key Constraint of a Table

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

This article is half-done without your Comment! *** Please share your thoughts via Comment ***

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:

1
2
3
4
5
6
CREATE TABLE tbl_Students
(
StudID INTEGER PRIMARY KEY
,StudName CHARACTER VARYING
,StudClass CHAR(1)
);

Insert few sample records in Student Master table:

1
2
3
4
INSERT INTO tbl_Students
VALUES (1,'Anvesh','A')
,(2,'Neevan','B'),(3,'Jenny','C')
,(4,'Roy','C'),(5,'Martin','C');

Create a sample Student Marks table:

1
2
3
4
5
6
7
8
9
CREATE TABLE tbl_StudentMarks
(
StudentMarkID INTEGER PRIMARY KEY
,StudID INTEGER
,Sub1Mark SMALLINT
,Sub2Mark SMALLINT
,Sub3Mark SMALLINT
,CONSTRAINT fk_tbl_StudentMarks_StudID FOREIGN KEY (StudID) REFERENCES tbl_Students (StudID)
);

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

1
2
INSERT INTO tbl_StudentMarks
VALUES (1,6,50,60,90);

You will get a below error message:

1
2
3
ERROR: insert or update on table "tbl_studentmarks" violates foreign key constraint "fk_tbl_studentmarks_studid"
DETAIL: Key (studid)=(6) is not present in table "tbl_students".
********** Error **********

Disable all hidden triggers of a Student Mark table:

1
ALTER TABLE tbl_StudentMarks DISABLE TRIGGER ALL;

Now Again, try to insert same record:

1
2
INSERT INTO tbl_StudentMarks
VALUES (1,6,50,60,90);

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

1
ALTER TABLE tbl_StudentMarks ENABLE TRIGGER ALL;

Feb 2, 2017Anvesh Patel
SQL Server: After Restart, Database in "In Recovery" status, Can't Access itPostgreSQL: Improve the performance of Query Sort operation by setting work_mem
Comments: 11
  1. :)
    February 3, 2018 at 4:05 am

    Thanks for this, it was very useful and informative. I had to use it to insert default data into the database to prime it for other table to reference it, but it had a FK constraint that needed to be satisfied so this worked!

    • Anvesh Patel
      Anvesh Patel
      February 3, 2018 at 6:50 am

      Your welcome!

  2. Mściwój
    September 13, 2018 at 7:35 am

    drawbacks/missing bits
    – DISABLE TRIGGER ALL requires ADMIN/SU account
    – it speeds up inserts etc… but ultimately can lead to data inconsistency (exactly the example you put). Should cover the topic/best practice of validating it manually as enabling triggers don’t revalidate existing data.

  3. Ravikumar
    October 10, 2018 at 12:45 pm

    Dear Anvesh Patel,
    I disable the triggers(constraint) and inserted the some data and again enable the trigger (constraint) then ???

  4. David Climent
    January 25, 2019 at 5:23 pm

    Thanks a lot, you were so helpful!!

  5. Szymon
    February 20, 2019 at 2:27 pm

    Postgres – can I DISABLE TRIGGER where I’m not relation owner?

    • Anvesh Patel
      Anvesh Patel
      March 8, 2019 at 10:00 am

      yes

  6. Abhishek
    April 5, 2019 at 4:22 am

    I need the same action to be performed in the heroku. But heroku doesnot give the superuser access to us. But disabling the triggers requires the superuser access to psql. Is there any way that I can bypass the superuser access and perform the disable trigger. Or is there any other way than disabling the trigger to copy the records?

  7. CV Kannan
    June 12, 2019 at 5:33 pm

    Thanks for the post. I tried to disable constraints on a table with the syntax provided & getting some errors :-

    alter table AUTOMIC.RT disable TRIGGER ALL;
    ERROR: syntax error at or near “alter”
    LINE 2: alter table AUTOMIC.RT disable TRIGGER ALL;

    ALTER TABLE AUTOMIC.RT DISABLE TRIGGER ALL;
    ERROR: permission denied: “RI_ConstraintTrigger_c_17366” is a system trigger

  8. Tiago van den Berg
    September 12, 2019 at 4:03 pm

    Great Post. Disabling triggers speed up batch processings.

    For simple UPDATE cases where it is necessary, POSTGRES allows deferrable foreign keys. That means that a foreign key will be validated only after commiting transaction. So it is possible to modifiy all records that share a constrained key inside a transaction.

    Its possible to change a FOREIGN KEY with the following command:

    ALTER TABLE Table_Name ALTER CONSTRAINT Constraint_Name_Fk DEFERRABLE INITIALLY DEFERRED;

  9. Alexandre Paiva
    May 1, 2020 at 2:42 pm

    Congratulations Patel, I´m a developer of system computer. I’m migrating from Oracle to PostgreSql, but I have to keep systems running two databases. Very good article, congratulations. I’ll be around more often. Thank you.

Anvesh Patel
Anvesh Patel

Database Engineer

February 2, 2017 PostgreSQLAnvesh Patel, bulk operation, data migration, database, database research and development, dbrnd, Disable Foreign Key Constraint, Foreign Key constraint, plpgsql, Postgres Query, postgresql, PostgreSQL Administrator, PostgreSQL Error, PostgreSQL Performance Tuning, PostgreSQL Programming, PostgreSQL Tips and Tricks, trigger
About Me!

I'm Anvesh Patel, a Database Engineer certified by Oracle and IBM. I'm working as a Database Architect, Database Optimizer, Database Administrator, Database Developer. Providing the best articles and solutions for different problems in the best manner through my blogs is my passion. I have more than six years of experience with various RDBMS products like MSSQL Server, PostgreSQL, MySQL, Greenplum and currently learning and doing research on BIGData and NoSQL technology. -- Hyderabad, India.

About DBRND !

dbrnd

This is a personal blog (www.dbrnd.com).

Any views or opinions represented in this blog are personal and belong solely to the blog owner and do not represent those of people, institutions or organizations that the owner may or may not be associated with in professional or personal capacity, unless explicitly stated.

Feel free to challenge me, disagree with me, or tell me I’m completely nuts in the comments section of each blog entry, but I reserve the right to delete any comment for any reason whatsoever (abusive, profane, rude, or anonymous comments) - so keep it polite.

The content of this website is protected by copyright. No portion of this website may be copied or replicated in any form without the written consent of the website owner.

Recent Comments !
  • Anvesh Patel { Sure will do... } – May 27, 12:43 PM
  • Anvesh Patel { Great... } – May 27, 12:41 PM
  • Anvesh Patel { Great... } – May 27, 12:39 PM
  • Anvesh Patel { Great... } – May 27, 12:36 PM
  • Anvesh Patel { Great... } – May 27, 12:28 PM
  • Anvesh Patel { Great... } – May 27, 12:27 PM
  • Anvesh Patel { Great... } – May 27, 12:16 PM
  • Older »
Follow Me !
  • facebook
  • linkedin
  • twitter
  • youtube
  • google
  • flickr
© 2015 – 2019 All rights reserved. Database Research & Development (dbrnd.com)
Posting....