Sling Academy
Home/SQLite/How to Use BEGIN, COMMIT, and ROLLBACK in SQLite

How to Use BEGIN, COMMIT, and ROLLBACK in SQLite

Last updated: December 07, 2024

SQLite is a light-weight, disk-based database that requires minimal setup. Like many SQL-based systems, it supports transactional operations, providing powerful data management features such as BEGIN, COMMIT, and ROLLBACK. These are crucial in ensuring data integrity, especially in multi-step operations that must either fully complete or not happen at all.

Understanding SQLite Transactions

Transactions allow you to execute a series of operations as a single unit of work. If something goes wrong during one of the operations, you can revert all changes made during the transaction. In SQLite, this is accomplished using the keywords BEGIN, COMMIT, and ROLLBACK.

BEGIN

The BEGIN keyword starts a new transaction. SQLite transactions can be DEFERRED, IMMEDIATE, or EXCLUSIVE, but the default transaction mode is DEFERRED, which is typically what you will start with.

BEGIN TRANSACTION;

Using the above command, you can start a transaction that is read-write-safe. No other operations can modify the data involved in the transaction until it’s committed or rolled back.

COMMIT

The COMMIT keyword ends the current transaction by saving all changes made during it to the database. This command finalizes the transaction, ensuring all data modifications are permanent.

COMMIT;

Once a transaction is committed, the changes are applied and can be seen by other database connections.

ROLLBACK

The counterpart to commit, ROLLBACK restores the database to its state before the BEGIN TRANSACTION was executed. It's particularly useful when an error occurs, ensuring that only complete sets of transactions are saved to the database.

ROLLBACK;

This cancels all changes made during the transaction, ensuring that partially-applied or incorrect data is not saved.

Practical Example with Transactions

Consider a scenario where you are updating user balance records. You must ensure that updates occur consistently.


BEGIN TRANSACTION;

-- Subtract 100 from User A's balance
UPDATE accounts SET balance = balance - 100 WHERE user_id = 1;

-- Add 100 to User B's balance
UPDATE accounts SET balance = balance + 100 WHERE user_id = 2;

COMMIT;

In the above example, the transactions ensure that if the transfer from User A is successful but an error occurs while crediting User B, you can use ROLLBACK to undo the operation. You can implement this as:


BEGIN TRANSACTION;

UPDATE accounts SET balance = balance - 100 WHERE user_id = 1;
UPDATE accounts SET balance = balance + 100 WHERE user_id = 2;

-- if success
COMMIT;

-- if failure
-- ROLLBACK;

Best Practices for SQLite Transactions

  • Always be sure of database consistency before using COMMIT. Double-check conditions that may affect data integrity.
  • Use ROLLBACK in code logic where errors can occur. This ensures data consistency.
  • Test transactions thoroughly under simulated conditions that occur in live environments.

By following these practices, developers can maximize the integrity and reliability of their SQLite operations.

Hence, employing transactions in SQLite, using BEGIN, COMMIT, and ROLLBACK properly can significantly improve your database management strategy, ensuring that complex series of operations always result in consistent data storage and retrieval.

Next Article: Ensuring Data Consistency with SQLite Transactions

Previous Article: Understanding 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