Is this a correct understanding of transactions? I have just noticed that one of my TRUNCATE queries takes 16 seconds to complete. I always assumed that TRUNCATE queries were basically-instant.
I currently do this:
TRUNCATE TABLE bigtable RESTART IDENTITY;
INSERT INTO bigtable (col) VALUES ($1); -- This one is run countless times.

Question 1: Since it takes 16 seconds for the TRUNCATE to do its thing, does that mean that for 16 seconds, my applications might be querying the bigtable and get nothing returned?
Question 2: If I do the following, will my applications continue to get the old values until the entire new dataset has been loaded in? Or will something else happen?
BEGIN TRANSACTION;
TRUNCATE TABLE bigtable RESTART IDENTITY;
INSERT INTO bigtable (col) VALUES ($1); -- This one is run countless times.
COMMIT TRANSACTION;

As I understand it, the BEGIN ... COMMIT &quot;block&quot; will basically not &quot;go live&quot; until the COMMIT, at which point both the TRUNCATE and all the INSERTS have taken place, so at that moment, the applications will get the new data, but until then, they will get the old data rather than NO or PARTIAL data?
Correct?
TRUNCATE is indeed very fast, but it has to take an ACCESS EXCLUSIVE lock on the table.
For this, the query has to wait until all concurrent transactions that use the table (even if only for a SELECT!) are done. Only then can it take the lock and execute the actual truncation.
To make it faster, see that concurrent transactions are short. 16 seconds is an awfully long time for a database transaction.
To your questions:

All the transactions that started before the TRUNCATE (and that block it) will see the complete, untruncated table.
All transactions that start after the TRUNCATE will be blocked until the TRUNCATE's transaction is done, even if they only SELECT from the table.

If you TRUNCATE and INSERT in the same transaction, the ACCESS EXCLUSIVE lock is held until the whole transaction is done.
So it will be like in the previous case, but the transactions that started later will see the table filled immediately.