BEGIN TRANSACTION
BEGIN starts an explicit transaction boundary.
After BEGIN, changes are pending until you COMMIT or ROLLBACK.
Core Concepts
flowchart TD
A[BEGIN ...] --> B[Execute writes]
B --> C{Finish path}
C -->|COMMIT| D[Persist changes]
C -->|ROLLBACK| E[Discard changes]
| BEGIN form | Typical behavior |
|---|---|
BEGIN / BEGIN DEFERRED | Acquire locks lazily when needed |
BEGIN IMMEDIATE | Start reserved write intent earlier |
BEGIN EXCLUSIVE | Stronger locking mode |
- Default BEGIN
- BEGIN IMMEDIATE
BEGIN;
-- write statements
COMMIT;
| Expected output |
|---|
| Transaction starts and ends explicitly around writes. |
BEGIN IMMEDIATE;
-- write statements
COMMIT;
| Expected output |
|---|
| Transaction starts with immediate write intent. |
Code Examples
-- Setup table for BEGIN examples.
CREATE TABLE tx_begin_demo (
id INTEGER PRIMARY KEY,
note TEXT NOT NULL
);
| Expected output |
|---|
| Demo table created. |
-- Explicit transaction using BEGIN.
BEGIN TRANSACTION;
INSERT INTO tx_begin_demo (note)
VALUES ('step one'), ('step two');
COMMIT;
| Expected output |
|---|
| Both inserts committed together. |
-- Verify inserted rows.
SELECT id, note
FROM tx_begin_demo
ORDER BY id;
| id | note |
|---|---|
| 1 | step one |
| 2 | step two |
SQLite-Specific Nuances
SQLite Nuance
BEGIN does not itself change data; it marks transaction start in the current connection.
Lock behavior differs slightly by begin mode (DEFERRED, IMMEDIATE, EXCLUSIVE).
Common Pitfalls / Best Practices
Pitfall
Starting a transaction and forgetting to finalize it, leaving locks and pending work.
Best Practice
Always pair every BEGIN with a clear end path (COMMIT on success, ROLLBACK on failure).
Quick Challenge
Begin a transaction and insert one row into tx_begin_demo with note manual tx.
View Solution
BEGIN;
INSERT INTO tx_begin_demo (note)
VALUES ('manual tx');
COMMIT;
| Expected output |
|---|
| New row inserted and persisted at commit time. |