PREP WITH PROOF
Menu
SQLITE & PYTHON / PRACTICAL GUIDE

SQLite RETURNING in Python: Finish the Cursor Before COMMIT

Fix SQLite COMMIT failures caused by unread RETURNING rows. Run a Python example comparing fetchall, cursor close and rollback with explicit transaction ownership.

THE QUICK ANSWER

A SQLite write with unread RETURNING output can block COMMIT on the same connection. Consume the result or close its cursor before committing. Closing discards unread output; it does not undo the write. The transaction owner must still commit or roll back using the API appropriate to the connection mode.

A returned row is not a commit receipt

An UPDATE succeeds, fetchone() returns a plausible record, and the following COMMIT raises “cannot commit transaction - SQL statements in progress.” The tempting repair is to retry the write, increase the timeout, or assume another process owns the database. First inspect the cursor produced by that UPDATE. A write with RETURNING can still have unread output on the same connection.

This guide isolates that case with a disposable in-memory database. It is aimed at Python developers who need updated values and also own the transaction boundary. The complete example runs on Python 3.12 or later with SQLite 3.35.0 or later. The published example was executed on Python 3.12.14 with SQLite 3.53.1. It does not measure disk durability, contention between processes, ORM behavior or performance.

The central question is what your application has finished: reading a result, completing a SQL statement, or committing a transaction. Those are separate checkpoints. A service can receive useful values before it has a successful commit, so returning them immediately as a durable success response creates a gap between what the caller believes and what the database has accepted.

What RETURNING gives the application

RETURNING adds result columns to a top-level INSERT, UPDATE or DELETE. For example, UPDATE item SET quantity = quantity + 5 RETURNING id, quantity returns the affected identifiers and their updated quantities. DELETE returns the removed values. This can avoid a separate lookup when the application needs the values associated with its write.

SQLite prepares the changes before emitting RETURNING rows, buffers the output, and does not promise output order. These changes are not necessarily committed. An AFTER trigger can also change values after the values reported by RETURNING were computed. Keep returned records narrow, identify them by key, and query again when you specifically require final trigger-adjusted values.

For the fixture below, the expected records are compared after sorting by identifier. That sort belongs to the Python assertion; it does not claim an ordering guarantee for SQL output. The business invariant is that all three quantities increased by five, independently of which returned row arrived first.

Source: SQLite transactions: pending statements and COMMIT ↗

Choose one owner for BEGIN and COMMIT

The example deliberately sets autocommit=True and controls the transaction using SQL BEGIN, COMMIT and ROLLBACK. In this Python mode, Connection.commit() and Connection.rollback() do nothing. Use con.execute("COMMIT") for this example. Replacing it with con.commit() would hide the failure being demonstrated and leave the explicit transaction active.

This is an explicit-ownership teaching setup, not a recommendation to switch an existing application’s transaction mode. Python also provides autocommit=False with commit()/rollback() ownership and a legacy mode. Read the configuration where the connection is constructed before copying a boundary into a shared utility. A helper receiving somebody else’s connection should not silently commit their unrelated work.

An application-level transaction may contain inventory changes, a ledger entry and an audit record. Finishing the inventory cursor should not decide when all three become a unit. Keep cursor cleanup close to the statement; keep the final transaction decision with the code that knows the whole operation. The table describes only the explicit BEGIN setup used here.

Action in this fixtureResult outputExplicit transaction
fetchone() with more rows pendingOne row read; more remainStill active; early COMMIT fails
fetchall() to exhaustionAll output consumedStill active until SQL COMMIT or ROLLBACK
cur.close()Unread output discardedStill active; close does not undo the UPDATE
SQL COMMIT after completionNo pending write outputUpdated values retained
SQL ROLLBACK after cursor closeNo pending write outputOriginal values restored

Run three completion paths against a fresh database

Save this as returning_demo.py and run python returning_demo.py in a disposable environment. Each path creates its own table and three starting rows, so the close case is not accidentally inheriting the consume case’s committed values. The only changed input is how the application finishes the cursor and transaction.

The first COMMIT is intentionally premature. The test requires an OperationalError and an active transaction; it does not depend on the exact English error text. After that failure, consume reads the remaining records and commits, close discards unread records and commits, and rollback closes the cursor before undoing the transaction. Every path checks the final table and transaction state.

The connection is explicitly closed with contextlib.closing. That wrapper manages resource lifetime; it does not choose a successful commit for the application. The database is in memory, so this script creates no persistent database file. Its assertions exercise completion semantics, rather than proving that a storage device has safely persisted bytes.

import sqlite3
from contextlib import closing


def database():
    con = sqlite3.connect(':memory:', autocommit=True)
    con.execute('CREATE TABLE item(id INTEGER PRIMARY KEY, quantity INTEGER)')
    con.executemany('INSERT INTO item VALUES (?, ?)', [(1, 10), (2, 20), (3, 30)])
    return con


def snapshot(con):
    return con.execute('SELECT id, quantity FROM item ORDER BY id').fetchall()


def experiment(action):
    with closing(database()) as con:
        before = snapshot(con)
        con.execute('BEGIN')
        cur = con.execute('UPDATE item SET quantity = quantity + ? RETURNING id, quantity', (5,))
        first = cur.fetchone()
        assert first is not None
        try:
            con.execute('COMMIT')
        except sqlite3.OperationalError as exc:
            print('Early COMMIT:', exc)
            assert con.in_transaction
        else:
            raise AssertionError('Expected an unfinished write statement')
        if action == 'consume':
            rows = [first, *cur.fetchall()]
            assert sorted(rows) == [(1, 15), (2, 25), (3, 35)]
            assert cur.rowcount == 3
        cur.close()  # Discard unread output for close/rollback cases.
        assert con.in_transaction  # Closing a cursor did not end BEGIN.
        con.execute('ROLLBACK' if action == 'rollback' else 'COMMIT')
        expected = before if action == 'rollback' else [(1, 15), (2, 25), (3, 35)]
        assert snapshot(con) == expected
        assert not con.in_transaction
        print(action, snapshot(con))


if __name__ == '__main__':
    print('SQLite', sqlite3.sqlite_version)
    for action in ('consume', 'close', 'rollback'):
        experiment(action)

Read the outcomes without confusing close with cancel

The consume and close paths both finish with [(1, 15), (2, 25), (3, 35)]. The rollback path finishes with [(1, 10), (2, 20), (3, 30)]. These are observed results from this fixture. In particular, fetching one row did not limit the UPDATE to one database row. The WHERE clause, not the number of fetch calls, defines the rows being changed.

Closing the cursor is appropriate when you intentionally do not need the remaining values. It is not a partial undo operation. If a caller asks for one changed record, clarify whether the write should target one record or whether a broader write is intended and only one output is useful. Those are different application contracts, and throwing away output cannot repair an overly broad predicate.

The published example was also checked with 500 seeded small datasets across consume, close and rollback paths. A separate Python list transformation computed the expected quantities, including empty matches, negative values and zero increments. The checks compared returned records, final table values and transaction state. They do not cover every SQLite build or concurrency scenario.

A practical completion and error-handling sequence

For a bounded result that the application needs, execute the parameterized statement, consume all returned rows inside the transaction, close the cursor, then commit at the owning boundary. Publish a success response only after that boundary succeeds. For large results, design a bounded write unit instead of collecting an unlimited list in a request handler.

If application validation fails after the UPDATE, close its cursor and roll back the owned transaction. For a reusable helper, propagate failure to the caller rather than deciding to roll back a shared connection without a contract. Use a savepoint when the caller explicitly permits a smaller rollback scope; the related SAVEPOINT guide covers that separate decision.

If COMMIT fails, do not automatically execute the UPDATE again. In the demonstrated pending-statement case, the original write is still inside the transaction. Retrying the mutation could apply the increment twice. Finish or close the relevant cursor first, then let the transaction owner choose whether to retry COMMIT or abandon the operation. Other errors require their own handling.

Keep external effects outside this small demonstration. Sending a message, charging an account or acknowledging a remote job merely because RETURNING produced an identifier does not establish a successful database commit. Applications needing reliable coordination should design that boundary explicitly; this cursor example is not an implementation of a distributed transaction.

Source: Python 3.12 sqlite3: transaction control, cursors and rowcount ↗

Troubleshoot the same symptom in an existing program

Start with a minimal trace: the connection’s configured transaction mode, the SQL operation, whether the cursor was exhausted or closed, and the boundary that failed. Record error codes when available. Keep credentials and returned customer data out of diagnostics; a transaction identifier and cursor lifecycle are usually more useful than dumping every row.

Look for a loop that breaks after the first returned record, a generator that yields database results to a slow caller, or a shortcut such as con.execute(...).fetchone() whose cursor lifetime is unclear. A shortcut still creates a cursor. Give it a name when its cleanup matters, and finish it deliberately before the commit boundary.

A cursor’s rowcount should not be used as an early completion signal. Python documents that returned rows must be fetched for the affected-row count to update. In the consume path, the assertion checks rowcount only after fetchall(). For an empty match, expect an empty returned collection; do not invent a changed identifier or infer a successful business update from statement execution alone.

If all write cursors are finished and COMMIT still reports a busy database, broaden the investigation to other connections and transaction lifetimes. The related lock guide covers that topic. A timeout is not a substitute for finishing your own pending write statement. Conversely, finding unread output does not prove that every busy error in the application has this cause.

Finish the statement, then decide the transaction

RETURNING is useful when a write must report the values it affected. Make the lifetime of that report explicit: consume it when needed, close it when intentionally discarded, and keep commit or rollback under a clearly named owner. Treat the values as provisional until the relevant commit succeeds.

The three-path fixture gives a compact regression case for a refactor that introduces RETURNING into existing code. Preserve its final-state assertions when adapting the idea to your schema, and add tests for your actual transaction mode and failure boundaries. A returned row answers what the statement produced; the successful commit answers whether the owned transaction completed.

KEEP THESE THREE THINGS

Your next steps

  1. Returned values are provisional until the owning transaction commits.
  2. Fetching one result does not limit a multirow UPDATE.
  3. Consume results or explicitly close the cursor before the commit boundary.
  4. Closing a cursor and rolling back a transaction are different operations.
  5. The example uses SQL transaction commands with Python autocommit=True.

Sources & official resources

Linked resources checked on 2026-11-05. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →