Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I see four useful ways to replace the contents of the table. None of them is "obviously right", but it depends on your requirements.</p> <ol> <li><p>(In a single transaction) <code>DELETE FROM foo; INSERT INTO foo SELECT ...</code></p> <p><strong>Pro:</strong> Best concurrency: doesn't lock out other transactions accessing the table, as it leverages Postgres's MVCC.</p> <p><strong>Con:</strong> Probably the slowest if you measure the insert-speed alone. Causes autovacuum to clean up dead rows, thus creating a higher I/O load.</p></li> <li><p><code>TRUNCATE foo; INSERT INTO foo SELECT ...</code></p> <p><strong>Pro:</strong> Fastest for smaller tables. Causes less write I/O than #1</p> <p><strong>Con:</strong> Excludes all other readers -- other transactions reading from the table will have to wait.</p></li> <li><p><code>TRUNCATE foo</code>, DROP all indexes on table, <code>INSERT INTO foo SELECT ...</code>, re-create all indexes.</p> <p><strong>Pro:</strong> Fastest for large tables, because creating indexes with <code>CREATE INDEX</code> is faster than updating them incrementally.</p> <p><strong>Con:</strong> Same as #2</p></li> <li><p>The switcheroo. Create two identical tables <code>foo</code> and <code>foo_tmp</code></p> <pre><code>TRUNCATE foo_tmp; INSERT INTO foo_tmp SELECT ...; ALTER TABLE foo RENAME TO foo_tmp1; ALTER TABLE foo_tmp RENAME TO foo; ALTER TABLE foo_tmp1 RENAME TO foo_tmp; </code></pre> <p>Thanks to PostgreSQL's transactional DDL capabilities, if this is done in a transaction, the rename is performed without other transactions noticing. You can also combine this with #3 and drop/create indexes.</p> <p><strong>Pro:</strong> Less I/O performed, like #2, and without locking out other readers (locks taken only during the rename part).</p> <p><strong>Con:</strong> The most complicated. Also you cannot have foreign keys or views pointing to the table, as they would point to the <em>wrong</em> table after renaming it.</p></li> </ol>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload