// PostgreSQL error reference

PostgreSQL 25001: cannot run inside a transaction block

Some commands (VACUUM, CREATE DATABASE, CREATE INDEX CONCURRENTLY, ALTER SYSTEM) must run on their own, outside BEGIN ... COMMIT.

SQLSTATE
25001
Name
active_sql_transaction
Category
Invalid Transaction State
Error message
CREATE INDEX CONCURRENTLY cannot run inside a transaction block

What it means

A handful of PostgreSQL commands manage their own transactions or can't be rolled back, so they refuse to run inside an explicit transaction block: VACUUM, CREATE DATABASE, DROP DATABASE, CREATE INDEX CONCURRENTLY, REINDEX ... CONCURRENTLY, ALTER SYSTEM, CREATE TABLESPACE and others. Running one after BEGIN fails with 25001 (active_sql_transaction).

The catch is that many tools and drivers open a transaction for you: migration frameworks wrap each migration in one, and clients with autocommit turned off start one implicitly.

Common causes

  • A migration framework runs every migration inside a transaction.
  • The client or driver has autocommit off (psycopg2's default, JDBC with setAutoCommit(false)), so every statement is inside a transaction.
  • A script sends several statements as one multi-statement query string, which PostgreSQL runs as a single implicit transaction.
  • Calling the command from a function or DO block, which always runs inside a transaction.

How to fix it

  1. Run the command on its own with autocommit on. In psql that is the default; just don't put it between BEGIN and COMMIT.

    CREATE INDEX CONCURRENTLY orders_customer_id_idx ON orders (customer_id);
  2. In your driver, switch autocommit on for this statement (psycopg: conn.autocommit = True).

  3. In migration tools, mark the migration as non-transactional; most frameworks have an option for this.

  4. Send each such command as a separate query, not combined with others in one string.

Reproduce it safely

BEGIN;
VACUUM;  -- ERROR: VACUUM cannot run inside a transaction block
ROLLBACK;

Related errors

More invalid transaction state errors

The code and message text are from the PostgreSQL documentation, Appendix A: PostgreSQL Error Codes. Browse the full PostgreSQL error list or search every database error.

// fewer errors, faster fixes

Work on PostgreSQL in SQLly

A native SQL client for macOS, Windows and Linux with schema-aware IntelliSense, guardrails for risky statements and clear error messages, for PostgreSQL and the other databases you use.