Temp Table ON COMMIT DROP Lifecycle
Session-private temp tables either survive commits (the default) or vanish with ON COMMIT DROP, which requires an enclosing transaction.
Code
-- TEMP 表只有本会话可见;默认 ON COMMIT PRESERVE ROWS 跨提交存活
CREATE TEMP TABLE staging_ids (account_id bigint) ON COMMIT PRESERVE ROWS;
INSERT INTO staging_ids VALUES (7), (42);
SELECT COUNT(*) FROM staging_ids;
-- 正式表与临时表联用:只处理本次草稿里的账号
UPDATE accounts
SET status = 'migrating'
WHERE id IN (SELECT account_id FROM staging_ids);
-- ON COMMIT DROP 必须包在显式事务里:自动提交模式下语句一提交表就被删
BEGIN;
CREATE TEMP TABLE once_only (account_id bigint) ON COMMIT DROP;
INSERT INTO once_only VALUES (99);
SELECT COUNT(*) FROM once_only;
COMMIT;
-- COMMIT 之后 once_only 已不存在;staging_ids 还活着,断开连接才回收
SELECT COUNT(*) FROM staging_ids;Inside the snippet
Several statements share this file — SELECT / INSERT / UPDATE / CREATE, with staging_ids, accounts and once_only among the objects involved.
staging_ids and once_only are created in this same file as session-local temp tables — nothing needs to exist beforehand, and they go away at session end (or right at commit, for the ON COMMIT DROP one).
Breaking the statements into their working parts: a WHERE clause narrowing which rows one statement affects; COUNT aggregation.
Putting it to use
The file is self-contained: it creates the session-local tables it uses (staging_ids, once_only), so run it as a whole against a scratch database.
Core lines
UPDATE accounts
SET status = 'migrating'
WHERE id IN (SELECT account_id FROM staging_ids);
CREATE TEMP TABLE staging_ids (account_id bigint) ON COMMIT PRESERVE ROWS;
CREATE TEMP TABLE once_only (account_id bigint) ON COMMIT DROP;
Interactive Tools for This Topic
FAQ
- Which relations are involved here?
- `staging_ids`, `accounts`, `once_only`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.