title: Is it safe to drop and then create the foreign key constraints inside a transaction?
body: <p>I have a table A that references a table B. Table B needs to be populated with updated data from an external source and for efficiency I use TRUNCATE followed by a COPY. This is done even when the application is live.</p>
  
  <p>To further improve efficiency, <a href="http://www.postgresql.org/docs/9.1/static/populate.html" rel="nofollow">as suggested in the documentation</a>, I want to drop and then recreate the foreign keys.</p>
  
  <p>However I have some doubts.</p>
  
  <p>If I drop the FKs, COPY and then recreate FKs <strong>inside the same transaction</strong>, can I be sure that the constraint is preserved even on data inserted in table A during the transaction? I ask this because in theory a transaction is atomic, but in the docs, about the temporary removal of FKs say:</p>
  
  <blockquote>
    <p>there is a trade-off between data load speed and loss of error checking while the constraint is missing.</p>
  </blockquote>
  
  <p>If there's a chance that a wrong reference is inserted in the meantime, what happens when you try to recreate the FK constraints? </p>