A Python data script can run cleanly in local testing and then fail later in execution. The crash shows up as sqlite3.OperationalError: cannot start a transaction within a transaction. This note covers why SQLite raises it, how to fix it in an existing codebase, and how to structure database calls so it doesn't come back.
The symptom
A script might run for several minutes and then halt on sqlite3.OperationalError: cannot start a transaction within a transaction. It usually happens when the code issues an explicit BEGIN right before a batch of deletes or updates.
The error means the connection already has a transaction open when your script calls BEGIN a second time [1]. SQLite won't open a new transaction on a connection that has one active, so the engine rejects the statement and Python raises the operational error.

Why it happens
Python's built-in sqlite3 library gives you a standard DB-API interface to lightweight, disk-based databases [2]. By default, the driver manages transactions implicitly.
Before it runs a Data Modification Language statement (a DML statement), the module opens a transaction for you [3]. DML here means the usual write operations: INSERT, UPDATE, DELETE, and REPLACE [3].
From the engine's side, reads and writes always happen inside a transaction [4]. You can start one by hand with BEGIN, but any query that touches the database starts one automatically if none is open [4].
So the first modification query your script runs opens a transaction, and the connection stays in that state until your code calls commit() or rollback().
If a script runs updates or deletes before it sends an explicit BEGIN, a transaction is already in progress. SQLite reads that BEGIN as a nested transaction request, which it doesn't support, and aborts the statement.
This tends to show up in workflows that prepare staging data before a bulk update. A setup phase might purge stale records or update status flags, which opens an implicit transaction. When the bulk step then issues BEGIN, the database rejects it.
The fix
The fix is to make your script's transaction logic match what the driver actually does.
One option is to drop the explicit BEGIN statements entirely. Let the implicit driver transaction handle write state, call conn.commit() at the end of the run, and call conn.rollback() in your error handlers.
If you need explicit control over transaction boundaries, open the connection with autocommit=True or set isolation_level=None. The autocommit parameter decides whether the driver manages transactions for you or leaves it to you [5]. In autocommit mode the driver doesn't start implicit transactions, so you run BEGIN, COMMIT, and ROLLBACK yourself.
If you are designing backend workflows or expanding your data pipelines, you can explore our automation consultancy services to learn more about building resilient script architectures.

Reproduce it yourself
This needs only the Python standard library. We ran both examples on Python 3.12.10. The first one uses the default connection settings. The default isolation_level is an empty string, which means the driver opens transactions for you before write statements. It is not None: None turns that behavior off [2].
import sqlite3
conn = sqlite3.connect(":memory:")
print(repr(conn.isolation_level), conn.in_transaction)
conn.execute("CREATE TABLE jobs (id INTEGER PRIMARY KEY, status TEXT)")
conn.execute("INSERT INTO jobs (status) VALUES ('old')")
print(conn.in_transaction)
try:
conn.execute("BEGIN")
except sqlite3.OperationalError as exc:
print(exc)
conn.rollback()
print(conn.in_transaction)The output was:
'' False
True
cannot start a transaction within a transaction
FalseThe INSERT quietly opened a transaction, so conn.in_transaction became True and the manual BEGIN failed. A rollback() closed it again.
The second example opens the connection with isolation_level=None. Now the driver never opens a transaction on its own, and your own BEGIN works.
import sqlite3
conn = sqlite3.connect(":memory:", isolation_level=None)
conn.execute("CREATE TABLE jobs (id INTEGER PRIMARY KEY, status TEXT)")
conn.execute("INSERT INTO jobs (status) VALUES ('old')")
print(conn.in_transaction)
conn.execute("BEGIN")
print(conn.in_transaction)
conn.execute("UPDATE jobs SET status = 'new'")
conn.execute("COMMIT")
print(conn.in_transaction, conn.execute("SELECT status FROM jobs").fetchall())The output was:
False
True
False [('new',)]On Python 3.12 and later you can pass autocommit=True to sqlite3.connect() for the same manual control [2]. We checked that BEGIN and ROLLBACK work on such a connection.
How to prevent it
Decide on transaction boundaries early and you avoid collisions at runtime.
Pick one strategy when you start a Python SQLite project. Either rely on default implicit handling and never call BEGIN yourself, or turn on autocommit and manage the boundaries manually. Mixing implicit transaction opening with explicit SQL commands leads straight to driver conflicts.
Audit your code for setup routines that are followed by an explicit BEGIN. That sequence causes most failures of this kind. Removing the redundant BEGIN lets the driver do its normal job.
Run integration tests against realistic data sizes. A small test set can skip the conditional prep queries entirely, so the implicit transaction never opens until production volume sends the script down that path.
Remember that implicit transactions cover every standard DML statement, including INSERT, UPDATE, DELETE, and REPLACE [3]. Any of them opens a transaction if the connection is idle.
Summary checklist
Use this checklist when you build or review Python scripts that talk to SQLite:
- Choose one transaction approach (implicit driver management or explicit autocommit) and apply it consistently across the script.
- Remove manual
BEGINSQL statements if you are using default connection settings. - In implicit mode, place a single
conn.commit()call at the end of a successful run. - Add exception handling that calls
conn.rollback()when an error occurs during execution. - Pass
autocommit=Trueor setisolation_level=Noneif your design requires manualBEGINstatements. - Check data preparation steps for early INSERT, UPDATE, DELETE, or REPLACE queries that open implicit transactions.
- Test scripts against production-like data sets so conditional write statements don't trigger unexpected transaction boundaries.