# Postgres UNLOGGED tables: how much faster they really are, and exactly what you lose

We measured UNLOGGED tables on PostgreSQL 17.11: a million-row bulk load took only 17% less time, small cache writes were 2.9× faster, reads didn't change, and synchronous_commit = off on a normal table came within a few percent of the same speedup. Then we crashed the server to show what you lose, and explain why a serverless suspend counts too.

**`CREATE UNLOGGED TABLE` is the closest thing Postgres has to a "go faster" switch: the table skips the write-ahead log. People reach for it when they want Postgres to act as a cache, a session store or a staging area for ETL. We measured how much it actually buys you on PostgreSQL 17.11, the major version Relyt One runs. A bulk load of a million rows took only 17% less time. Small single-row upserts, the way a cache is written, ran 2.9 times faster. Reads didn't change at all. And a normal table with `synchronous_commit = off` was almost as fast as the unlogged one, without losing all its rows when the server crashes. That's the price of `UNLOGGED`: after any crash the table comes back empty. On Relyt One, where compute is serverless, its rows don't survive a compute suspend either. Every Postgres number and error message below comes from scripted replays you can run yourself.**

## The short version

- **Writes get faster, reads don't.** `UNLOGGED` removes WAL writes and the flush at commit. It does nothing for `SELECT`.
- **The gain depends on how you commit.** One big `INSERT … SELECT` of a million rows: 4.4 s → 3.6 s. Upserts into a 100,000-key cache from 8 clients, one row per transaction: about 24,500 → 70,800 transactions per second.
- **`synchronous_commit = off` gave 2.8× on a normal table.** A crash can lose the last fraction of a second of commits, but the table is never emptied.
- **Any crash empties the table**, even right after a `CHECKPOINT`. A clean shutdown keeps the rows. Identity and `serial` sequences on the table restart at 1.
- **Unlogged tables don't reach standbys.** Querying one on a replica is an error.
- **On a serverless compute, a suspend counts.** On Relyt One, unlogged tables live only on the compute's local disk, so their rows don't survive a suspend and resume, a resize, or a new branch.

Use `UNLOGGED` only for data you can rebuild without anyone noticing. If what you're really after is faster commits, try `synchronous_commit = off` first.

## What UNLOGGED actually skips

Every change to a normal table is written twice: once to the table's data pages, and once to the write-ahead log (WAL). At `COMMIT`, Postgres waits until the WAL record is flushed to disk. That flush is what makes a committed row survive a crash, and the WAL stream is also what replicas and point-in-time recovery replay.

An unlogged table skips the WAL for its data. The [CREATE TABLE documentation](https://www.postgresql.org/docs/17/sql-createtable.html#SQL-CREATETABLE-UNLOGGED) states the trade-off directly: unlogged tables are "considerably faster than ordinary tables", but "they are not crash-safe: an unlogged table is automatically truncated after a crash or unclean shutdown," and their contents "are also not replicated to standby servers."

Everything attached to the table inherits that. Here are the catalog entries for two otherwise identical tables, each with an identity primary key and one extra index. `relpersistence` is `p` for permanent and `u` for unlogged:

```sql
CREATE UNLOGGED TABLE events_unlogged (
  id         bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  user_id    int  NOT NULL,
  payload    text NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX ON events_unlogged (user_id);

SELECT c.relname, c.relkind, c.relpersistence
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname = 'public' ORDER BY 1;
```

```text
           relname           | relkind | relpersistence
-----------------------------+---------+----------------
 events_logged               | r       | p
 events_logged_id_seq        | S       | p
 events_logged_pkey          | i       | p
 events_logged_user_id_idx   | i       | p
 events_unlogged             | r       | u
 events_unlogged_id_seq      | S       | u
 events_unlogged_pkey        | i       | u
 events_unlogged_user_id_idx | i       | u
```

The indexes and the identity sequence are unlogged too. Unlogged sequences arrived in PostgreSQL 15. Before that, the sequence behind an unlogged table's identity column was logged, so it kept counting after a crash.

## How we tested

Everything ran in a throwaway `postgres:17.11-alpine` container with default settings (`shared_buffers` 128 MB, `synchronous_commit` on, `wal_level` replica) on an Apple M1 Pro laptop, with 5 CPUs and 12 GB of memory given to Docker. The load generator was the container's own `pgbench` 17.11. Each measurement ran three times. The scripts, the logs, and a second script that builds a streaming standby are in the post's run record.

Absolute numbers depend heavily on the disk. A laptop SSD behind Docker's virtual machine flushes at a different speed than a cloud volume. Read the ratios, not the raw throughput.

## Bulk loads: 15–20% faster, not 10×

The first test is the classic ETL case: load a million rows into an empty table with one statement, then update every row. Before each run the table was truncated and the server checkpointed. The table shows the median of three runs. We read the WAL volume from `pg_current_wal_insert_lsn()` before and after.

```sql
INSERT INTO events_unlogged (user_id, payload)
SELECT (random()*100000)::int, md5(g::text) || md5((g*7)::text)
FROM generate_series(1, 1000000) g;

UPDATE events_unlogged SET payload = upper(payload);
```

| Table    | Insert (s) | Update (s) |
| -------- | ---------- | ---------- |
| Logged   | 4.38       | 6.45       |
| Unlogged | 3.64       | 5.50       |

The logged table wrote 273 MB of WAL for the insert and about 410 MB for the update; the unlogged table wrote under 100 bytes for either. Both tables ended up at 144 MB including indexes.

Skipping almost 700 MB of WAL cut the insert time by 17% and the update time by 15%. In one big statement, WAL is written sequentially in large chunks, and the statement waits for a flush only once, at `COMMIT`. Most of the time goes into building heap pages, maintaining two B-tree indexes and generating the data. If your bulk loads are slow, [`COPY` and batching](/blog/postgres-bulk-insert-copy-vs-insert) are usually worth much more than `UNLOGGED`.

## Small writes: 2.9× faster, and synchronous_commit = off gets 2.8×

A cache doesn't take writes in batches of a million. It takes many small writes, each in its own transaction. Here the cost that matters is the WAL flush at every `COMMIT`. We filled two key-value tables with 100,000 keys and ran this upsert as a `pgbench` script from 8 clients for 30 seconds (`:tbl` is the table, `:k` a random key):

```sql
\set k random(1, 100000)
INSERT INTO :tbl (key, value, expires_at)
VALUES ('session:' || :k, jsonb_build_object('n', :k, 'at', now()), now() + interval '5 minutes')
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, expires_at = EXCLUDED.expires_at;
```

We also ran it a third way: against the normal table, with `synchronous_commit = off` set for the session through `PGOPTIONS`.

| Table                | Upserts/s | Latency (ms) |
| -------------------- | --------- | ------------ |
| Logged               | 24,500    | 0.33         |
| Unlogged             | 70,800    | 0.11         |
| Logged, async commit | 68,200    | 0.12         |

![Cache upserts per second from 8 clients: about 24,500 on a logged table, 70,800 on an unlogged table and 68,200 on a logged table with synchronous_commit off](/blog/assets/8a03f9ce0659aa76.svg)

Values are the median of three runs, rounded. Runs varied: the logged table did 21,630 to 25,450 per second, the unlogged one 70,341 to 72,317, and asynchronous commit 62,365 to 74,414.

The unlogged table was 2.9 times faster. The surprise is the third row: a normal table with asynchronous commit got 2.8 times, and its best run beat every unlogged run. Both remove the same bottleneck, which is waiting for the WAL flush before `COMMIT` returns. They differ in what a crash costs:

- With `synchronous_commit = off`, the WAL is still written; Postgres just doesn't wait for the flush. The [documentation](https://www.postgresql.org/docs/17/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT) puts the maximum delay at three times `wal_writer_delay` (200 ms by default). A crash can lose the transactions committed in that window, and "the database state will be just the same as if those transactions had been aborted cleanly." Everything older is safe, and replicas still receive it.
- With `UNLOGGED`, a crash loses the entire table.

You also don't have to change the setting server-wide. It works per session, per role (`ALTER ROLE cache_writer SET synchronous_commit = off`), or per transaction:

```sql
CREATE TABLE page_views (path text, viewed_at timestamptz);

BEGIN;
SET LOCAL synchronous_commit = off;
INSERT INTO page_views (path, viewed_at) VALUES ('/pricing', now());
COMMIT;
```

## Reads: no difference

The same two tables, 8 clients, 30 seconds of primary-key lookups that skip expired entries:

```sql
SELECT value FROM :tbl WHERE key = 'session:' || :k AND expires_at > now();
```

| Run | Logged | Unlogged |
| --- | ------ | -------- |
| 1   | 78,361 | 77,903   |
| 2   | 77,385 | 72,684   |
| 3   | 80,497 | 79,853   |

Those are reads per second, and the differences are noise. A read doesn't wait for a WAL flush, and both tables live in the same shared buffers. If your cache is slow to read, `UNLOGGED` won't help; an index or a smaller row will.

## What you lose: a crash empties the table

We stopped the server in two ways with both kinds of tables full. `docker restart` stops the official image with `SIGINT`, which Postgres treats as a fast shutdown: it writes a final checkpoint and exits cleanly. After that, every table still had all its rows.

Then we ran a `CHECKPOINT` and killed the server with `docker kill -s KILL`, the same as a power cut or the kernel's OOM killer. The server log on the next start said `database system was not properly shut down; automatic recovery in progress`, and:

```text
       tbl       |  count
-----------------+---------
 cache_logged    |  100000
 cache_unlogged  |       0
 events_logged   | 1000000
 events_unlogged |       0
```

```text
 next_unlogged_id | next_logged_id
------------------+----------------
                1 |        3000003
```

Three things to take from this:

- **The checkpoint didn't help.** The data pages had been written to disk moments before, but on recovery Postgres resets every unlogged table to its empty "init fork" without looking at them. It cannot tell whether those pages are consistent, so it throws them all away.
- **The table and its indexes still exist**, empty and usable. Nothing errors; queries return zero rows. Your application has to treat empty as normal.
- **The identity sequence restarted at 1.** If anything outside the table remembered those IDs, they will be reused.

### Replicas and backups

On a streaming standby built with `pg_basebackup`, the table is in the catalog, but reading it fails:

```text
ERROR:  cannot access temporary or unlogged relations during recovery
```

So you can't move cache reads to a read replica if the cache table is unlogged. Physical backups such as `pg_basebackup` copy only the empty init fork, so a restore also gives you an empty table. `pg_dump` does include unlogged data, unless you pass `--no-unlogged-table-data` or dump from a standby, where it is always skipped.

### Foreign keys

A normal table can't reference an unlogged one, because a crash would leave it pointing at rows that no longer exist:

```text
ERROR:  constraints on permanent tables may reference only permanent tables
```

The other direction works. An unlogged `sessions` table can reference a normal `users` table.

## On serverless Postgres, a suspend counts too

On a server you run yourself, "after a crash" is a rare event. On serverless Postgres, where storage is separate from compute, there's a much more common one.

On Relyt One, an idle compute suspends, and the next connection resumes it. Table data doesn't live on the compute; it lives in a separate storage layer, and a compute fetches pages from it on demand. That works because every change is in the WAL. Unlogged tables have no WAL, so their rows never reach the storage layer. They are kept only on the compute's local disk, and when the compute stops, that copy is gone.

So on Relyt One, treat an unlogged table as scratch space that belongs to one running compute:

- **Its rows don't survive a suspend and resume.** If the cache was warm in the evening and nobody connected overnight, don't expect those rows in the morning.
- **Resizing the compute has the same effect.** A resize stops the compute and starts it again at the new size.
- **A new branch doesn't get the rows.** Branches are created from the storage layer, and the rows were never there.

Plan for that from the start: your application should be able to refill an unlogged table from scratch after any compute restart, not just after the rare crash.

## A cache table that expects to lose its contents

If you keep a cache in Postgres, `UNLOGGED` fits, as long as the application treats an empty table as a cache miss:

```sql
CREATE UNLOGGED TABLE cache (
  key        text PRIMARY KEY,
  value      jsonb NOT NULL,
  expires_at timestamptz NOT NULL
);
CREATE INDEX cache_expires_at_idx ON cache (expires_at);

-- set
INSERT INTO cache (key, value, expires_at)
VALUES ('user:42:profile', '{"name": "Ada", "plan": "pro"}', now() + interval '5 minutes')
ON CONFLICT (key) DO UPDATE
  SET value = EXCLUDED.value, expires_at = EXCLUDED.expires_at;

-- get (a miss returns zero rows)
SELECT value FROM cache WHERE key = 'user:42:profile' AND expires_at > now();

-- purge expired entries in batches
DELETE FROM cache
WHERE ctid IN (SELECT ctid FROM cache WHERE expires_at <= now() LIMIT 10000);
```

The `get` filters on `expires_at`, so an expired row is a miss even before the purge removes it. Run the purge from your application's scheduler or a background job. Batching keeps each `DELETE` short. Deleted rows still occupy space until autovacuum reclaims it, as with any table that churns.

Good fits: rendered fragments, rate-limit counters you can afford to reset, results of slow queries, ETL staging tables you reload from the source anyway. Bad fits: anything that's the only copy, such as sessions you can't afford to drop at once, job queues, or carts.

## Changing your mind: SET LOGGED and SET UNLOGGED

You can switch a table either way with `ALTER TABLE … SET LOGGED` or `SET UNLOGGED`. Both rewrite the whole table into a new file, and the rewrite holds an `ACCESS EXCLUSIVE` lock that blocks reads too. Switching to logged also writes the entire table into the WAL, since replicas and recovery need a copy:

```sql
SELECT pg_relation_filenode('events_unlogged') AS filenode_before;
ALTER TABLE events_unlogged SET LOGGED;
SELECT pg_relation_filenode('events_unlogged') AS filenode_after;
```

The file node changed (16433 before, 16454 after), which is the rewrite. On our million-row, 144 MB table, the `ALTER` took 1.0 second and wrote 165 MB of WAL. The identity sequence and indexes changed with it. The common ETL pattern of "load unlogged, then `SET LOGGED`" therefore still pays for the WAL in the end. It only wins if the loading involved many updates or deletes that you'd otherwise have logged.

`SET UNLOGGED` fails if a normal table still has a foreign key to this one. PostgreSQL's message, verbatim, names the referencing table:

```text
ERROR:  could not change table "users_u" to unlogged because it references logged table "orders_p"
```

To find every unlogged table in a database:

```sql
SELECT n.nspname AS schema, c.relname AS table, pg_size_pretty(pg_total_relation_size(c.oid)) AS size
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relpersistence = 'u' AND c.relkind IN ('r', 'p')
ORDER BY pg_total_relation_size(c.oid) DESC;
```

## Which one to use

- **Normal table**: the data matters. That's most tables.
- **Normal table with `synchronous_commit = off`** (per role or per transaction): you want fast small writes and can lose the last fraction of a second on a crash, but not the whole table. In our test, this was within a few percent of `UNLOGGED`.
- **`UNLOGGED` table**: the data is shared between connections, can be rebuilt, and losing every row at any moment is acceptable. Good for caches and staging tables.
- **`TEMPORARY` table**: the data belongs to one session and should disappear when it ends. Other connections can't see it.

## Try it on a branch

The SQL above uses only standard PostgreSQL 17 features, and Relyt One runs PostgreSQL 17. To find out what a cold cache costs your application, create a branch, empty the cache table there with `TRUNCATE`, point a staging copy of your app at the branch and measure the warm-up. Nothing you do on a branch touches its parent, so delete it when you're done. For more on the write path, see [bulk inserts measured](/blog/postgres-bulk-insert-copy-vs-insert); for a queue that does need to survive crashes, see [job queues with SKIP LOCKED](/blog/postgres-job-queue-skip-locked).

[Start for free](/auth/signin?ref=blog-postgres-unlogged-tables)
