SQLite Transactions
What is a Transaction?
A transaction is a group of SQL statements that belong together. Either all the statements are done, or none of them.
Think of moving money from one account to another. You must take the money from one account, and add it to the other. If only one of the two statements runs, money is lost or created.
BEGIN and COMMIT
BEGIN starts a transaction, and COMMIT saves all the changes:
Example
BEGIN;
UPDATE Products SET Price = Price + 1
WHERE CategoryID = 1;
UPDATE Products SET Price = Price - 1
WHERE CategoryID = 2;
COMMIT;
Try it Yourself »
ROLLBACK
ROLLBACK cancels all the changes since BEGIN. In this example, all the customers are deleted, but the delete is cancelled, so all 91 customers are still there:
Automatic Transactions
If you do not use BEGIN, SQLite puts each statement in its own transaction. A statement is always done completely, or not at all.
Tip: Many inserts are much faster inside one transaction, because SQLite saves to the disk only once, at COMMIT.
SAVEPOINT
A savepoint is a named point in a transaction. You can roll back to it, without cancelling the whole transaction:
Example
BEGIN;
UPDATE Products SET Price = 10
WHERE ProductID = 1;
SAVEPOINT before_delete;
DELETE FROM Products WHERE ProductID = 2;
ROLLBACK TO before_delete;
COMMIT;
SELECT ProductID, Price FROM Products
WHERE ProductID IN (1, 2);
Try it Yourself »
The price change is saved, but the delete is cancelled.