DISCARD ALL Resets Pooled Session State

Clean temporary tables, prepared statements, GUCs, and LISTEN channels with DISCARD ALL before returning pooled connections, outside transactions.

SqlResilience

Code

snippet
-- Create dirty session-scoped state typical of pooled application requests
CREATE TEMP TABLE scratch_ids (id integer);
PREPARE ping_stmt AS SELECT 1 AS ok;
SET app.tenant = 'acme';
LISTEN cache_invalidation;

SELECT
    (SELECT count(*) FROM pg_tables WHERE schemaname LIKE 'pg_temp%' AND tablename = 'scratch_ids') AS temp_tables,
    (SELECT count(*) FROM pg_prepared_statements WHERE name = 'ping_stmt') AS prepared_stmts,
    current_setting('app.tenant', true) AS active_tenant,
    (SELECT count(*) FROM pg_listening_channels() AS c(ch) WHERE ch = 'cache_invalidation') AS listeners;

-- DISCARD ALL resets temp tables, prepared statements, GUCs, and LISTEN channels (cannot run inside BEGIN..COMMIT)
DISCARD ALL;

SELECT
    (SELECT count(*) FROM pg_tables WHERE schemaname LIKE 'pg_temp%' AND tablename = 'scratch_ids') AS temp_tables,
    (SELECT count(*) FROM pg_prepared_statements WHERE name = 'ping_stmt') AS prepared_stmts,
    current_setting('app.tenant', true) AS active_tenant,
    (SELECT count(*) FROM pg_listening_channels() AS c(ch) WHERE ch = 'cache_invalidation') AS listeners;

Behavior overview — DISCARD ALL Resets Pooled Session State

What runs here is SELECT / CREATE — pg_tables, pg_prepared_statements and pg_listening_channels are the objects involved.

scratch_ids spins up isolated session-local scratch tables right inside this script without any prerequisite objects and disappears automatically upon close.

The pieces that do the work: a WHERE clause constraining which rows the statement operates on; COUNT aggregation.

Putting it to use

Nothing outside the file is needed: the session-local tables it touches (scratch_ids) are created by the file itself — point it at a scratch database and run the whole thing.

Core lines

CREATE TEMP TABLE scratch_ids (id integer);
PREPARE ping_stmt AS SELECT 1 AS ok;
LISTEN cache_invalidation;

Interactive Tools for This Topic

FAQ

Which tables or CTEs does it reference?
The references are `pg_tables`, `pg_prepared_statements`, `pg_listening_channels`.