Full answer
Sample schema and data:
sql
CREATE TABLE prices (sku text PRIMARY KEY, price int);
INSERT INTO prices VALUES ('PEN', 10), ('INK', 45);sql
CREATE TEMP TABLE staging (sku text, price int); INSERT INTO staging VALUES ('PEN', 12), ('PAD', 60); SELECT count(*) AS staged FROM staging;Output:
text
staged
--------
2
(1 row)In a second session:
sql
SELECT count(*) FROM staging;PostgreSQL returns:
text
ERROR: relation "staging" does not existsql
INSERT INTO prices SELECT sku, price FROM staging ON CONFLICT (sku) DO UPDATE SET price = EXCLUDED.price; SELECT sku, price FROM prices ORDER BY sku;Result on PostgreSQL 17:
text
sku | price
-----+-------
INK | 45
PAD | 60
PEN | 12
(3 rows)sql
BEGIN; CREATE TEMP TABLE scratch (x int) ON COMMIT DROP; INSERT INTO scratch VALUES (1); COMMIT; SELECT to_regclass('scratch') IS NULL AS dropped;Result:
text
dropped
---------
t
(1 row)Session A loads two rows into its staging table, and session B cannot see the table at all: 'relation "staging" does not exist'. Merging from staging updates PEN and adds PAD. The ON COMMIT DROP table vanished when its transaction ended. With PgBouncer in transaction mode, session-lifetime temporary tables can leak between clients that share a server connection, so ON COMMIT DROP is the safer choice there.
sql
CREATE TABLE prices (sku text PRIMARY KEY, price int);
INSERT INTO prices VALUES ('PEN', 10), ('INK', 45);
CREATE TEMP TABLE staging (sku text, price int); INSERT INTO staging VALUES ('PEN', 12), ('PAD', 60); SELECT count(*) AS staged FROM staging;
-- session B
SELECT count(*) FROM staging;
INSERT INTO prices SELECT sku, price FROM staging ON CONFLICT (sku) DO UPDATE SET price = EXCLUDED.price; SELECT sku, price FROM prices ORDER BY sku;
BEGIN; CREATE TEMP TABLE scratch (x int) ON COMMIT DROP; INSERT INTO scratch VALUES (1); COMMIT; SELECT to_regclass('scratch') IS NULL AS dropped;Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
- Temp tables are private to a session
- ON COMMIT DROP removes them at transaction end
- ON COMMIT DELETE ROWS empties them
- Not WAL-logged; analyse manually
- Be careful with transaction poolers
Common mistakes
- Using session temp tables behind transaction pooling
- Forgetting ANALYZE on large temp tables
Follow-ups
- How do unlogged tables differ?
- When would a CTE replace a temp table?
Tips
- Mention poolers