---
title: "Roll back to a SQLite savepoint in C#"
url: https://recursiveai.org/onelite/cookbook/roll-back-part-of-sqlite-transaction-with-savepoint/
description: "Use SQLite ROLLBACK TO in C# to undo an optional batch without losing earlier writes. Release the savepoint and commit the rows you want to keep."
version: "1.0.0"
---

# Roll back to a SQLite savepoint in C#

**OneLite** is a free, open-source SQLite-compatible database for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneLite) · [GitHub](https://github.com/recursive-ai-oss/onelite-csharp) · [Docs](https://recursiveai.org/onelite/docs/) · [Download example (.zip)](https://recursiveai.org/onelite/cookbook/roll-back-part-of-sqlite-transaction-with-savepoint/roll-back-part-of-sqlite-transaction-with-savepoint.zip)

Use `ROLLBACK TO` to undo changes after a savepoint while keeping earlier writes.

```shell
dotnet add package RecursiveAI.OneLite
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using RecursiveAI.OneLite;

await using var db =
    await Database.OpenAsync(":memory:");
await db.ExecuteScriptAsync("""
    CREATE TABLE jobs(name TEXT);
    BEGIN;
    INSERT INTO jobs VALUES ('core');
    SAVEPOINT extras;
    INSERT INTO jobs VALUES ('optional');
    ROLLBACK TO extras;
    RELEASE extras;
    COMMIT;
    """);
foreach (var job in await db.QueryAsync<string>(
    $"SELECT name FROM jobs"))
    Console.WriteLine(job);
```

Prints `core`; the optional row is gone.

Unzip [the example](https://recursiveai.org/onelite/cookbook/roll-back-part-of-sqlite-transaction-with-savepoint/roll-back-part-of-sqlite-transaction-with-savepoint.zip), then `dotnet run`.

```text
core
```

## The full program

The download creates a temporary database file. It inserts the required `core` row, then two optional jobs after `SAVEPOINT extras`. It rolls back the optional jobs, releases the savepoint, and inserts `finish` before committing. It reopens the database to read the committed rows and deletes the example file when done. If the named savepoint doesn’t exist, `ROLLBACK TO` fails without undoing anything.

```csharp
using RecursiveAI.OneLite;

string file = Path.Combine(Path.GetTempPath(),
    $"jobs-{Guid.NewGuid():N}.db");
try
{
    await using (var db = await Database.OpenAsync(file))
    {
        await db.ExecuteScriptAsync("""
            CREATE TABLE jobs(id INTEGER PRIMARY KEY, name TEXT);
            BEGIN;
            INSERT INTO jobs(name) VALUES ('core');
            SAVEPOINT extras;
            INSERT INTO jobs(name) VALUES ('optional report'), ('optional email');
            """);
        bool keepExtras = args.Contains("--keep-extras");
        if (!keepExtras)
            await db.ExecuteAsync($"ROLLBACK TO extras");
        await db.ExecuteScriptAsync("""
            RELEASE extras;
            INSERT INTO jobs(name) VALUES ('finish');
            COMMIT;
            """);
    }

    await using var reopened = await Database.OpenAsync(file);
    Console.WriteLine("Committed rows:");
    var jobs = await reopened.QueryAsync<string>($"SELECT name FROM jobs ORDER BY id");
    foreach (var job in jobs)
        Console.WriteLine(job);
}
finally
{
    File.Delete(file);
}
```

`dotnet run` prints:

```text
Committed rows:
core
finish
```

## Variations

**Keep the optional batch.** Run the download with `--keep-extras`. This skips `ROLLBACK TO` but still runs `RELEASE` and `COMMIT`.

```shell
dotnet run -- --keep-extras
```

```text
Committed rows:
core
optional report
optional email
finish
```

## Related recipes

- [Use SQLite transactions in C#](https://recursiveai.org/onelite/cookbook/sqlite-transactions-csharp/)
- [Execute a batch of SQLite commands in C#](https://recursiveai.org/onelite/cookbook/execute-sqlite-command-batch/)

## The short answer

Run `SAVEPOINT extras` after the work you want to keep and before the work you might discard. On the same database connection, `ROLLBACK TO extras` undoes only the changes made since that savepoint. `RELEASE extras` removes the marker. `COMMIT` saves what’s left in the outer transaction.

## How do I roll back to a savepoint in SQLite?

Start the outer transaction with `BEGIN` and write the required rows. Then create the savepoint just before the optional work. The boundary matters: if you create `extras` before inserting `core`, rolling back to `extras` will also undo `core`. If you create it after inserting an optional row, that row will survive the partial rollback.

Run `ROLLBACK TO extras` after a decision to discard that batch. The outer transaction remains active, so you can insert a replacement, continue with the required work, or roll everything back if the required work fails. In C#, keep every statement on the same open connection. The example uses `ExecuteScriptAsync` for fixed SQL containing multiple statements. `ExecuteAsync` and `QueryAsync` use OneLite’s interpolated-SQL API, so the example uses `$"…"` even when there are no values to insert into the SQL.

Through the [OneLite SQLitePCLRaw adapter](https://recursiveai.org/onelite/cookbook/microsoft-data-sqlite-ef-core-without-native-library/), `SqliteTransaction.Save(name)` and `Rollback(name)` also work.

## Does SQLite ROLLBACK undo the whole transaction?

Without `TO`, yes: `ROLLBACK` ends the transaction and undoes all of its uncommitted changes. In the example that would discard `core` as well as any optional rows. With `TO`, SQLite rewinds to the named savepoint, discards any newer savepoints, and leaves the named one active. That’s why `RELEASE extras` still works after `ROLLBACK TO extras`. The [SQLite savepoint rules](https://www.sqlite.org/lang_savepoint.html) also specify what happens when nested savepoints share a name: the most recent matching one is the target. Distinct names make it easier to see which batch a rollback will affect.

## When do you release a savepoint and when do you commit?

Release an inner savepoint when done with it, whether you kept the optional changes or rewound them. In a `BEGIN` transaction, releasing it does not commit the changes to disk. A later outer `ROLLBACK` still undoes work retained by `RELEASE`. Outside an explicit transaction, `SAVEPOINT` can start the transaction itself; in that case, releasing its outermost savepoint commits. For an optional sub-batch of a larger job, use an explicit outer `BEGIN` and leave the final decision to `COMMIT` or full `ROLLBACK`.
