I have a project where I'd like to replace all the rows in a table periodically with new data. That data will 99% of the time have the previous rows with updated data and some new ones. There are other tables that have a foreign key with this table. Is it possible to create a SQL script which drops all the previous rows, bulk imports the new data and keeps the foreign keys?

I've tried using DROP table and bulk INSERT after that, but the foreign key constraints are dropped as well. I've also tried TRUNCATE table or DELETE FROM without success.

The last option I have is to only INSERT/UPDATE/DELETE what's needed, but for this table and the kind of data it has, I would prefer rebuilding everything.

Thanks in advance!

  • 1
    Have you tried by removing FK, truncate, bulk insert and adding FK again?
    – McNets
    Commented Oct 20, 2021 at 18:29
  • @McNets Thanks for the reply. Yes, I've read something like that. Is there any way to do that programatically? Like looking at some postgres internal table?
    – Martyns
    Commented Oct 20, 2021 at 18:37
  • 1
    Why not just use insert on conflict() and update the existing rows
    – user1822
    Commented Oct 20, 2021 at 19:30


Browse other questions tagged or ask your own question.