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.
Code
-- 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
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which relations are involved here?
- `session_cache`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.