Video in progress

What is an unlogged table, and when can you use it?

An unlogged table isn't written to the WAL, so writes are several times faster. But after a crash or an unclean shutdown it is emptied, and it never reaches the replicas. It suits temporary data you can rebuild.

📖 Answer

CREATE UNLOGGED TABLE import_staging (
    line_no bigint,
    raw     text
);

Where I use it:

  • an intermediate stage of a big import: load a CSV into an unlogged table with COPY, clean it up, then INSERT ... SELECT into the main table;
  • a cache, or intermediate report results that can be recomputed;
  • in tests, for speed.

Where I don't: any data whose loss would hurt the business. After crash recovery, an unlogged table is automatically TRUNCATEd. On a clean shutdown, though, the data is kept, so in local testing everything looks fine and people get fooled.

A trap with replicas: the table definition exists on the replica but the data doesn't, and trying to read from it gives the error cannot access temporary or unlogged relations during recovery. After a failover, the table on the new primary is empty.

You can change the state:

ALTER TABLE import_staging SET LOGGED;

But this rewrites the whole table and writes it fully to the WAL, with an ACCESS EXCLUSIVE lock.

How it differs from a temporary table (CREATE TEMP TABLE): a temp table is visible to only one session and disappears when the session closes, while an unlogged table is shared by all sessions.