Sling Academy
Home/SQLite/SQLite BEGIN, COMMIT, and ROLLBACK: A Quick Guide

SQLite BEGIN, COMMIT, and ROLLBACK: A Quick Guide

Last updated: December 07, 2024

SQLite is a lightweight, embedded database system that's perfect for mobile applications and small web services. One of the essential aspects of working with any database, including SQLite, is understanding how to manage transactions. In SQLite, transactions allow you to execute a series of operations atomically. This means all operations are completed successfully or none at all, ensuring data integrity. The three primary commands to manage transactions in SQLite are: BEGIN, COMMIT, and ROLLBACK.

Understanding Transactions

A transaction groups multiple SQL statements so that they are treated as a single unit of work. The benefit is that if an error occurs during one of the statements, the entire transaction can be undone with a ROLLBACK. Conversely, if everything works as expected, the transaction changes are saved with COMMIT.

BEGIN

The BEGIN statement initiates a new transaction in SQLite. All SQL commands following the BEGIN statement are part of this transaction until it is closed with a COMMIT or ROLLBACK.

BEGIN TRANSACTION;

This command does not lock the database by default but prepares the database to be locked as needed during the transaction.

COMMIT

When you have completed all your database operations successfully, the COMMIT statement is used to save changes and end the transaction.

COMMIT;

Using COMMIT finalizes the changes made during the transaction and releases any locks the transaction holds on the database.

ROLLBACK

If something goes wrong during the execution of a transaction, or if you decide not to proceed with the changes, you can abort the transaction with a ROLLBACK.

ROLLBACK;

This command undoes all changes made during the transaction and also ends the transaction.

Simple Example

Let's consider a simple case where we want to transfer money from one bank account to another. This scenario requires ensuring that both debit and credit operations succeed or none at all, which naturally fits into a transaction.

BEGIN TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;
UPDATE accounts SET balance = balance + 100 WHERE account_id = 2;
COMMIT;

If at any point in this series of updates an error occurs (such as insufficient funds), the transaction should be rolled back:

BEGIN TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;
-- Here we check if the balance is sufficient; if not, we rollback
IF (SELECT balance FROM accounts WHERE account_id = 1) < 0 THEN ROLLBACK;
UPDATE accounts SET balance = balance + 100 WHERE account_id = 2;
COMMIT;

Nesting Transactions

SQLite does not support true nested transactions, but you can simulate them using savepoints. Savepoints allow you to create temporary points that you can roll back to without affecting other parts of the transaction.

BEGIN TRANSACTION;
SAVEPOINT savepoint1;
-- Perform some operations
ROLLBACK TO savepoint1; -- This undoes operations back to the savepoint
RELEASE savepoint1; -- This commits operations after this point, removing the savepoint
COMMIT;

Summary

Using BEGIN, COMMIT, and ROLLBACK is vital for maintaining data integrity within your SQLite database. These commands help ensure that a series of SQL operations either all happen or none happen, effectively shielding your database from inconsistency. Mastering these transaction controls allows you to build robust applications where data integrity is crucial.

  • BEGIN: Starts a transaction.
  • COMMIT: Completes the transaction by saving all operations.
  • ROLLBACK: Aborts the transaction, discarding all changes.
  • Savepoints: Allow finer-grained transaction control for rollback scopes.

Next Article: Best Practices for Data Consistency in SQLite Transactions

Previous Article: How to Handle Nested Transactions in SQLite

Series: Transactions and Concurrency in SQLite

SQLite

You May Also Like

  • How to use regular expressions (regex) in SQLite
  • SQLite UPSERT tutorial (insert if not exist, update if exist)
  • What is the max size allowed for an SQLite database?
  • SQLite Error: Invalid Value for PRAGMA Configuration
  • SQLite Error: Failed to Load Extension Module
  • SQLite Error: Data Type Mismatch in INSERT Statement
  • SQLite Warning: Query Execution Took Longer Than Expected
  • SQLite Error: Cannot Execute VACUUM on Corrupted Database
  • SQLite Error: Missing Required Index for Query Execution
  • SQLite Error: FTS5 Extension Malfunction Detected
  • SQLite Error: R-Tree Node Size Exceeds Limit
  • SQLite Error: Session Extension: Invalid Changeset Detected
  • SQLite Error: Invalid Use of EXPLAIN Statement
  • SQLite Warning: Database Connection Not Closed Properly
  • SQLite Error: Cannot Attach a Database in Encrypted Mode
  • SQLite Error: Insufficient Privileges for Operation
  • SQLite Error: Cannot Bind Value to Parameter
  • SQLite Error: Maximum String or Blob Size Exceeded
  • SQLite Error: Circular Reference in Foreign Key Constraints