UNLOGGED Table Staging Tradeoffs

Trade WAL writes for speed with CREATE UNLOGGED: faster inserts for rebuildable staging data, with the table truncated after a crash and never replicated.

SqlData Integrity

Code

snippet
-- UNLOGGED 表不写 WAL:写入更快,但崩溃后表被清空、也不走流复制
CREATE UNLOGGED TABLE session_cache (
    session_id uuid        NOT NULL,
    payload    jsonb       NOT NULL,
    expires_at timestamptz NOT NULL
);

-- 适合:可丢失的临时数据——会话缓存、ETL 中转、试算结果
INSERT INTO session_cache (session_id, payload, expires_at)
VALUES ('11111111-1111-1111-1111-111111111111',
        '{"user": 42}',
        now() + interval '30 minutes');

-- 不适合:任何需要持久保证或复制到备库的业务数据
-- 索引照常可用,变的只是 durability 语义
CREATE INDEX session_cache_expires ON session_cache (expires_at);

-- 清理过期会话
DELETE FROM session_cache WHERE expires_at < now();

How the snippet works

Several statements share this file — INSERT / DELETE / CREATE, with session_cache among the objects involved.

Breaking the statements into their working parts: a WHERE clause narrowing which rows one statement affects; NOT NULL qualifiers on the required columns.

Applying it

The session_cache table is the working surface here.

Statements that matter

INSERT INTO session_cache (session_id, payload, expires_at)
VALUES ('11111111-1111-1111-1111-111111111111',
'{"user": 42}',
now() + interval '30 minutes');
CREATE UNLOGGED TABLE session_cache (
session_id uuid        NOT NULL,
payload    jsonb       NOT NULL,
expires_at timestamptz NOT NULL
);
CREATE INDEX session_cache_expires ON session_cache (expires_at);

Interactive Tools for This Topic

FAQ

Which relations are involved here?
`session_cache`.