Full answer
Sample schema and data:
CREATE TABLE numbers (n int);
INSERT INTO numbers SELECT generate_series(1, 10);SET statement_timeout = '100ms'; SELECT pg_sleep(1);Result on PostgreSQL 17:
ERROR: canceling statement due to statement timeoutBEGIN; SET LOCAL statement_timeout = '5s'; SELECT count(*) AS rows_counted FROM numbers; SHOW statement_timeout;Result:
statement_timeout
-------------------
5s
(1 row)COMMIT; SHOW statement_timeout;Output:
statement_timeout
-------------------
0
(1 row)The one-second sleep is cancelled after 100 ms with 'canceling statement due to statement timeout'. SET LOCAL changes the value for the current transaction only: inside it the limit shows 5s, and after COMMIT the setting is back to 0, meaning no limit. It is 0 rather than 100ms because the first script ran as one implicit transaction that failed, and a SET inside a failed transaction is rolled back along with everything else. In production, a typical pattern is ALTER ROLE web_app SET statement_timeout = '5s' and a longer limit for a reporting role, with exceptions raised by SET LOCAL in the few transactions that need more time.
CREATE TABLE numbers (n int);
INSERT INTO numbers SELECT generate_series(1, 10);
SET statement_timeout = '100ms'; SELECT pg_sleep(1);
BEGIN; SET LOCAL statement_timeout = '5s'; SELECT count(*) AS rows_counted FROM numbers; SHOW statement_timeout;
COMMIT; SHOW statement_timeout;Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
- statement_timeout cancels long statements
- SET LOCAL scopes to a transaction
- ALTER ROLE sets defaults per role
- Different roles need different limits
- Pair with lock_timeout and idle timeouts
Common mistakes
- No timeout on web-facing roles
- Setting a global timeout that breaks maintenance jobs
Follow-ups
- What is idle_in_transaction_session_timeout for?
- How does a timeout interact with connection poolers?
Tips
- Show SET LOCAL scope