---
title: "Transactions: COMMIT, ROLLBACK and savepoints"
description: "How transactions work in CoraDB: auto-commit, COMMIT and ROLLBACK, savepoints, transactional DDL, cursor holdability and recovery."
url: "https://www.coradb.ai/manual/sql/transaction.html"
markdown_url: "https://www.coradb.ai/manual/markdown/sql/transaction.md"
product: "CoraDB"
version: "1.0"
keywords: "coradb transaction, commit, rollback, savepoint, partial rollback, autocommit, cursor holdability, transactional ddl, database recovery"
---

# Transactions: COMMIT, ROLLBACK and savepoints

A transaction is a group of SQL statements that CoraDB treats as one unit: either all of its changes become permanent (**COMMIT**) or none of them do (**ROLLBACK**). Transactions give each user a consistent view of the data while many users read and write at the same time, and they let the database recover to a consistent state after a failure.

| Topic | Page |
|---|---|
| COMMIT, ROLLBACK, savepoints, cursor holdability, recovery | This page |
| How concurrent transactions see data: MVCC, snapshots, VACUUM | [Concurrency and MVCC](https://www.coradb.ai/manual/sql/transaction_mvcc.html) |
| Locks, lock modes, deadlocks and lock timeouts | [Locking](https://www.coradb.ai/manual/sql/transaction_locking.html) |
| READ COMMITTED, REPEATABLE READ and SERIALIZABLE | [Isolation levels](https://www.coradb.ai/manual/sql/transaction_isolation.html) |

In short: CoraDB uses multiversion concurrency control (MVCC). A transaction's changes are invisible to others until it commits, readers never wait for writers, and two transactions that modify the same row are serialized by an exclusive row lock. The default isolation level is **READ COMMITTED**.

## Autocommit

By default every statement runs in **autocommit** mode: it is committed automatically when it succeeds and rolled back when it fails. To group several statements in one transaction, turn autocommit off in your client and end the transaction yourself with **COMMIT** or **ROLLBACK**.

| Client | How to control autocommit |
|---|---|
| corasql | The session command `;autocommit off` / `;autocommit on`; see [Session commands](https://www.coradb.ai/manual/corasql.html#session-commands) |
| JDBC | `Connection.setAutoCommit(false)` |
| CCI and the drivers built on it | The broker parameter [CCI_DEFAULT_AUTOCOMMIT](https://www.coradb.ai/manual/admin/config_broker.html#cci_default_autocommit) (default `ON`) sets the initial mode; `cci_set_autocommit()` changes it per connection |

The examples on these pages assume autocommit is off.

## Transaction commit

```sql
COMMIT [WORK];
```

**COMMIT** makes all changes of the current transaction permanent (written to the log on disk) and visible to other transactions, and releases all locks the transaction holds. Until then, only the transaction itself sees its changes. The keyword **WORK** is optional.

```sql
-- autocommit off
SELECT id, units_in_stock FROM product WHERE id IN (1618, 1619);   -- 22, 76

UPDATE product SET units_in_stock = units_in_stock + 10 WHERE id IN (1618, 1619);
SELECT id, units_in_stock FROM product WHERE id IN (1618, 1619);   -- 32, 86, seen only by this transaction

COMMIT;    -- now permanent and visible to everyone
```

## Transaction rollback

```sql
ROLLBACK [WORK];
```

**ROLLBACK** cancels every change made since the transaction started and releases its locks. Use it to undo mistakes before they become permanent.

DDL statements are transactional too, so a schema change can be rolled back together with data changes. In the following transaction a column is dropped by mistake:

```sql
CREATE TABLE gift_card (code VARCHAR(16), owner VARCHAR(64), balance NUMERIC(10,2));
COMMIT;

ALTER TABLE gift_card DROP COLUMN owner;
INSERT INTO gift_card (code, owner, balance) VALUES ('GC-1001', 'Alvarado LLC', 50);
-- ERROR: Attribute "owner" was not found.

ROLLBACK;  -- the column is back; the failed INSERT can be run again
```

## Savepoint and partial rollback

A savepoint marks a point inside a transaction. **ROLLBACK TO SAVEPOINT** undoes only the changes made after that point; the transaction stays open and can continue, commit or roll back completely. A savepoint does not commit anything.

```sql
SAVEPOINT mark;

ROLLBACK [WORK] TO [SAVEPOINT] mark;
```

- *mark* is an identifier or a host variable (`:name`).
- A transaction can have several savepoints. If a name is reused, the newest savepoint with that name is used; the older one becomes visible again after the newer one has been rolled back to.
- Rolling back to a savepoint removes the savepoints set after it. **COMMIT** and a full **ROLLBACK** remove all savepoints.
- You can roll back to the same savepoint several times.
- **ROLLBACK** without **TO** rolls back the whole transaction.

```sql
-- autocommit off; product 1618 has 22 units, 1619 has 76
UPDATE product SET units_in_stock = units_in_stock - 2 WHERE id = 1618;   -- 20
SAVEPOINT sp1;

UPDATE product SET units_in_stock = units_in_stock - 5 WHERE id = 1619;   -- 71
SAVEPOINT sp2;

UPDATE product SET units_in_stock = 0 WHERE id IN (1618, 1619);           -- 0, 0 (mistake)

ROLLBACK TO SAVEPOINT sp2;   -- 20, 71: only the last UPDATE is undone
ROLLBACK TO sp1;             -- 20, 76: the second UPDATE is undone as well
COMMIT;                      -- keeps the first UPDATE only
```

Savepoints are useful in long transactions, for example a batch job that can retry one step without repeating everything before it.


## Cursor holdability

*Cursor holdability* means that a result set stays open after the transaction that produced it commits, so the application can keep fetching rows. In CoraDB cursors are holdable by default (**HOLD_CURSORS_OVER_COMMIT**).

In JDBC you can set holdability per connection or per statement:

```java
// connection level
conn.setHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT);

// statement level, overrides the connection setting
PreparedStatement ps = conn.prepareStatement(sql,
        ResultSet.TYPE_SCROLL_SENSITIVE,
        ResultSet.CONCUR_UPDATABLE,
        ResultSet.HOLD_CURSORS_OVER_COMMIT);
```

Use `ResultSet.CLOSE_CURSORS_AT_COMMIT` to close result sets at commit instead. `HOLD_CURSORS_OVER_COMMIT` is not supported on `java.sql.XAConnection`.

CCI applications and the drivers built on CCI hold cursors by default. If holding is turned off for a connection, the `CCI_PREPARE_HOLDABLE` flag of `cci_prepare()` makes one statement holdable. See the prepare function of each driver for its options.

**When held result sets are closed**

- A **ROLLBACK** closes all result sets, including those held over earlier commits. This includes the automatic rollback after a failed statement in autocommit mode.

  ```java
  rs1 = stmt.executeQuery(sql1);
  conn.commit();                 // rs1 stays open
  rs2 = stmt.executeQuery(sql2);
  conn.rollback();               // rs1 and rs2 are closed
  ```

- The application closes the result set (`rs.close()`) or the statement (`stmt.close()`), or disconnects.
- The connection between the application and its CAS (the broker's application server) is closed. With the broker parameter [KEEP_CONNECTION](https://www.coradb.ai/manual/admin/config_broker.html#keep_connection) set to `AUTO`, a CAS is not restarted while it has an open holdable result set; with `ON`, holdability is not affected.

Open result sets use memory on the server, so close them as soon as you are done.

## Transaction termination and recovery

CoraDB guarantees that a transaction is *atomic*: after any failure, either all of its changes are in the database or none are. Recovery is automatic and based on undo/redo logging; applications do not need to repair the database after a crash.

- Every change is written to the log twice: a *before image* (undo) used for **ROLLBACK** and for removing uncommitted changes after a failure, and an *after image* (redo) used to re-apply committed changes that had not yet reached the data volumes.
- The current log is the *active log*. When it is full, it is copied to an *archive log*.
- If a failure happens while **COMMIT** is running and the commit was not completed, the transaction is rolled back.


### Restarting the database

**After a normal shutdown or a system failure,** start the server as usual (`coradb server start <db>`). On restart CoraDB re-applies committed changes that are missing from the data volumes and removes uncommitted ones. No archive logs or backups are needed.

**After a media (disk) failure,** restore the last good backup and the logs written after it with [restoredb](https://www.coradb.ai/manual/admin/admin_backup.html#restoredb), then start the server. Take regular backups with [backupdb](https://www.coradb.ai/manual/admin/admin_backup.html#backupdb) so that as few changes as possible depend on log files.

### Dirty records in the client

A client keeps changed objects (*dirty records*) in its buffers and flushes them to the server when needed, for example when the transaction commits, when many objects are loaded, when the schema of their table changes, when their table is queried, or when a server-side function is called. This is automatic and does not change transaction semantics.
