PREP WITH PROOF
Menu
SQL & DATA ENGINEERING / PRACTICAL GUIDE

SQLite SAVEPOINT: Partial Rollback, RELEASE and Transaction Ownership

Use SQLite savepoints for partial rollback without committing the outer transaction. Test ROLLBACK TO, RELEASE, nested names and Python autocommit with a runnable lab.

THE QUICK ANSWER

A SQLite savepoint marks a position inside a transaction. ROLLBACK TO rewinds database changes to that mark while keeping it available; RELEASE removes the mark. Releasing an inner savepoint does not commit the outer transaction. If a savepoint started the outermost transaction itself, releasing it can commit. Define who owns the outer transaction before using a helper that creates savepoints.

Give a multi-statement unit its own rollback boundary

Consider an import that writes an item and then writes its audit note. If the item succeeds but the audit note violates a NOT NULL constraint, rejecting only the second statement leaves a half-completed logical unit. The importer needs a boundary around both statements, while keeping unrelated accepted items available for the final batch decision.

The lab below uses invented item and audit tables to make that distinction observable. A savepoint surrounds each unit. A rejected audit note removes the item inserted earlier in the same unit; a rejected duplicate item does not erase previously accepted items. The outer transaction can still commit the accepted subset or discard the whole batch.

This is a policy choice, not an automatic recommendation to keep partial imports. If the business rule requires every source record to succeed together, report the failure and roll back the outer transaction. Savepoints give you a smaller recovery boundary; they do not decide which partial result is acceptable.

Read the commands as operations on a transaction stack

The command names are easy to misread when translating from application words such as save or finish. A savepoint name identifies a database mark, not a separately committed record. The table summarizes the state transitions demonstrated by the executable tests.

Unlike savepoints, BEGIN transactions cannot be nested in SQLite. Our test attempts another BEGIN while a transaction remains active and checks that it is rejected without losing the pending rows. Use a savepoint for the inner boundary rather than treating an inner BEGIN as an independent transaction.

CommandState transitionConsequence for the caller
SAVEPOINT nameAdds a named markCan also start a transaction if none is active
ROLLBACK TO nameRewinds to the mark and cancels newer marksThe target mark remains available
RELEASE nameRemoves marks through the newest matching nameInner release keeps changes pending in the parent
RELEASE of the outermost transaction markEnds that transactionCommits when no outer BEGIN remains
ROLLBACK without TOEnds the entire transactionEarlier accepted units are discarded too
COMMITEnds the entire transactionAll remaining pending units share the final outcome

Source: SQLite: savepoints and nesting rules ↗

Show that inner RELEASE is not an independent commit

The on-disk fixture opens a writer and a separate reader. The writer begins a transaction, inserts row 1, creates an inner mark, inserts row 2 and releases that mark. The writer sees both rows. The reader sees neither. Rolling back the outer transaction then removes both rows.

This check is stronger than looking only at the writer’s query results: seeing a row on the writing connection is not evidence that another connection can see it or that it has been committed. The observer queries in the fixture are fully consumed and do not intentionally hold a long-lived read transaction.

The next test begins with SAVEPOINT outer_mark and no BEGIN. After inserting row 3, releasing that outermost mark ends the transaction and the reader sees the row. Those two outcomes explain why a helper that sometimes runs inside a transaction and sometimes runs alone can accidentally have different commit behavior.

Source: SQLite: visibility between database connections ↗

ROLLBACK TO keeps its target, while removing newer marks

The fixture keeps row 4 before mark, adds row 5 after it, then creates later and adds row 6. ROLLBACK TO mark removes rows 5 and 6. Releasing later afterward fails because that newer mark no longer exists. The database changes before mark remain pending.

The test then inserts row 7 and rolls back to mark again. That second rollback succeeds: the original target survived the first rewind. A subsequent RELEASE mark removes it, and attempting to rewind to that removed name fails.

This is the reason the failure path in import_unit uses both operations. It first rewinds the unit’s changes, then releases the remaining mark before returning to the caller. Releasing without rewinding would retain the successful first statement of a failed two-statement unit.

Make Python transaction ownership explicit

The listing requires Python 3.12 or later and opens connections with autocommit=True. For this teaching configuration, the transaction commands are explicit SQL: execute("BEGIN"), execute("COMMIT") and execute("ROLLBACK"). This keeps the SQL savepoint experiment visible rather than relying on implicit driver transactions.

In that Python mode, Connection.commit() and Connection.rollback() have no effect. The lab deliberately calls writer.commit() while its explicit SQL transaction is active and verifies that the reader still sees no pending rows. Do not mix the API method and SQL command as if they were interchangeable under every driver configuration.

The connection context manager is also not a nested-savepoint manager. The listing uses contextlib.closing to close handles and issues its own SQL transaction commands. If your application instead uses autocommit=False, legacy isolation_level behavior, an ORM or a framework transaction wrapper, review that owner’s contract before adapting this pattern. Changing a connection’s transaction mode mid-operation is not part of the example.

Source: Python 3.12: sqlite3 autocommit and connection context manager ↗

Run the complete disposable SQLite experiment

Save the program as savepoint_lab.py and run python savepoint_lab.py without optimization flags. We executed the exact listing on Python 3.12.14 with SQLite 3.53.1: all 5,029 checks passed. It uses only the standard library, a temporary on-disk database and an in-memory database. No existing database is opened.

The file-based checks cover inner release, reader visibility, outermost release, repeated rollback to the same target, canceled child marks, duplicate names and transaction-ending conflict behavior. After closing the connections, a new connection confirms that committed rows 3 and 4 remain in the disposable file.

The import checks first keep alpha while rejecting beta’s missing audit note, then commit the accepted unit. One hundred seeded batches follow, each with twelve candidate units. Independent Python dictionaries model accepted item quantities and audit notes; after every attempt the SQL tables and transaction state are compared with that model. Each random batch is finally rolled back and checked empty.

import random
import sqlite3
import tempfile
from contextlib import closing
from pathlib import Path

checks = 0


def check(condition):
    global checks
    assert condition
    checks += 1


def rejected(con, statement):
    try:
        con.execute(statement)
    except sqlite3.OperationalError:
        check(True)
    else:
        raise AssertionError('expected SQL error')


def ids(con):
    return [x[0] for x in con.execute('SELECT id FROM t ORDER BY id').fetchall()]


with tempfile.TemporaryDirectory(prefix='savepoint-lab-') as temp:
    path = Path(temp) / 'lab.db'
    with closing(sqlite3.connect(path, autocommit=True)) as writer, \
         closing(sqlite3.connect(path, autocommit=True)) as reader:
        writer.execute('CREATE TABLE t(id INTEGER PRIMARY KEY)')
        writer.execute('BEGIN')
        writer.execute('INSERT INTO t VALUES(1)')
        writer.execute('SAVEPOINT inner_mark')
        writer.execute('INSERT INTO t VALUES(2)')
        writer.execute('RELEASE inner_mark')
        check(writer.in_transaction and ids(writer) == [1, 2])
        check(ids(reader) == [])
        writer.commit()  # no effect with autocommit=True; use explicit SQL
        check(writer.in_transaction and ids(reader) == [])
        writer.execute('ROLLBACK')
        check(ids(writer) == [] and ids(reader) == [])
        # Outermost SAVEPOINT, with no BEGIN: RELEASE ends the transaction.
        writer.execute('SAVEPOINT outer_mark')
        writer.execute('INSERT INTO t VALUES(3)')
        check(writer.in_transaction and ids(reader) == [])
        writer.execute('RELEASE outer_mark')
        check(not writer.in_transaction and ids(reader) == [3])
        writer.execute('BEGIN')
        writer.execute('INSERT INTO t VALUES(4)')
        writer.execute('SAVEPOINT mark')
        writer.execute('INSERT INTO t VALUES(5)')
        writer.execute('SAVEPOINT later')
        writer.execute('INSERT INTO t VALUES(6)')
        writer.execute('ROLLBACK TO mark')
        check(ids(writer) == [3, 4] and writer.in_transaction)
        rejected(writer, 'RELEASE later')
        writer.execute('INSERT INTO t VALUES(7)')
        writer.execute('ROLLBACK TO mark')  # target mark still exists
        check(ids(writer) == [3, 4])
        writer.execute('RELEASE mark')
        rejected(writer, 'ROLLBACK TO mark')
        rejected(writer, 'BEGIN')
        check(ids(writer) == [3, 4] and writer.in_transaction)
        writer.execute('COMMIT')
        check(ids(reader) == [3, 4])
        # Duplicate names resolve from the newest matching mark.
        writer.execute('BEGIN')
        writer.execute('SAVEPOINT duplicate')
        writer.execute('INSERT INTO t VALUES(8)')
        writer.execute('SAVEPOINT duplicate')
        writer.execute('INSERT INTO t VALUES(9)')
        writer.execute('ROLLBACK TO duplicate')
        check(ids(writer) == [3, 4, 8])
        writer.execute('RELEASE duplicate')
        writer.execute('ROLLBACK TO duplicate')
        check(ids(writer) == [3, 4])
        writer.execute('RELEASE duplicate')
        writer.execute('COMMIT')
        writer.execute('BEGIN')
        writer.execute('SAVEPOINT parent')
        writer.execute('INSERT INTO t VALUES(10)')
        writer.execute('SAVEPOINT child')
        writer.execute('INSERT INTO t VALUES(11)')
        writer.execute('RELEASE parent')
        rejected(writer, 'ROLLBACK TO child')
        check(ids(writer) == [3, 4, 10, 11] and ids(reader) == [3, 4])
        writer.execute('ROLLBACK')
        check(ids(reader) == [3, 4])
        # A transaction-ending conflict destroys the savepoint stack.
        writer.execute('BEGIN')
        writer.execute('SAVEPOINT doomed')
        writer.execute('INSERT INTO t VALUES(12)')
        try:
            writer.execute('INSERT OR ROLLBACK INTO t VALUES(3)')
        except sqlite3.IntegrityError:
            check(not writer.in_transaction)
        else:
            raise AssertionError('expected primary-key conflict')
        check(ids(writer) == [3, 4])
        rejected(writer, 'ROLLBACK TO doomed')
    with closing(sqlite3.connect(path, autocommit=True)) as reopened:
        check(ids(reopened) == [3, 4])


def import_unit(con, sku, qty, note):
    # Fixed private name; this helper must not recursively call itself.
    if not con.in_transaction:
        raise ValueError('caller must own an open SQL transaction')
    con.execute('SAVEPOINT import_unit')
    try:
        con.execute('INSERT INTO item VALUES(?,?)', (sku, qty))
        con.execute('INSERT INTO audit VALUES(?,?)', (sku, note))
    except sqlite3.IntegrityError:
        if not con.in_transaction:  # OR ROLLBACK, triggers, etc. may end it
            raise
        con.execute('ROLLBACK TO import_unit')
        con.execute('RELEASE import_unit')
        return False
    else:
        con.execute('RELEASE import_unit')
        return True


with closing(sqlite3.connect(':memory:', autocommit=True)) as con:
    con.execute('CREATE TABLE item(sku TEXT PRIMARY KEY, qty INT CHECK(qty>0))')
    con.execute('CREATE TABLE audit(sku TEXT, note TEXT NOT NULL)')
    con.execute('BEGIN')
    check(import_unit(con, 'alpha', 2, 'accepted'))
    check(not import_unit(con, 'beta', 3, None))
    check(con.execute('SELECT sku FROM item').fetchall() == [('alpha',)])
    check(con.execute('SELECT sku FROM audit').fetchall() == [('alpha',)])
    con.execute('COMMIT')
    check(not con.in_transaction)
    check(con.execute('SELECT qty FROM item').fetchall() == [(2,)])
    con.execute('DELETE FROM item')
    con.execute('DELETE FROM audit')
    rng = random.Random(91)
    for _ in range(100):
        con.execute('BEGIN')
        expected, notes = {}, {}
        for _ in range(12):
            sku, qty = str(rng.randrange(8)), rng.randrange(-1, 4)
            note = None if rng.randrange(4) == 0 else 'accepted'
            valid = sku not in expected and qty > 0 and note is not None
            check(import_unit(con, sku, qty, note) == valid)
            if valid:
                expected[sku], notes[sku] = qty, note
            check(dict(con.execute('SELECT * FROM item').fetchall()) == expected)
            check(dict(con.execute('SELECT * FROM audit').fetchall()) == notes)
            check(con.in_transaction)
        con.execute('ROLLBACK')
        check(con.execute('SELECT COUNT(*) FROM item').fetchone()[0] == 0)
        check(con.execute('SELECT COUNT(*) FROM audit').fetchone()[0] == 0)
    try:
        import_unit(con, 'outside', 1, 'note')
    except ValueError:
        check(not con.in_transaction)
    else:
        raise AssertionError('missing transaction guard')
print('SQLite:', sqlite3.sqlite_version)
print(f'PASS: {checks} checks; disposable SQLite databases only')

Statement failure and unit failure are different scopes

The import tables use ordinary constraint behavior. Under SQLite’s default ABORT policy, a failing statement is undone while preceding statements in the same transaction can remain. That is exactly why the helper must undo the earlier item insertion when the later audit insertion fails.

The helper catches the expected IntegrityError, checks that the transaction still exists, then performs ROLLBACK TO and RELEASE. It is intentionally narrow: a database I/O problem or another operational failure is not a rejected business record to skip. Let the transaction owner handle unexpected failures and decide how to abort or recover.

The separate INSERT OR ROLLBACK test creates a mark and a pending row, then triggers a primary-key conflict. This ends the whole transaction, discards the pending row and removes the savepoint. A later ROLLBACK TO doomed fails. Cleanup code must not assume every exception leaves the original transaction stack intact.

Source: SQLite: conflict resolution ABORT versus ROLLBACK ↗

Prefer private, predictable names and clear nesting ownership

SQLite permits repeated savepoint names. The duplicate-name fixture creates two marks with the same name, rewinds to the newer one, releases it, then successfully rewinds to the older one. That behavior is testable, but it is harder to review than distinct names with obvious ownership.

The import helper uses one fixed private name and explicitly does not support recursive calls to itself. It rejects calls with no open transaction, which prevents it from silently creating and releasing an outermost transaction on its own. The caller must still ensure other helpers do not reuse or manipulate its active mark.

For a reusable transaction abstraction, track ownership and nesting explicitly rather than accepting arbitrary SQL fragments as savepoint names. Parameter placeholders in the lab bind row values; all transaction identifiers and SQL structure are fixed. Error handlers should preserve the original failure if cleanup itself fails, and must not continue writing through an unknown transaction state.

Keep savepoints separate from retries, locks and external effects

A partial rollback can repair the database work done by this unit, but it cannot undo an email, remote API request or file operation performed alongside that work. Keep those effects outside an uncommitted unit or use an application design that coordinates them deliberately. A savepoint is not a distributed transaction.

Savepoints also do not create another independent SQLite writer. A long outer import remains one transaction even if many inner units are released. Decide your batch size, lock policy and retry boundary separately. On a transaction-ending error, restarting a logical unit can require rebuilding its surrounding transaction state rather than merely reissuing RELEASE.

At the final boundary, check the actual COMMIT outcome. Successful inner units are still pending until their outer transaction succeeds. The test suite does not simulate disk failure, crash recovery, lock contention, deferred foreign-key failures, triggers or ORM nesting. Its evidence concerns the stated SQLite operations and ordinary fixture constraints.

Source: SQLite: transactions and response to errors ↗

Use the smallest rollback scope that matches the business rule

For a partial-import policy, mark each multi-statement unit, rewind a rejected unit and release its mark, then let one explicit owner decide the batch outcome. For an all-or-nothing policy, abort the outer transaction when the required unit fails. In both cases, report accepted and rejected work in terms of the final commit decision.

When debugging, inspect the SQL transaction boundary, the current mark and the connection’s transaction configuration before changing error handling. The useful distinction is whether you are removing a mark, rewinding database work or ending the transaction. Keeping those three operations separate makes nested database code easier to reason about.

KEEP THESE THREE THINGS

Your next steps

  1. Define the owner of the outer transaction before adding savepoints.
  2. ROLLBACK TO rewinds changes; RELEASE removes marks.
  3. An inner RELEASE does not make its changes independently committed.
  4. A statement error can leave earlier unit statements intact; test your conflict policy.
  5. Keep driver configuration,unexpected errors andexternal effects explicit.

Sources & official resources

Linked resources checked on 2026-11-03. 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 →