SQLite in Depth
"SQLite is an in-process library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine." — SQLite project, About SQLite (sqlite.org/about.html)
Summary: SQLite is a real, fully transactional SQL database that lives inside your process as a library and stores everything in one file; it gives up client/server networking and concurrent writers, and gets simplicity, speed and a very small failure surface in return. Focus: The file and page format, rollback journal vs WAL and checkpoints, the lock ladder and SQLITE_BUSY, BEGIN IMMEDIATE, PRAGMAs, flexible typing vs STRICT, FTS5, JSON, backups, corruption, and Go and Laravel usage, plus where Litestream, LiteFS, rqlite and libSQL fit. Learning goal: Decide when SQLite is the right production database, configure it correctly (WAL, busy_timeout, synchronous, foreign_keys), write code that never loses a write to SQLITE_BUSY, and back it up without corrupting it.
This page is the complete reference for SQLite as a production database engine: the embedded model, the single-file format built from pages and B-trees, the two atomic-commit mechanisms (rollback journal and write-ahead log), checkpointing, the four lock states, the one-writer rule, the busy handler, BEGIN DEFERRED/IMMEDIATE/EXCLUSIVE, isolation, every PRAGMA a practitioner meets, type affinity and STRICT tables, upsert, RETURNING, window functions, JSON/JSONB, FTS5, in-memory and shared-cache databases, limits, backup (.backup, VACUUM INTO, the backup API), the causes of file corruption, and the testing culture behind it. It then covers running it from Go (modernc.org/sqlite, mattn/go-sqlite3) and Laravel (the sqlite driver and :memory: tests), and the replication layer around it (Litestream, LiteFS, rqlite, libSQL/Turso). It does not re-teach what sibling pages own: the four ACID properties are in ACID & Transactions, anomaly definitions in Isolation Levels, how a WAL gives crash recovery in general in Durability, WAL & Crash Recovery, B-tree theory in B-Tree vs B+Tree, and generic backup strategy in Backup, PITR & Disaster Recovery.
Page map
| If you are looking for | Go to |
|---|---|
| The whole thing in tables you can memorise | Everything in one minute |
| Why an embedded database exists, and what it costs | Why SQLite exists |
| History, public domain, testing, how widely it is deployed | Where it comes from |
| Serverless, in-process, zero-config | The embedded model |
| Pages, B-trees, the 100-byte header, rowid | The file format |
| Rollback journal, hot journal, atomic commit | Rollback journal |
| WAL, wal-index, checkpoint modes, WAL growth | WAL and checkpointing |
| SHARED, RESERVED, PENDING, EXCLUSIVE | Locking states |
SQLITE_BUSY, busy_timeout, BEGIN IMMEDIATE | BUSY and the write lock |
| Is SQLite serializable, what do readers see | Isolation |
Dynamic typing, affinity, STRICT | Types |
journal_mode, synchronous, foreign_keys, cache_size, mmap_size, temp_store | PRAGMAs |
Upsert, RETURNING, window functions, CTEs, generated columns | Modern SQL |
json_extract, ->>, JSONB | JSON |
MATCH, bm25, tokenizers | FTS5 |
:memory:, cache=shared | In-memory and shared cache |
| 281 TB, 2000 columns, 64 tables in a join | Limits |
.backup, VACUUM INTO, sqlite3_rsync | Backup |
| How a SQLite file gets damaged | Corruption |
| 100% branch coverage | Testing culture |
| What PostgreSQL, MySQL, DuckDB do differently | Comparison |
| Litestream, LiteFS, rqlite, libSQL/Turso | Replication and scale-out |
| Go: pools, DSNs, writers | Go |
Laravel: driver, config keys, :memory: tests | Laravel |
| Error codes and retry | Mechanics, Retry |
| Which database for which workload | Choosing |
| Monolith to distributed | In architecture |
| Reproduce it | Lab |
| Wrong beliefs, cheat sheet, terms | Misconceptions, Cheat sheet, Glossary |
Everything in one minute
The model.
| Property | SQLite | Consequence |
|---|---|---|
| Process model | A library inside your process; no server, no port | No network latency, no connection auth, no separate ops |
| Storage | A single file (one ordinary file, plus -wal, -shm or -journal while in use) | Copy, ship, attach and delete it like a file |
| Concurrency | Unlimited readers, exactly one writer at a time | Great for read-heavy and short-write workloads, wrong for many concurrent writers |
| Isolation | Serializable (by serializing writers); WAL readers see a snapshot | No dirty reads, no lost updates; the price is SQLITE_BUSY instead of waiting rows |
| Durability | Atomic commit via rollback journal (default) or WAL | Survives power loss when synchronous and the disk honour fsync |
| Types | Dynamic by default (affinity); STRICT tables since 3.37.0 | Wrong-typed data is accepted silently unless you opt in to STRICT |
| Size | Up to about 281 TB, 1 GB per row/BLOB | The limit you hit first is write concurrency, not size |
| Network | Not a protocol; never share the file over NFS/SMB for writing | Replication is a separate layer (Litestream, LiteFS, rqlite) |
The two journaling modes.
Rollback journal (default, DELETE) | WAL (journal_mode=WAL) | |
|---|---|---|
| Where changes go first | Original pages are copied to -journal; new data is written into the main file | New data is appended to -wal; the main file is untouched |
| Commit point | Journal file deleted | Commit record appended to the WAL |
| Readers and writer | A writer needs exclusive access for the final write; readers block it | Readers never block the writer, the writer never blocks readers |
| Writers | One | One |
| fsyncs per commit | Several (journal, then database, then delete) | One on the WAL (synchronous=FULL), none per commit with NORMAL |
| Extra work | None | Checkpointing (WAL back into the main file) |
| Network filesystem | Works poorly but possible | Not supported: needs shared memory on one host |
| Typical use | Application file formats, single-user tools | Servers and anything with concurrent readers |
The PRAGMAs you set on every connection.
| PRAGMA | Value for a server app | Why |
|---|---|---|
journal_mode | WAL | Concurrency and speed; persists in the file |
busy_timeout | 5000 (ms) | Wait for the lock instead of failing at once |
synchronous | NORMAL with WAL | Safe against app crashes; may lose the last commits on power loss, never corrupts |
foreign_keys | ON | Off by default in the library; per connection |
cache_size | -65536 (64 MiB) or more | Default is only about 2 MiB |
temp_store | MEMORY | Sorts and temp tables stay off disk |
mmap_size | 268435456 or larger, if the files are on a local disk | Fewer copies on reads |
wal_autocheckpoint | default 1000 pages | Move WAL back into the file regularly |
Where SQLite wins and loses.
| Situation | Verdict |
|---|---|
| Mobile, desktop, browser, IoT, embedded, tests | Wins by default |
| One web app on one server, read-heavy, short writes | Wins (with WAL) and removes a whole component |
| Edge/regional apps with local reads | Wins with LiteFS or libSQL replication |
| Many app servers writing the same data | Loses; use PostgreSQL or MySQL |
| Hundreds of concurrent writers, long write transactions | Loses |
| Analytical scans over hundreds of millions of rows | Loses to DuckDB or a warehouse |
| Need roles, row-level security, wire protocol, online schema tools | Loses |
Why SQLite exists
Most database engines are a separate server process: your program opens a socket, sends SQL, and waits. That is the right design when many programs share one data set and need access control. It is the wrong design when the data belongs to exactly one program, because you pay for a network hop, a connection pool, a config file, a daemon to patch and a second thing that can be down. SQLite removes the server: the SQL engine is a C library linked into your program, and a database is a file the library opens. The project's own framing is "SQLite does not compete with client/server databases. SQLite competes with fopen()." (sqlite.org/whentouse.html).
| What you gain by being embedded | What you give up |
|---|---|
| A query is a function call: microseconds, no round trip | Other machines cannot connect to it |
| Zero administration: no users, no ports, no tuning daemon | No roles, no GRANT, no row-level security |
| The database is one file: backup, copy, ship, diff | You must back up carefully (a naive cp of a live file can be corrupt) |
| Tiny failure surface: nothing to be unreachable | One writer at a time, whole-database write lock |
Deterministic tests: :memory: is free and private | Behaviour differs from PostgreSQL/MySQL in typing and DDL |
| Same engine on phone, laptop, server, browser | No built-in replication or failover |
The analogy we reuse on this page: a notebook on your own desk versus a shared filing room. A client/server database is a filing room with a clerk: many people queue at the window, the clerk enforces rules and keeps the books for everyone. SQLite is a notebook on your own desk: nothing is faster to open, and you need no clerk, but only one person writes in it at a time, and if you want colleagues to read it from another building you must photocopy pages and send them (replication is a separate service).
Three common misunderstandings, up front
- “SQLite is a toy for prototypes.” It is the most widely deployed database in the world, has a larger test suite than almost any server database, and many production sites (read-heavy, single node) run on it. What it is not is a multi-writer, networked database.
- “Because it is just a file, I can copy or sync the file while the app runs.” A live database is the main file plus
-wal(or-journal) plus shared state. Copying onlyapp.dbin the middle of a write, or syncing it with Dropbox or over NFS, is one of the classic ways to corrupt it. Use.backup,VACUUM INTOor Litestream. - “It is dynamically typed, so a column type is just a comment.” A column type sets an affinity that coerces values; it does not reject wrong ones. Only
STRICTtables enforce types, andforeign_keysis off unless you turn it on for each connection.
Where it comes from
SQLite's own change log (sqlite.org/changes.html, read for this page) dates the first public release, "Initial Public Release of Alpha code", to 2000-05-29. The author, D. Richard Hipp, and the origin story (a US Navy damage-control application that had to work without a database server) come from Hipp's talks and are secondary information that this page did not verify against a primary page. The primary documents used on this page are the project's own: About SQLite, Appropriate Uses For SQLite, SQLite Is Serverless, File Format, Write-Ahead Logging, File Locking And Concurrency, Atomic Commit, Isolation In SQLite, Datatypes, STRICT Tables, FTS5, JSON Functions, Limits, How To Corrupt, and How SQLite Is Tested. The source code is in the public domain, the file format is documented as stable and enduring, and the project states a long-term support commitment.
| Year (release) | Milestone | Why it matters here |
|---|---|---|
| 2000 | First release | Embedded, serverless, file-based from day one |
| 3.7.0 (2010-07-21) | Write-ahead logging | Readers and the writer stop blocking each other |
| 3.8.3 | Common table expressions | Recursive queries |
| 3.9.0 (2015-10-14) | FTS5 and the JSON1 extension added to the source tree (both compile-time options then) | Modern full-text search with bm25; JSON functions on request |
| 3.24.0 (2018-06-04) | Upsert (ON CONFLICT DO UPDATE) | One-statement insert-or-update |
| 3.25.0 (2018-09-15) | Window functions | Ranking and running totals in SQL |
| 3.35.0 (2021-03-12) | RETURNING | Get generated ids and new values back |
| 3.37.0 (2021-11-27) | STRICT tables | Real type enforcement |
| 3.38.0 (2022-02-22) | JSON functions built in, -> and ->> | JSON without a loadable extension |
| 3.45.0 (2024-01-15) | JSONB binary JSON | Faster JSON processing |
The concept catalogue
Each block follows the same order: plain words, the usual wrong belief, the precise definition, a sequence you can follow step by step, real scenarios, what each engine does, and the fix in SQL, Go and Laravel.
The embedded, serverless model Must-know
In plain words: There is no database server. Your program links the SQLite library and reads and writes the database file directly, so a query is just a function call that touches a file.
Common misunderstanding: "Serverless" means Lambda or cloud functions. In SQLite's vocabulary it means there is no server process at all: the page SQLite Is Serverless says "the process that wants to access the database reads and writes directly from the database files on disk. There is no intermediary server process."
Definition: SQLite is an in-process library. Every connection (sqlite3 handle) lives in the application's address space, has its own page cache and parser, and coordinates with other connections (in this or other processes) only through locks on the database file and, in WAL mode, a shared-memory file. There is no authentication, because whoever can open the file can read all of it; access control is the operating system's file permissions.
1 app process A: sqlite3_open("app.db") -> own page cache, own parser
2 app process B: sqlite3_open("app.db") -> own page cache, own parser
3 A: SELECT ... -> read(2) the pages it needs, take SHARED lock via fcntl
4 B: UPDATE ... -> take RESERVED lock, change pages in its own cache
5 B: COMMIT -> journal + write(2) + fsync(2)
6 A: next read -> notices the file changed (change counter) and drops stale cache
-- no socket, no daemon: the operating system's file locks are the only coordinatorReal scenarios: the file format of an application (a document, a game save, a browser's history), phone and desktop apps, a router's configuration, a CI cache, unit tests with :memory:, a single-server Laravel or Go app, a per-tenant database file, an edge function with a local replica.
| Product | Process model |
|---|---|
| SQLite | In-process library, file locks |
| DuckDB | In-process library (columnar, analytics) |
| PostgreSQL | Postmaster plus a backend process per connection |
| MySQL InnoDB | One server (mysqld) with a thread per connection |
| SQL Server, Oracle | Server processes, listener, shared memory |
| MongoDB | mongod server, wire protocol |
| Redis | Single-threaded server for commands, wire protocol (RESP) |
| CockroachDB | Distributed cluster, PostgreSQL wire protocol |
Fix / how to use it:
-- Open a database (creates the file) and look at what the engine is
sqlite3 app.db
sqlite> SELECT sqlite_version();
sqlite> PRAGMA compile_options; -- ENABLE_FTS5, THREADSAFE=..., etc.
sqlite> .open --readonly app.db -- CLI: reopen read-onlyIn Go the "connection string" is a file path with options (see Go); in Laravel it is DB_CONNECTION=sqlite and DB_DATABASE=/absolute/path/database.sqlite (see Laravel).
The file format: pages and B-trees Must-know
In plain words: The database file is a stack of equal-size blocks called pages. Every table and every index is a B-tree built out of those pages, and a small table at the start of the file lists where each tree begins.
Common misunderstanding: "A SQLite table is a heap of rows plus separate indexes, like PostgreSQL." No: a normal SQLite table is a B-tree keyed by a 64-bit integer rowid, with the row stored in the leaf. An index is a second B-tree keyed by the indexed columns and ending with the rowid, so an index lookup is two B-tree searches unless the index covers the query.
Definition: The first 100 bytes of the file are the database header (magic string SQLite format 3 followed by a NUL byte, page size at offset 16, file format versions at 18 and 19 where 2 means WAL, change counter at 24, size in pages at 28, freelist trunk page at 32, schema cookie at 40, text encoding at 56, user_version at 60, application_id at 68). The page size is a power of two between 512 and 65536 (default 4096 since 3.12.0). Page 1 is the root of the sqlite_schema table (also known as sqlite_master), which has one row per table, index, view and trigger with its rootpage and its CREATE text. B-tree pages are one of four types, flagged by their first byte: 0x02 interior index, 0x05 interior table, 0x0a leaf index, 0x0d leaf table. Table interior pages hold only rowid separators; all rows are in the leaves. A row that does not fit in a page spills its tail into overflow pages. Pages that were freed by DELETE go to the freelist; they are reused but the file does not shrink until VACUUM (or auto_vacuum). Integers inside records use a variable-length encoding (a varint of 1 to 9 bytes), and each record starts with a header of serial types that tells the type and size of each column.
1 SELECT * FROM users WHERE id = 150; -- id is INTEGER PRIMARY KEY = rowid
2 read page 1 -- find rootpage of "users" = 2
3 read page 2 (interior table page) -- 150 is between separators 100 and 200
4 read leaf page -- binary search the cell with rowid 150
5 decode the record header -- serial types give each column's size
6 SELECT * FROM users WHERE email = 'a@b.c'; -- uses index users_email (root p4)
7 walk the index B-tree to key (email, rowid)
8 take the rowid, search the table B-tree again -- second descent
-- 3 or 4 page reads for a warm tree; the first levels are almost always in the page cacheReal scenarios: rowid makes INTEGER PRIMARY KEY lookups the fastest path (no separate index); a table with a TEXT primary key has both the table B-tree and a hidden unique index, which is why WITHOUT ROWID tables (the primary key is the table B-tree) are smaller and faster for composite or text keys; deleting half of a big table leaves the file the same size until VACUUM; a table with large BLOBs is slower to scan because wide rows push data into overflow pages.
| Engine | Table storage | Index points to |
|---|---|---|
| SQLite | B-tree keyed by rowid (or by the PK with WITHOUT ROWID) | The rowid (or the PK) |
| PostgreSQL | Heap file of tuples, no clustering by default | ctid (page, offset) |
| MySQL InnoDB | Clustered B+tree on the primary key | The primary key value |
| SQL Server | Heap, or clustered B+tree if a clustered index exists | RID or the clustering key |
| Oracle | Heap by default (index-organized tables optional) | ROWID |
For the theory of B-trees versus B+trees see B-Tree vs B+Tree; for heap pages see Database Internals.
Fix / how to use it:
PRAGMA page_size; -- 4096 by default; change before the first table (or via VACUUM)
PRAGMA page_count; -- pages in the file
PRAGMA freelist_count; -- free pages waiting for reuse
SELECT name, rootpage FROM sqlite_schema WHERE type IN ('table', 'index');
CREATE TABLE tags (tenant_id INTEGER NOT NULL, name TEXT NOT NULL, n INTEGER NOT NULL,
PRIMARY KEY (tenant_id, name)) WITHOUT ROWID;
VACUUM; -- rebuilds the file and returns free pages to the OSThe rollback journal and atomic commit Must-know
In plain words: Before SQLite changes a page in the database file, it copies the original page into a side file called the journal. If the power fails mid-write, the next opener sees the journal and puts the originals back, so a transaction either happened entirely or not at all.
Common misunderstanding: "Committing means the data is written to the database file." In rollback-journal mode the commit point is the moment the journal file is deleted (or its header zeroed), not the moment pages reach the main file.
Definition: In journal_mode=DELETE (the default) a write transaction (per Atomic Commit In SQLite): acquires a SHARED lock to read, then a RESERVED lock; creates the app.db-journal file; writes the original content of every page it is about to change into the journal; changes pages in its private page cache; waits for the journal to be flushed to disk; escalates to PENDING and then EXCLUSIVE; writes the changed pages into the main file; flushes it; and finally deletes the journal, which is the commit. A journal that exists after a crash is a hot journal: the next connection that opens the database finds it, takes a lock, and rolls back by copying the original pages back. Other journal modes: TRUNCATE (zero the file instead of deleting), PERSIST (overwrite the header with zeros), MEMORY (journal in RAM: a crash mid-transaction can corrupt), OFF (no rollback at all: ROLLBACK stops working), and WAL.
1 BEGIN; UPDATE accounts SET balance = balance - 100 WHERE id = 1;
2 SHARED lock (read pages) -> RESERVED lock (I will write)
3 create app.db-journal; write ORIGINAL page 7 into it
4 modify page 7 only in the private page cache
5 COMMIT;
6 fsync the journal -- originals are now safe on disk
7 PENDING -> EXCLUSIVE (wait for readers to leave)
8 write page 7 into app.db; fsync app.db
9 delete app.db-journal -- COMMIT POINT
10 unlock
-- power failure after 7 and before 9: journal exists = hot journal -> next open restores the original page 7
-- power failure after 9: the transaction is durableReal scenarios: an app that crashes during a large UPDATE leaves a hot journal that the next start repairs silently; deleting app.db-journal by hand "because it looks like junk" after a crash corrupts the database; restoring app.db from backup but keeping an old -journal mismatches them and corrupts it.
| Product | Atomic commit mechanism |
|---|---|
| SQLite (default) | Rollback journal (undo of original pages), delete = commit |
| SQLite (WAL) | Write-ahead log (redo), commit record = commit |
| PostgreSQL | WAL (redo) plus MVCC tuple versions; no undo log |
| MySQL InnoDB | Redo log plus undo log |
| SQL Server | Transaction log (redo and undo) |
| Oracle | Redo log plus undo tablespace |
| MongoDB WiredTiger | Journal (redo) plus checkpoints |
Fix / how to use it:
PRAGMA journal_mode; -- delete (default)
PRAGMA journal_mode = WAL; -- switch; returns 'wal'; persists in the file
PRAGMA synchronous; -- 2 = FULL (default), 1 = NORMAL, 0 = OFF, 3 = EXTRA
PRAGMA journal_size_limit = 67108864; -- shrink leftover journal/WAL to 64 MiB after useWAL, the wal-index and checkpointing Must-know
In plain words: In WAL mode SQLite stops touching the main file on commit. It appends the changed pages to a log, and a background step later copies them into the main file. Readers keep reading the old pages while the writer appends, so they do not wait for each other.
Common misunderstanding: "WAL allows many writers." It does not. The WAL page says it directly: "since there is only one WAL file, there can only be one writer at a time." What WAL changes is that readers and the writer no longer block each other.
Definition: Since 3.7.0 (2010-07-21) a database can use journal_mode=WAL. The writer appends frames (a page image plus a 24-byte frame header) to app.db-wal; a transaction ends with a frame whose header marks it as a commit. When a read transaction starts it records the last valid commit frame as its end mark and keeps that view for its whole duration; to read a page it looks in the WAL up to its end mark, else in the main file. Finding the newest frame for a page quickly is the job of the wal-index, stored in shared memory in the app.db-shm file, which is why all processes must be on the same host and why WAL does not work over a network filesystem. Checkpointing copies committed frames from the WAL back into the main file. It runs automatically when the WAL reaches 1000 pages (wal_autocheckpoint), and manually with PRAGMA wal_checkpoint(MODE) or sqlite3_wal_checkpoint_v2. Modes: PASSIVE (do as much as possible without waiting), FULL (wait for writers and readers so everything is copied), RESTART (like FULL, and also wait until readers use only the main file so the next writer restarts the WAL), TRUNCATE (like RESTART, and truncate the WAL file to zero bytes). A checkpoint cannot pass the end mark of the oldest active reader, so one long read transaction stops the WAL from being reset and it grows. The WAL is persistent: the mode is recorded in the database header (version bytes 18 and 19 become 2), and the last connection to close normally checkpoints and deletes -wal and -shm.
1 W: BEGIN IMMEDIATE; UPDATE ... ; COMMIT; -- frames f5, f6 appended, f6 is a commit frame
2 R1: BEGIN; SELECT ... -- end mark = f4 (last commit at the time)
3 W: BEGIN IMMEDIATE; UPDATE ... ; COMMIT; -- appends f7, f8; R1 does not wait, does not see them
4 R1: SELECT ... -- same snapshot as step 2 (repeatable)
5 CK: PRAGMA wal_checkpoint(PASSIVE); -- copies f1..f4 into app.db, stops at R1's end mark
6 R1: COMMIT; -- read transaction ends
7 CK: PRAGMA wal_checkpoint(TRUNCATE); -- now copies the rest and truncates app.db-wal to 0 bytes
-- a reader that never ends (a forgotten open transaction) = a WAL that never shrinksReal scenarios: a web app with many readers and a few writers goes from "database is locked" errors to none after enabling WAL; a nightly job holding a long SELECT cursor makes app.db-wal grow to gigabytes; a -wal file left on disk after a crash is replayed on the next open (recovery); a read-only mount fails to open a WAL database that has no -shm unless the process can create it (since 3.22.0 read-only opens are possible if the -wal and -shm files already exist or can be created).
| Property | Rollback journal | WAL |
|---|---|---|
| Readers block writer | Yes at the final write (EXCLUSIVE needs readers gone) | No |
| Writer blocks readers | Yes while EXCLUSIVE | No |
| Large transaction (hundreds of MB) | Fine | Historically slower; since 3.11.0 about as efficient |
| Many small commits | Slow (several fsyncs per commit) | Fast (one sequential append) |
| Needs same host (shared memory) | No | Yes |
Multi-file ATTACH atomicity | Atomic across files | Atomic per file only |
Change page_size later | Possible | Not once in WAL mode |
Fix / how to use it:
PRAGMA journal_mode = WAL;
PRAGMA wal_autocheckpoint = 1000; -- pages; 0 disables automatic checkpoints
PRAGMA wal_checkpoint(PASSIVE); -- returns busy | log frames | checkpointed frames
PRAGMA wal_checkpoint(TRUNCATE); -- also resets the WAL file to 0 bytes
PRAGMA journal_size_limit = 134217728; -- cap what is kept after a checkpointIn Go and Laravel you set WAL once per connection through the DSN or config (see Go and Laravel).
Locking states and the one-writer rule Must-know
In plain words: In the default mode each connection climbs a ladder of locks: it reads (SHARED), announces it will write (RESERVED), asks the readers to leave (PENDING), and finally writes alone (EXCLUSIVE). Many can read at once but only one can be on the write side of the ladder.
Common misunderstanding: "SQLite locks rows or tables." The lock granularity is the entire database file. Even a one-row UPDATE is a whole-database write lock; only the duration is short.
Definition: The File Locking And Concurrency page defines five states per connection. UNLOCKED: no access. SHARED: may read; any number of connections can hold it. RESERVED: plans to write; only one at a time, and SHARED locks may still be acquired by others. PENDING: wants to write as soon as current readers finish; no new SHARED locks are granted, which prevents writer starvation. EXCLUSIVE: writing; no other lock of any kind. A statement that cannot get its lock invokes the busy handler (see BUSY) and, if that gives up, fails with SQLITE_BUSY. Locks are implemented with POSIX advisory locks (fcntl) on a few bytes at fixed offsets of the file (the lock-byte page near the 1 GB offset), LockFileEx on Windows.
1 A: BEGIN; SELECT ... -- A: UNLOCKED -> SHARED
2 B: BEGIN; SELECT ... -- B: SHARED (many readers are fine)
3 A: UPDATE t SET ... -- A: SHARED -> RESERVED (B still reads)
4 B: UPDATE t SET ... -- B holds SHARED and wants RESERVED, which A holds
5 A: COMMIT; -- A would need PENDING then EXCLUSIVE: it must wait for B's SHARED to go
6 -- if B also waited for A, both would wait forever (deadlock)
7 SQLite refuses to let that happen: B's upgrade gets SQLITE_BUSY at once, without invoking the busy handler
-- the fix is BEGIN IMMEDIATE (take RESERVED first), not a bigger timeoutReal scenarios: two web workers incrementing a counter with BEGIN then SELECT then UPDATE produce intermittent "database is locked"; a reporting script with an open read transaction stalls the nightly VACUUM; an app that opens a second connection inside a write transaction to read the same table hangs until the timeout.
| Product | Lock granularity for a writer | Readers vs writer |
|---|---|---|
| SQLite | Whole database file | Rollback mode: block at commit; WAL: never block |
| PostgreSQL | Row (and table modes for DDL) | MVCC, readers never block |
| MySQL InnoDB | Row, gap and next-key locks | MVCC consistent reads never block |
| SQL Server | Row, page, table; escalates | Blocking by default; READ_COMMITTED_SNAPSHOT avoids it |
| Oracle | Row | Undo-based read consistency, no blocking |
| MongoDB | Document | WiredTiger MVCC |
| Redis | None needed; single command thread | Not applicable |
| CockroachDB | Row/key intents | MVCC |
The lock modes of server databases are in Locks & Concurrency.
Fix / how to use it:
-- inspect: which locking mode and mode of readers
PRAGMA locking_mode; -- NORMAL (default); EXCLUSIVE keeps the lock after each transaction
PRAGMA locking_mode = EXCLUSIVE; -- single-process apps: no per-transaction lock traffic, nobody else can openSQLITE_BUSY, busy_timeout and BEGIN IMMEDIATE Must-know
In plain words: When the lock you need is taken, SQLite either returns an error at once (database is locked) or waits a while if you told it to. The reliable pattern is to start every write transaction with BEGIN IMMEDIATE and set a busy timeout, so the wait happens at the start of the transaction where it is safe.
Common misunderstanding: "A big busy_timeout fixes all database is locked errors." Not those caused by a read-to-write upgrade: if your transaction already read a snapshot and the database changed since, waiting cannot help, because upgrading would let you write on stale data. SQLite returns SQLITE_BUSY (extended code SQLITE_BUSY_SNAPSHOT in WAL mode) immediately and the whole transaction must be retried.
Definition: SQLITE_BUSY (result code 5, "database is locked") means another connection holds a lock that conflicts with the one you need. SQLITE_LOCKED (6, "database table is locked") is a conflict inside one connection or a shared cache. Extended codes: SQLITE_BUSY_RECOVERY (261, another process is recovering a WAL), SQLITE_BUSY_SNAPSHOT (517, a read transaction cannot be upgraded to write because the database changed), SQLITE_BUSY_TIMEOUT (773, a blocking POSIX lock request in the VFS timed out; only with a special compile option). The busy handler is only consulted while the connection holds no lock yet; an upgrade from a held read lock is refused at once because waiting could deadlock. The busy handler is installed per connection with sqlite3_busy_handler or, usually, PRAGMA busy_timeout = ms / sqlite3_busy_timeout; the default is 0 (fail immediately). BEGIN takes three forms (Transaction page): BEGIN DEFERRED (the default: no lock until the first statement; a read starts a read transaction, a later write tries to upgrade and can fail with SQLITE_BUSY), BEGIN IMMEDIATE (take the write lock now; may fail with SQLITE_BUSY at BEGIN, where the busy handler can wait), and BEGIN EXCLUSIVE (like IMMEDIATE, and in rollback mode also blocks readers; in WAL mode it is the same as IMMEDIATE).
1 -- WAL mode, default BEGIN DEFERRED, two connections, both read-then-write
2 A: BEGIN; SELECT balance FROM acc WHERE id=1; -- read snapshot at commit 10
3 B: BEGIN; SELECT balance FROM acc WHERE id=1; -- read snapshot at commit 10
4 A: UPDATE acc SET balance = balance - 5 WHERE id=1; COMMIT; -- ok, creates commit 11
5 B: UPDATE acc SET balance = balance - 5 WHERE id=1; -- SQLITE_BUSY_SNAPSHOT: B's snapshot is stale
6 B: ROLLBACK; and retry the whole transaction -- waiting would not help
7 -- with BEGIN IMMEDIATE at step 3 B would have waited (busy_timeout) for A at BEGIN, then read fresh dataReal scenarios: a queue worker doing BEGIN, SELECT the next job, UPDATE it to running fails randomly under concurrency until it switches to BEGIN IMMEDIATE; a Go service with a pool of 10 connections all trying to write sees database is locked and is fixed by a one-connection writer pool; a Laravel job queue on SQLite throws SQLSTATE[HY000]: General error: 5 database is locked until busy_timeout and transaction_mode => 'IMMEDIATE' are set.
| Error text | Code | Cause | Retry? |
|---|---|---|---|
database is locked | SQLITE_BUSY (5) | Another connection holds a conflicting lock | Yes, whole transaction |
database is locked (snapshot) | SQLITE_BUSY_SNAPSHOT (517) | Read-to-write upgrade on a stale snapshot | Yes, restart transaction |
database table is locked | SQLITE_LOCKED (6) | Same connection or shared-cache table lock | Fix the code path |
attempt to write a readonly database | SQLITE_READONLY (8) | Read-only open, or directory/-shm not writable | No |
database or disk is full | SQLITE_FULL (13) | No space | No, free space |
database disk image is malformed | SQLITE_CORRUPT (11) | Damaged file | No, restore |
Fix / how to use it: SQL first, then Go and Laravel (full programs are imported in Solving the classic problems).
PRAGMA busy_timeout = 5000; -- per connection, milliseconds
BEGIN IMMEDIATE; -- take the write lock now; waits up to busy_timeout
UPDATE accounts SET balance = balance - 100 WHERE id = 1 AND balance >= 100;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;Isolation in SQLite Important
In plain words: SQLite behaves as if transactions ran one at a time, because writers really do run one at a time. A reader sees one frozen picture of the data for its whole transaction.
Common misunderstanding: "SQLite has no isolation because it is simple." The Isolation In SQLite page states: "Except in the case of shared cache database connections with PRAGMA read_uncommitted turned on, all transactions in SQLite show "serializable" isolation. SQLite implements serializable transactions by actually serializing the writes." There are no dirty reads between separate connections.
Definition: Readers in WAL mode keep an end mark (a snapshot); in rollback mode a writer cannot finish until readers release SHARED, so a reader's data cannot change under it. A transaction that tries to turn a read into a write after the database changed fails instead of overwriting (no lost update). PRAGMA read_uncommitted = 1 is honoured only between connections sharing a cache, and is the only way to see uncommitted data. Within one connection, a statement sees changes made earlier by the same transaction. For the vocabulary (snapshot isolation, serial vs serializable, write skew) see Isolation Levels.
| Anomaly | SQLite (separate connections, no shared cache) |
|---|---|
| Dirty write, dirty read | Not possible |
| Non-repeatable read, phantom | Not possible inside one transaction (snapshot / lock) |
| Lost update | Prevented: stale read-to-write upgrade returns SQLITE_BUSY |
| Write skew | Not possible: writers are serialized |
| Cost | Writers queue; stale upgrades must be retried |
| Product | Default isolation | Strongest |
|---|---|---|
| SQLite | Serializable (single writer) | Serializable |
| PostgreSQL | Read Committed | Serializable (SSI) |
| MySQL InnoDB | Repeatable Read | Serializable (locking reads) |
| SQL Server | Read Committed (locking, or RCSI on Azure SQL) | Serializable, Snapshot |
| Oracle | Read Committed | Serializable (really snapshot isolation) |
| MongoDB | Snapshot reads in transactions with read concern snapshot | Snapshot |
| CockroachDB | Serializable | Serializable |
| Redis | Single-threaded command order | MULTI/EXEC as one step |
Fix / how to use it: keep write transactions short and start with BEGIN IMMEDIATE; do not hold a read transaction open across user interaction; retry on SQLITE_BUSY.
Flexible typing, type affinity and STRICT tables Must-know
In plain words: In most databases a column of type INTEGER refuses text. In SQLite the value carries the type, and the column type is only a preference: it tries to convert what you insert and, if it cannot, stores it as it came. STRICT tables turn that off and behave like other databases.
Common misunderstanding: "VARCHAR(10) limits length and INTEGER limits type." Neither: length arguments are ignored, and INSERT INTO t(age) VALUES ('abc') into an INTEGER column succeeds unless the table is STRICT. The STRICT Tables page describes the default as "SQLite strives to be flexible regarding the datatype of the content that it stores".
Definition: There are five storage classes: NULL, INTEGER (1 to 8 bytes, signed), REAL (8-byte IEEE float), TEXT (UTF-8, UTF-16LE or UTF-16BE per database) and BLOB. A column has an affinity, derived from the declared type name by these rules in order: contains INT gives INTEGER; contains CHAR, CLOB or TEXT gives TEXT; contains BLOB or has no type gives BLOB (formerly NONE); contains REAL, FLOA or DOUB gives REAL; anything else gives NUMERIC. On insert, an INTEGER or NUMERIC column converts text that looks like a number into a number, a TEXT column converts numbers into text; values that cannot be converted losslessly are stored unchanged. INTEGER PRIMARY KEY (exactly that spelling) makes the column an alias of the rowid; AUTOINCREMENT additionally guarantees ids are never reused (via the sqlite_sequence table) at some cost. There are no boolean, date or decimal types: store booleans as 0/1, dates as ISO-8601 TEXT, Unix INTEGER or Julian REAL, money as integer minor units. STRICT tables (3.37.0, 2021-11-27) are opt-in per table: every column must be declared as one of INT, INTEGER, REAL, TEXT, BLOB or ANY, and a value that cannot be losslessly converted to the declared type is rejected with SQLITE_CONSTRAINT_DATATYPE (3091, message "cannot store TEXT value in INTEGER column t.a"). ANY keeps flexible typing for that column. A PRIMARY KEY column of a normal (non-WITHOUT ROWID, non-INTEGER) table may contain NULLs for historical reasons unless declared NOT NULL; STRICT and WITHOUT ROWID tables enforce it.
1 CREATE TABLE loose (a INTEGER);
2 INSERT INTO loose VALUES ('12'), ('abc'), (3.0), (X'ff');
3 SELECT a, typeof(a) FROM loose; -- 12 integer | abc text | 3 integer | blob (no error)
4 CREATE TABLE strict_t (a INTEGER) STRICT;
5 INSERT INTO strict_t VALUES ('12'); -- ok: lossless conversion, stored as integer 12
6 INSERT INTO strict_t VALUES ('abc'); -- Error: cannot store TEXT value in INTEGER column strict_t.a
-- the same column, two behaviours: affinity coerces and tolerates, STRICT enforcesReal scenarios: a Laravel app on SQLite and production MySQL hides a bug where a string lands in an integer column; sorting a column that holds mixed integers and text orders by storage class first (NULL, then numbers, then text, then blobs); comparing '10' < '9' as text but 10 < 9 as numbers depending on affinity; a date column storing both '2025-01-02' and 1735776000 and failing a range query; money stored as REAL accumulating floating-point error.
| Product | Typing |
|---|---|
| SQLite | Dynamic; affinity; STRICT per table (3.37+) |
| PostgreSQL | Static, strict, rich (numeric, timestamptz, uuid, jsonb, arrays) |
| MySQL InnoDB | Static; in non-strict sql_mode silently truncates, in strict mode (default 8.x) errors |
| SQL Server | Static, strict |
| Oracle | Static, strict (NUMBER, VARCHAR2) |
| MongoDB | Dynamic per document (BSON types); optional JSON Schema validation |
| DuckDB | Static, strict, rich |
See Schema Design for money, timestamps and key choice in general.
Fix / how to use it:
CREATE TABLE orders (
id INTEGER PRIMARY KEY, -- rowid alias
user_id INTEGER NOT NULL REFERENCES users(id),
total_cents INTEGER NOT NULL CHECK (total_cents >= 0),
status TEXT NOT NULL CHECK (status IN ('new', 'paid', 'shipped')),
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
) STRICT;In Go, database/sql scans by the Go destination type, so a stray TEXT in an integer column surfaces as a scan error at read time rather than a write error: another argument for STRICT. In Laravel migrations the column helpers generate affinity names and no STRICT, so add it with DB::statement('CREATE TABLE ... STRICT') or an ALTER-free rebuild, and rely on Eloquent casts for types.
PRAGMAs: journal_mode, synchronous, foreign_keys, cache_size, mmap_size, temp_store Must-know
In plain words: PRAGMAs are SQLite's configuration switches, set with SQL, and most of them apply to one connection only. A few (journal mode, page size) are stored in the file.
Common misunderstanding: "I ran PRAGMA foreign_keys = ON once at deploy time, so it is on." It is per connection and off by default in the library; each new pooled connection must set it again. Laravel does that for you (foreign_key_constraints), a raw Go database/sql pool does not unless the DSN carries it.
Definition: PRAGMAs read and write settings (PRAGMA name; reads, PRAGMA name = value; writes). The ones every service meets:
| PRAGMA | Default | What it does | Persisted in file? |
|---|---|---|---|
journal_mode | delete | DELETE, TRUNCATE, PERSIST, MEMORY, WAL, OFF | Only WAL |
synchronous | 2 (FULL) | OFF (0), NORMAL (1), FULL (2), EXTRA (3): how often to fsync | No |
foreign_keys | 0 (off) | Enforce REFERENCES constraints | No |
busy_timeout | 0 | Milliseconds to wait for a lock | No |
cache_size | -2000 | Negative = KiB (about 2 MiB), positive = pages | No |
mmap_size | 0 | Bytes of the file to access through mmap | No |
temp_store | 0 (compile-time, usually file) | DEFAULT 0, FILE 1, MEMORY 2 for temp tables and sort spill | No |
page_size | 4096 | Page size; change before data or with VACUUM (not in WAL) | Yes |
wal_autocheckpoint | 1000 | Pages in WAL before an automatic checkpoint | No |
journal_size_limit | -1 (none) | Truncate WAL/journal to this size when finished | No |
locking_mode | NORMAL | EXCLUSIVE keeps locks after a transaction | No |
auto_vacuum | 0 (none) | NONE, FULL, INCREMENTAL; must be set before tables exist | Yes |
user_version | 0 | 32-bit integer for your own schema version | Yes |
application_id | 0 | Identifies the file format of an application | Yes |
query_only | 0 | Reject all writes on this connection | No |
read_uncommitted | 0 | Shared-cache only: see uncommitted rows | No |
secure_delete | build-dependent | Overwrite deleted content with zeros | No |
recursive_triggers | 0 | Allow triggers to fire themselves | No |
case_sensitive_like | 0 | LIKE case sensitivity for ASCII | No |
defer_foreign_keys | 0 | Postpone FK checks to commit | No |
trusted_schema | 1 | Allow functions in views/triggers/checks to run unsafe code (set 0 for untrusted DBs) | No |
analysis_limit, optimize | n/a | PRAGMA optimize refreshes planner statistics; run before closing | No |
integrity_check, quick_check, foreign_key_check | n/a | Verify the file, quickly, or the FK constraints | No |
table_info, table_xinfo, index_list, index_info, compile_options, database_list | n/a | Introspection | No |
synchronous in plain terms: FULL fsyncs the journal/WAL at every commit; in WAL mode NORMAL fsyncs only at checkpoint, so after a power loss (not an application crash) the most recent commits may be lost but the file is never corrupt; OFF hands everything to the OS and can corrupt on power loss; EXTRA also syncs the directory.
1 PRAGMA synchronous = FULL; COMMIT -> fsync(wal) ~ one disk flush per commit
2 PRAGMA synchronous = NORMAL; COMMIT -> write(wal) only ~ no flush; flush at checkpoint
3 power cut after commit #42, WAL mode:
4 FULL -> commit #42 survives
5 NORMAL -> commits since the last checkpoint may be gone; the database is consistent, just older
6 application crash (kill -9) at any time -> committed data always survives in both (it is in the OS cache)Real scenarios: a service with foreign_keys off in one code path accumulates orphan rows; cache_size left at 2 MiB makes a 5 GB database slow on a 16 GB machine; mmap_size accelerates read-heavy workloads on local SSD but a failing disk or truncated file can crash the process with SIGBUS instead of returning an I/O error; temp_store=MEMORY makes a big ORDER BY fast and a small container run out of memory.
Fix / how to use it:
-- the server preset, executed on every new connection
PRAGMA journal_mode = WAL;
PRAGMA synchronous = NORMAL;
PRAGMA foreign_keys = ON;
PRAGMA busy_timeout = 5000;
PRAGMA cache_size = -65536; -- 64 MiB
PRAGMA temp_store = MEMORY;
PRAGMA mmap_size = 268435456; -- 256 MiB, local disks only
PRAGMA journal_size_limit = 67108864;
-- before closing a long-lived connection
PRAGMA optimize;Modern SQL: upsert, RETURNING, window functions, CTEs, generated columns Important
In plain words: SQLite's SQL is far richer than its reputation: it has upsert, RETURNING, window functions, recursive queries, generated columns, partial and expression indexes, and transactional DDL.
Common misunderstanding: "SQLite has no ALTER TABLE and no real SQL." It supports RENAME, ADD COLUMN, RENAME COLUMN and, since 3.35.0, DROP COLUMN; changing a column's type or constraints needs the documented rebuild (create new table, copy, drop, rename) inside a transaction. DDL is transactional.
Definition: INSERT ... ON CONFLICT (cols) DO UPDATE SET ... (3.24.0) is the upsert, with excluded.col for the proposed row and DO NOTHING for ignore. RETURNING (3.35.0, 2021-03-12) on INSERT, UPDATE and DELETE returns the changed rows (including generated ids). Window functions (3.25.0): row_number(), rank(), dense_rank(), ntile(), lag(), lead(), first_value(), sum() OVER (PARTITION BY ... ORDER BY ... ROWS BETWEEN ...). CTEs with WITH and WITH RECURSIVE. Generated columns (3.31.0) AS (expr) VIRTUAL or STORED. Partial indexes (CREATE INDEX ... WHERE), expression indexes, RIGHT and FULL OUTER JOIN (3.39.0), ATTACH DATABASE to query several files, EXPLAIN QUERY PLAN to see the plan, ANALYZE and PRAGMA optimize for statistics in sqlite_stat1. The planner uses nested-loop joins (it may build a temporary automatic index for a join) and is described in The SQLite Query Planner; see Query Planning for the general plan-reading skills.
1 INSERT INTO counters(name, n) VALUES ('hits', 1)
2 ON CONFLICT(name) DO UPDATE SET n = n + 1 RETURNING n; -- 1
3 -- run again -- 2 (atomic: no select-then-update race)
4 SELECT name, n FROM counters; -- hits | 2Real scenarios: idempotent consumers (INSERT ... ON CONFLICT DO NOTHING RETURNING), per-key counters, "latest row per group" with row_number(), running balance with sum() OVER, tree walks with WITH RECURSIVE, soft-delete uniqueness with a partial unique index, searching on lower(email) with an expression index.
| Feature | SQLite | PostgreSQL | MySQL InnoDB |
|---|---|---|---|
| Upsert | ON CONFLICT DO UPDATE | ON CONFLICT DO UPDATE | ON DUPLICATE KEY UPDATE |
RETURNING | Yes (3.35+) | Yes | No (MariaDB yes) |
| Window functions | Yes (3.25+) | Yes | Yes (8.0+) |
| Transactional DDL | Yes | Yes | No (implicit commit) |
| Partial index | Yes | Yes | No |
DROP COLUMN | Yes (3.35+) | Yes | Yes |
| Stored procedures | No | Yes | Yes |
Fix / how to use it:
-- latest order per user, with a running total
WITH ranked AS (
SELECT user_id, id, total_cents,
row_number() OVER (PARTITION BY user_id ORDER BY id DESC) AS rn,
sum(total_cents) OVER (PARTITION BY user_id ORDER BY id) AS running_cents
FROM orders
)
SELECT * FROM ranked WHERE rn = 1;
-- soft delete + unique email only among live rows
CREATE UNIQUE INDEX users_email_live ON users(lower(email)) WHERE deleted_at IS NULL;
-- generated column
ALTER TABLE orders ADD COLUMN total_eur REAL GENERATED ALWAYS AS (total_cents / 100.0) VIRTUAL;JSON and JSONB Important
In plain words: SQLite can store JSON in an ordinary TEXT column and has built-in functions to read and edit it. Since 3.45 it can also keep a faster binary form called JSONB.
Common misunderstanding: "There is a JSON type." There is no JSON column type; JSON is TEXT (or BLOB for JSONB) plus functions, and nothing validates it unless you add CHECK (json_valid(col)).
Definition: The functions were the optional JSON1 extension (added to the source tree in 3.9.0, enabled with -DSQLITE_ENABLE_JSON1) and are built in since 3.38.0 (2022-02-22): json(), json_valid(), json_extract(), the operators -> (returns JSON) and ->> (returns an SQL value), json_set, json_insert, json_replace, json_remove, json_patch, json_array, json_object, json_type, the aggregates json_group_array and json_group_object, and the table-valued functions json_each and json_tree. JSONB (3.45.0, 2024-01-15) is a binary encoding produced by jsonb() and the jsonb_* functions; it is stored as a BLOB, skips repeated text parsing, and is internal (not a stable interchange format). Index JSON with a generated column or an expression index.
1 CREATE TABLE events (id INTEGER PRIMARY KEY, body TEXT NOT NULL CHECK (json_valid(body)));
2 INSERT INTO events(body) VALUES ('{"user":{"id":7,"plan":"pro"},"tags":["a","b"]}');
3 SELECT body ->> '$.user.plan' FROM events; -- pro
4 SELECT j.value FROM events, json_each(events.body, '$.tags') AS j; -- a | b
5 CREATE INDEX events_plan ON events (body ->> '$.user.plan'); -- expression index
6 EXPLAIN QUERY PLAN SELECT id FROM events WHERE body ->> '$.user.plan' = 'pro'; -- SEARCH ... USING INDEX events_planReal scenarios: storing webhook payloads and querying a few fields, flexible per-tenant settings, event logs with a generated column on the event type, storing Laravel json or array casts.
| Product | JSON support |
|---|---|
| SQLite | Functions on TEXT; JSONB blob (3.45+); expression/generated-column indexes |
| PostgreSQL | json and jsonb types, GIN indexes, @>, SQL/JSON path |
| MySQL InnoDB | JSON type with functional and multi-valued indexes |
| MongoDB | Native BSON documents |
| SQL Server | JSON functions on NVARCHAR (and a native type in recent versions) |
| Oracle | JSON type and SQL/JSON |
Fix / how to use it: keep hot, filterable fields as real columns; use JSON for the long tail; add CHECK (json_valid(...)); index the extracted expression. In Laravel $casts = ['settings' => 'array'] works on SQLite because Laravel serializes to a JSON string; where('settings->plan', 'pro') compiles to json_extract(...) and whereJsonContains to an exists (select 1 from json_each(...) where ...) subquery, per the Laravel 13 SQLiteGrammar. In Go scan into []byte or string and json.Unmarshal.
FTS5 full-text search Important
In plain words: FTS5 is a built-in search engine: you create a special virtual table, insert text, and ask MATCH for words, phrases or prefixes, ranked by relevance.
Common misunderstanding: "Full-text search needs Elasticsearch." For a corpus that fits on one node, FTS5 with bm25 ranking is fast and has no extra service; the cost is no stemming in other languages out of the box, no fuzzy matching and no clustering.
Definition: CREATE VIRTUAL TABLE docs USING fts5(title, body, tokenize = 'porter unicode61', prefix = '2 3'). Tokenizers: unicode61 (default), ascii, porter (stemming wrapper), trigram (substring and LIKE/GLOB acceleration, 3.34.0). Query with docs MATCH 'text'; syntax supports phrases "write ahead", AND/OR/NOT, prefix writ*, NEAR(a b, 5), column filters title:wal, and the initial-token anchor ^. Ranking with bm25(docs, w_title, w_body) (lower is better) or the hidden rank column; highlight() and snippet() format results. Variants: normal (content stored in the index), external content (content='posts' with triggers keeping it in sync), contentless (content='', index only). Maintenance commands via INSERT INTO docs(docs) VALUES('optimize' | 'rebuild' | 'integrity-check'). fts5vocab exposes term statistics. detail=none or column shrinks the index. Compile with ENABLE_FTS5 (most distributions include it; check PRAGMA compile_options). The conceptual comparison with PostgreSQL full-text and Elasticsearch is in Full-Text Search.
1 CREATE VIRTUAL TABLE docs USING fts5(title, body, tokenize='porter unicode61');
2 INSERT INTO docs VALUES ('WAL mode', 'Readers do not block writers in write-ahead logging'),
3 ('Rollback', 'The rollback journal is deleted at commit');
4 SELECT title, bm25(docs) AS score FROM docs WHERE docs MATCH 'writer* OR journal' ORDER BY score;
5 -- Rollback | -1.07e-06
6 -- WAL mode | -9.39e-07 (negative: smaller = better match; tiny corpus, tiny numbers)
7 SELECT snippet(docs, 1, '[', ']', '...', 8) FROM docs WHERE docs MATCH 'journal';
8 -- The rollback [journal] is deleted at commitReal scenarios: in-app search over notes, tickets or documentation; a changelog search in a desktop app; typeahead with a prefix index; a product catalogue search kept in sync with triggers.
| Product | Full-text |
|---|---|
| SQLite | FTS5 virtual tables, bm25, tokenizers, single node |
| PostgreSQL | tsvector/tsquery, GIN, ts_rank (also pg_trgm) |
| MySQL InnoDB | FULLTEXT indexes, MATCH ... AGAINST |
| Elasticsearch | Distributed Lucene index (not a database in this table's sense) |
| MongoDB | Text indexes and Atlas Search |
Fix / how to use it:
-- external-content table kept in sync with triggers
CREATE TABLE posts (id INTEGER PRIMARY KEY, title TEXT NOT NULL, body TEXT NOT NULL) STRICT;
CREATE VIRTUAL TABLE posts_fts USING fts5(title, body, content='posts', content_rowid='id');
CREATE TRIGGER posts_ai AFTER INSERT ON posts BEGIN
INSERT INTO posts_fts(rowid, title, body) VALUES (new.id, new.title, new.body);
END;
CREATE TRIGGER posts_ad AFTER DELETE ON posts BEGIN
INSERT INTO posts_fts(posts_fts, rowid, title, body) VALUES ('delete', old.id, old.title, old.body);
END;
CREATE TRIGGER posts_au AFTER UPDATE ON posts BEGIN
INSERT INTO posts_fts(posts_fts, rowid, title, body) VALUES ('delete', old.id, old.title, old.body);
INSERT INTO posts_fts(rowid, title, body) VALUES (new.id, new.title, new.body);
END;
SELECT p.id, p.title FROM posts_fts f JOIN posts p ON p.id = f.rowid
WHERE posts_fts MATCH 'wal NEAR checkpoint' ORDER BY bm25(posts_fts) LIMIT 20;The schema builder in Laravel has no FTS5 helper; create the virtual table with DB::statement in a migration and query with DB::select, as in the example imported under Laravel (not executed here: PHP is not installed on the authoring machine).
In-memory databases and shared cache Important
In plain words: A database named :memory: lives only in RAM and disappears when the connection closes. Every connection that opens :memory: gets its own, separate empty database.
Common misunderstanding: "Two connections to :memory: see the same data." The In-Memory Databases page: "Every :memory: database is distinct from every other. So, opening two database connections each with the filename ":memory:" will create two independent in-memory databases." With a connection pool, the migration you ran on connection 1 is invisible to connection 2.
Definition: Options: :memory: (private to one connection); an empty filename (private temporary on-disk database that SQLite may keep in cache); file::memory:?cache=shared or file:name?mode=memory&cache=shared (one in-memory database shared by all connections in the same process, which also needs URI filenames enabled and survives only while at least one connection is open); ATTACH ':memory:' AS aux. Shared-cache mode lets several connections in one process share one page cache and uses table-level locks (and SQLITE_LOCKED_SHAREDCACHE, 262, on conflict); the docs state: "Shared-cache mode is an obsolete feature. The use of shared-cache mode is discouraged. Most use cases for shared-cache are better served by WAL mode." Its only unique ability is PRAGMA read_uncommitted.
1 Go: db, _ := sql.Open("sqlite", ":memory:") -- pool may open connection #1
2 db.Exec("CREATE TABLE t(a)") -- runs on connection #1
3 db.Query("SELECT * FROM t") -- pool hands out connection #2 (#1 busy)
4 -- Error: no such table: t (connection #2 has its own empty database)
5 fix A: db.SetMaxOpenConns(1)
6 fix B: sql.Open("sqlite", "file:test?mode=memory&cache=shared")
7 fix C: use a temp file (t.TempDir()) and the real WAL path, as production doesReal scenarios: unit tests, Laravel's default test configuration, throw-away analysis of a CSV, an in-process cache table, ATTACH an in-memory scratch database during a data migration.
| Product | In-memory mode |
|---|---|
| SQLite | :memory:, shared-cache memory DB, temp_store=MEMORY |
| PostgreSQL | None built in (use UNLOGGED, tmpfs, or a test container) |
| MySQL | MEMORY engine tables |
| Redis | The whole dataset is in memory |
| DuckDB | :memory: default |
Fix / how to use it: see Go for the pool settings and Laravel for DB_DATABASE=:memory:.
Limits Good to know
In plain words: SQLite has generous but real limits; almost none matter before write concurrency does.
Common misunderstanding: "SQLite cannot hold more than a few GB." The documented maximum database size is about 281 TB (at the 65536-byte page size); the site says the limit is "untested since the developers do not have access to hardware capable of reaching this limit". Practical limits are the single writer, backup time and the size of your disk.
Definition: from Limits In SQLite.
| Limit | Default | Can change | Notes |
|---|---|---|---|
| Database size | about 281 TB (4294967294 pages × 65536 B); 17.5 TB at the 4096 B default | PRAGMA max_page_count | Rows ≈ 2e13 at most |
| String or BLOB length | 1,000,000,000 bytes (SQLITE_MAX_LENGTH) | Lower at runtime, raise to 2^31-1 at compile time | Max row size is the same |
| Columns per table | 2000 (SQLITE_MAX_COLUMN) | Up to 32767 at compile time | Some code paths are O(N²) in columns |
| SQL statement length | 1,000,000,000 bytes by default | sqlite3_limit | |
| Tables in a join | 64 | No | Bitmap in the planner |
| Attached databases | 10 (SQLITE_MAX_ATTACHED) | Up to 125 | ATTACH |
| Bound parameters | 32766 (since 3.32.0), 999 before | sqlite3_limit | Batch inserts with many ? |
| Page size | 4096 | 512 to 65536, power of two | |
| Trigger recursion depth | Limited (SQLITE_MAX_TRIGGER_DEPTH) | Compile time | Prevents unbounded memory use |
Fix / how to use it: batch inserts by transactions (not by thousands of ?), keep rows narrow, put big blobs in files or a separate database, and remember the 32766 parameter ceiling when building WHERE id IN (?, ?, ...) lists.
Backup and copy: .backup, VACUUM INTO, sqlite3_backup, sqlite3_rsync Must-know
In plain words: Do not copy the live file with cp. Ask SQLite to produce a consistent copy, which it can do while the app keeps running.
Common misunderstanding: "It is one file, so cp app.db backup.db is a backup." If a write is in progress, or the real state is partly in app.db-wal, you get a torn or stale copy. How To Corrupt An SQLite Database File lists "Backup or restore while a transaction is active" as a cause of corruption. A raw file copy is safe only when no connection is open (or the copy is an atomic filesystem snapshot that includes app.db and app.db-wal together).
Definition: Four safe tools. (1) The CLI .backup FILE (and the C online backup API sqlite3_backup_init, sqlite3_backup_step, sqlite3_backup_finish) copies pages incrementally; if another connection or process writes to the source during the copy, the copy is restarted (and may never finish if writes keep coming). (2) VACUUM INTO 'file' (3.27.0) writes a compacted copy that is a consistent snapshot of the original; the target must not exist (or must be an empty file), and if the machine loses power while it runs the output can be incomplete, so verify it. (3) sqlite3_rsync copies a live database to or from a remote system over SSH, transferring only changed pages. (4) Continuous replication of the WAL with Litestream (see Replication). .dump produces SQL text, portable but slow to restore. After a restore run PRAGMA integrity_check. The general strategy (RPO/RTO, PITR, test restores) is in Backup, PITR & Disaster Recovery.
1 sqlite3 app.db ".backup 'backup-2025-01-02.db'" -- online backup (backup API)
2 sqlite3 app.db "VACUUM INTO 'backup-2025-01-02.db'" -- compacted copy, WAL readers not blocked
3 sqlite3 backup-2025-01-02.db "PRAGMA integrity_check" -- ok
4 -- WRONG: cp app.db backup.db (while the app is running)
5 -- WRONG: rsync app.db to another host while writers are active, without sqlite3_rsyncReal scenarios: a nightly cron running VACUUM INTO followed by upload to object storage; a pre-migration safety copy; a read-only reporting copy refreshed by sqlite3_rsync; a restore drill proving integrity_check passes.
| Method | Consistent while live? | Output | Cost |
|---|---|---|---|
cp / rsync of the files | No | Same files | Cheapest, unsafe |
.backup / backup API | Yes | Same pages | Restarts if other connections write meanwhile |
VACUUM INTO | Yes | Compacted copy | Reads whole DB, extra disk |
sqlite3_rsync | Yes | Replica file (over SSH) | Transfers only changed pages |
| Litestream | Yes | LTX files in object storage | Continuous, small RPO |
.dump | Yes | SQL text | Slow restore |
| Filesystem snapshot (LVM, ZFS, EBS) | If atomic for all files | Whole volume | Needs journal/WAL included |
Fix / how to use it: the Go program imported under Solving the classic problems runs VACUUM INTO and verifies the copy with PRAGMA integrity_check.
How a SQLite file gets corrupted Important
In plain words: SQLite is very hard to corrupt on its own. Almost all damage comes from outside: someone else writing to the file, locks that do not work, disks that lie about fsync, or hand-deleting the side files.
Common misunderstanding: "A crash or power failure corrupts SQLite." That is exactly what the journal and WAL prevent, provided the disk honours fsync and synchronous is not OFF. The documented causes are about the environment.
Definition: the headings of the How To Corrupt page, grouped:
| Cause | What happens | Prevention |
|---|---|---|
File overwrite by a rogue thread or process, including using a file descriptor after close() | Random bytes in the file | Do not write to the file yourself; fix fd bugs |
| Backup or restore while a transaction is active | Torn copy | .backup, VACUUM INTO, Litestream |
| Deleting a hot journal, or mispairing a database with a journal | Half-applied transaction | Never delete -journal/-wal; move all files together |
| Filesystems with broken or missing locks (NFS, SMB, some Docker/VM mounts) | Two writers at once | Local disk only; one host |
| Two libraries with different locking protocols, multiple copies of SQLite linked in | One breaks the other's locks | One SQLite per process |
| Unlinking, renaming or hard-linking a database file in use | Journal pairs with the wrong file | Do not move open files |
fork() with an open connection | Shared file descriptors and locks | Open after fork |
Disks that do not honour fsync, synchronous=OFF, non-powersafe flash | Lost ordering after power loss | Keep FULL or NORMAL in WAL on honest storage |
| Memory corruption in the host program | Bad pages written | Fix the program |
| WAL-mode bugs fixed in specific versions (the WAL-reset bug in 3.7.0 through 3.51.2, fixed in 3.51.3 on 2026-03-13) | Rare race | Upgrade |
Fix / how to use it: detect with PRAGMA integrity_check (full) or PRAGMA quick_check, and PRAGMA foreign_key_check; recover with the CLI .recover command (best effort) or restore from backup; never run two replicas of a service against one file on shared network storage.
The testing culture behind SQLite Good to know
In plain words: SQLite is trusted because it is tested more than almost any database: the test code is hundreds of times larger than the library.
Common misunderstanding: "100% coverage means no bugs." The project does not claim that; it claims every branch is exercised and then adds fuzzing, crash, I/O-error and out-of-memory tests to find what coverage cannot.
Definition: from How SQLite Is Tested: "100% branch test coverage in an as-deployed configuration", plus 100% MC/DC (modified condition/decision coverage), four independently developed harnesses (the TCL tests, the proprietary TH3 harness, SQL Logic Test, and the fuzzers dbsqlfuzz and jfuzz with OSS-Fuzz), out-of-memory tests, I/O-error tests, crash and power-loss tests, and as of 3.42.0 (2023-05-16) roughly 155.8 KSLOC of library code against 92053.1 KSLOC of test code (590 times as much). That culture is why it can be used in aviation software, and why a bug in SQLite is a rare event compared with a bug in the application around it.
| Test layer | What it catches |
|---|---|
| TCL tests | Behaviour and regressions |
| TH3 (branch/MC/DC) | Coverage on the as-deployed binary |
| SQL Logic Test | Same answers as other engines |
Fuzzers (dbsqlfuzz, jfuzz, OSS-Fuzz) | Malformed SQL and malformed database files |
| Crash/power-loss simulation | Atomic commit correctness |
For your own application the equivalent is to test against the real engine, in WAL mode, with the real PRAGMAs, not only a mock.
Per-product behaviour: SQLite against PostgreSQL, MySQL, DuckDB and the rest
| Axis | SQLite | PostgreSQL | MySQL InnoDB | DuckDB |
|---|---|---|---|---|
| Architecture | In-process library | Client/server, process per connection | Client/server, thread per connection | In-process library |
| Workload | OLTP-lite, embedded | General OLTP, strong SQL | Web OLTP | OLAP, columnar scans |
| Concurrent writers | One (database lock) | Many (row locks, MVCC) | Many (row locks) | One writer process, multi-threaded queries |
| Readers vs writer | WAL: no blocking | No blocking (MVCC) | No blocking (consistent reads) | Snapshot-based |
| Default isolation | Serializable | Read Committed | Repeatable Read | Snapshot isolation (MVCC, optimistic) |
| Network access | None (file) | Wire protocol | Wire protocol | None (file) |
| Auth and roles | None (file permissions) | Roles, RLS, SCRAM | Users and grants | None |
| Types | Dynamic, STRICT optional | Rich, strict | Strict-ish | Rich, strict |
| Replication | External (Litestream, LiteFS, rqlite) | Streaming and logical | Binlog | None |
| Online schema change | ALTER limited, rebuild | Mostly online | Online DDL/gh-ost | n/a |
| Max size | 281 TB nominal | Effectively disk | Effectively disk | Disk, memory-aware |
| Ops cost | Near zero | Real (vacuum, backups, HA) | Real | Near zero |
| Best use | Embedded, edge, single-node app | System of record | Web apps | Analytics on files and local data |
| Dimension | SQL Server | Oracle | MongoDB | CockroachDB | Redis |
|---|---|---|---|---|---|
| Where SQLite differs | Server, T-SQL, locking by default | Server, PL/SQL, enterprise | Document model, server | Distributed SQL, serializable | In-memory structures, server |
| When to pick it instead | Microsoft stack, enterprise BI | Existing enterprise estates | Flexible documents at scale | Multi-region SQL | Cache, queues, counters |
DuckDB's own positioning page says it adopted "the ideas of simplicity and in-process operation" from SQLite but targets analytical workloads: use SQLite for transactions inside an app and DuckDB when you scan and aggregate millions of rows (OLTP vs OLAP). A common pairing is SQLite as the transactional store and DuckDB reading the same data for reports.
Replication and scale-out: Litestream, LiteFS, rqlite, libSQL/Turso
SQLite has no replication of its own, and the file cannot be shared over a network filesystem for writing. Four projects add the missing layer; they differ in what they replicate, who may write, and what a failure costs. Verify each one's current status in its own docs before adopting it: the Fly.io page says LiteFS is "stable and running in production environments" but "still pre-1.0 so APIs may change", and the libSQL README says new features are now developed in the separate Turso database.
| Tool | Mechanism | Writers | Failover | Typical use |
|---|---|---|---|---|
| Litestream | Takes over checkpointing, streams new WAL pages as LTX files to object storage (S3, GCS, Azure, SFTP, NATS and others); restore rebuilds the file | One (the app) | None automatic; you restore elsewhere | Continuous backup, point-in-time restore, disaster recovery |
| LiteFS (Fly.io) | A FUSE file system that intercepts writes and ships transactions to replicas | One primary chosen by a lease (Consul), others read-only | Lease moves the primary | Read replicas close to users on Fly.io or Docker |
| rqlite | Raft consensus over SQLite, HTTP/JSON API, clustering via Kubernetes, Consul, etcd or DNS | One leader | Automatic leader election | A small, highly available relational store, "think etcd, but with relational modeling available" |
| libSQL / Turso | A fork of SQLite with embedded replicas and a remote server; the Turso database is a Rust rewrite aiming at concurrent writes | libSQL keeps the single-writer model | Hosted service | Per-tenant databases, edge reads |
Litestream, step by step (from How it works): Litestream "works by effectively taking over the checkpointing process. It starts a long-running read transaction to prevent any other process from checkpointing and restarting the WAL file. Instead, it continually reads new WAL pages and manually calls out to SQLite to perform checkpoints as necessary." New pages are packaged into LTX files named by the transaction-id range they cover, then compacted into levels (the docs list merges every 30 seconds, 5 minutes, and so on) and uploaded; a restore downloads a snapshot and replays the LTX files up to the requested point.
1 app (WAL mode) -> COMMIT #101..#107 appended to app.db-wal
2 litestream replicate: read new WAL pages -> LTX file 0000000000000101-0000000000000107.ltx
3 upload LTX to s3://bucket/app/ltx/0/ (small, frequent); background compaction merges levels
4 disk lost at 12:00:03
5 new host: litestream restore -o app.db s3://bucket/app -- snapshot + replay LTX files in order
6 start the app on the restored file
-- replication is asynchronous: commits not yet uploaded at step 4 (seconds worth) are lost, the database is consistentWhat each tool does not do: Litestream is a backup and restore tool, not a failover or read-scaling tool (its separate VFS extension can serve read-only queries from object storage). LiteFS replicas are read-only and write requests must reach the primary (an HTTP proxy can forward them), so read-your-writes needs care (see In architecture). rqlite changes the interface: you talk HTTP and SQL strings, not a library and a file, and it offers tunable read consistency (none, weak, strong, linearizable, auto per its read-consistency docs) at the cost of Raft's write latency. libSQL, per its README, "inherits SQLite's fundamental limitations such as the single-writer model". All of them leave you with one logical writer: they scale reads and durability, not write throughput. The consensus theory behind rqlite is in Distributed SQL, Consensus & 2PC, and replication lag and failover patterns in Replication & Failover.
Go: modernc.org/sqlite, mattn/go-sqlite3 and the pool
Go reaches SQLite through database/sql and one of two drivers.
modernc.org/sqlite | github.com/mattn/go-sqlite3 | |
|---|---|---|
| Implementation | Pure Go (C source transpiled), no cgo | cgo wrapper around the C amalgamation |
| Driver name | "sqlite" | "sqlite3" |
| Build | Cross-compiles with plain go build | Needs CGO_ENABLED=1 and a C compiler |
| DSN options | ?_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL), _txlock=immediate, _time_format | ?_busy_timeout=5000&_journal_mode=WAL&_txlock=immediate&_foreign_keys=1 |
| Notes | A _pragma value is run as SQL text, so build it from trusted input only | Mature, the long-time default |
The pool is the trap. database/sql opens as many physical SQLite connections as it needs, and everything that is per connection (PRAGMAs, temp tables, :memory: databases, the busy timeout) applies to each of them separately. With a file database in WAL mode that is exactly what you want for readers, and exactly what you do not want for writers, because ten connections racing for the one write lock produce SQLITE_BUSY. The recommended layout, in the snippet below, is two *sql.DB handles over the same file: a writer with SetMaxOpenConns(1) and _txlock=immediate, and a reader pool with query_only.
| Question | Answer |
|---|---|
| Single connection or a pool? | One connection for writes; a pool (4 to 16) of read connections |
| Where do PRAGMAs go? | In the DSN, so every new physical connection gets them |
Which BEGIN? | _txlock=immediate for the writer pool, so the lock wait happens at BEGIN |
:memory: in tests? | Use SetMaxOpenConns(1), or file::memory:?cache=shared, or a file under t.TempDir() |
| Context cancellation? | The drivers interrupt the running statement (sqlite3_interrupt); the write transaction rolls back |
| Idle connection lifetime | Keep them (SetConnMaxLifetime(0)): closing the last connection checkpoints the WAL, reopening costs a schema read |
// Package pool shows the recommended Go layout: one writer connection and a
// separate pool of readers, both on the same WAL-mode file.
package pool
import (
"database/sql"
"fmt"
"net/url"
_ "modernc.org/sqlite"
)
// Store keeps two *sql.DB handles over one database file.
type Store struct {
W *sql.DB // exactly one connection: serialises writers inside the process
R *sql.DB // many connections: readers never block in WAL mode
}
func dsn(path string, extra ...string) string {
q := url.Values{}
q.Add("_pragma", "busy_timeout(5000)") // first, so the next PRAGMAs can wait for a lock
q.Add("_pragma", "journal_mode(WAL)")
q.Add("_pragma", "synchronous(NORMAL)")
q.Add("_pragma", "foreign_keys(1)")
q.Add("_pragma", "temp_store(MEMORY)")
for _, e := range extra {
q.Add("_pragma", e)
}
return "file:" + path + "?" + q.Encode()
}
// Open creates both pools. Each new physical connection runs the _pragma list,
// because PRAGMAs such as foreign_keys and busy_timeout are per connection.
func Open(path string) (*Store, error) {
w, err := sql.Open("sqlite", dsn(path)+"&_txlock=immediate")
if err != nil {
return nil, err
}
w.SetMaxOpenConns(1) // one writer at a time, no SQLITE_BUSY between our own goroutines
w.SetMaxIdleConns(1)
r, err := sql.Open("sqlite", dsn(path, "query_only(1)"))
if err != nil {
return nil, err
}
r.SetMaxOpenConns(8)
s := &Store{W: w, R: r}
if _, err := w.Exec(`CREATE TABLE IF NOT EXISTS accounts (
id INTEGER PRIMARY KEY,
owner TEXT NOT NULL,
balance INTEGER NOT NULL CHECK (balance >= 0)
) STRICT`); err != nil {
return nil, fmt.Errorf("migrate: %w", err)
}
return s, nil
}
// Close releases both pools.
func (s *Store) Close() error {
werr := s.W.Close()
if err := s.R.Close(); err != nil {
return err
}
return werr
}
// Withdraw is a read-modify-write that is safe because the transaction starts
// with BEGIN IMMEDIATE (_txlock=immediate) and the update is atomic anyway.
func (s *Store) Withdraw(id, amount int64) error {
res, err := s.W.Exec(`UPDATE accounts SET balance = balance - ? WHERE id = ? AND balance >= ?`, amount, id, amount)
if err != nil {
return err
}
n, err := res.RowsAffected()
if err != nil {
return err
}
if n == 0 {
return fmt.Errorf("insufficient funds or unknown account %d", id)
}
return nil
}The same policy for the cgo driver:
// The same connection policy with github.com/mattn/go-sqlite3 (cgo driver).
// DSN keys use the form _journal_mode, _busy_timeout, _txlock, _foreign_keys.
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/mattn/go-sqlite3"
)
func main() {
dsn := "file:app.db?_journal_mode=WAL&_busy_timeout=5000&_synchronous=NORMAL&_foreign_keys=1&_txlock=immediate"
db, err := sql.Open("sqlite3", dsn) // the driver name is "sqlite3", not "sqlite"
if err != nil {
log.Fatal(err)
}
defer db.Close()
db.SetMaxOpenConns(1) // writer pool
var mode string
if err := db.QueryRow(`PRAGMA journal_mode`).Scan(&mode); err != nil {
log.Fatal(err)
}
fmt.Println("journal_mode:", mode)
}Laravel: the sqlite driver, config keys and tests
Laravel's sqlite connection uses PHP's pdo_sqlite (SQLite 3.26.0 or newer per the Laravel 13 database docs). You point DB_DATABASE at an absolute path to a file; foreign key constraints are enabled by default for SQLite connections (DB_FOREIGN_KEYS=false turns that off). The Laravel 13 application skeleton's config/database.php also ships four SQLite keys, busy_timeout, journal_mode, synchronous and transaction_mode (default DEFERRED), which map directly to the PRAGMAs and the BEGIN flavour on this page.
<?php
// config/database.php (excerpt). Laravel 13's application skeleton ships these
// four SQLite keys; the defaults keep SQLite's own behaviour (null = not set).
return [
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
'url' => env('DB_URL'),
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
// Wait up to 5 s for a lock instead of failing with SQLITE_BUSY.
'busy_timeout' => 5000,
// WAL: readers do not block the writer and vice versa.
'journal_mode' => 'WAL',
// NORMAL is safe against application crashes in WAL mode.
'synchronous' => 'NORMAL',
// BEGIN IMMEDIATE takes the write lock up front, so a
// read-then-write transaction cannot hit SQLITE_BUSY halfway.
'transaction_mode' => 'IMMEDIATE',
],
],
];Things that differ from MySQL or PostgreSQL in a Laravel app:
| Topic | On SQLite |
|---|---|
lockForUpdate() and sharedLock() | SQLiteGrammar::compileLock returns an empty string: no row lock is emitted. The protection is the database write lock, which you obtain with transaction_mode => 'IMMEDIATE' |
DB::transaction($cb, $attempts) | The attempts argument retries when ConcurrencyErrorDetector recognises the message; its list includes database is locked and database table is locked, so SQLite busy errors are retried (immediately, with no sleep in ManagesTransactions; add your own backoff outside if you need one) |
| Database queue, cache and session drivers | They write often; set busy_timeout and WAL, and prefer the Redis or file driver at higher concurrency |
php artisan test --parallel | Each worker process needs its own database file; :memory: is already private per process |
Schema:: builder | Types become affinities; STRICT, WITHOUT ROWID and FTS5 need DB::statement |
| JSON where clauses | Supported on SQLite 3.39.0 or newer per the Laravel 13 queries docs |
RefreshDatabase | Runs each test inside a transaction; with :memory: the connection must be the same PDO, which Laravel keeps |
Testing with :memory:. The Laravel 13 skeleton's phpunit.xml sets DB_CONNECTION to sqlite and DB_DATABASE to :memory:, so each test run gets a private, throw-away database that is fast and needs no setup; the RefreshDatabase trait migrates once and wraps each test in a transaction. The trade-off is that you test against SQLite's typing and DDL rules, not your production engine's. If production is PostgreSQL or MySQL, run the integration suite against the real engine in CI as well and keep SQLite for fast feedback.
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Tests\TestCase;
// phpunit.xml in the Laravel 13 skeleton sets DB_CONNECTION=sqlite and
// DB_DATABASE=:memory:, so every test process gets a private, throw-away database.
class FtsSearchTest extends TestCase
{
use RefreshDatabase;
public function test_fts5_match_returns_ranked_rows(): void
{
// Raw DDL: the schema builder has no FTS5 virtual tables.
DB::statement("CREATE VIRTUAL TABLE docs USING fts5(title, body, tokenize = 'porter unicode61')");
DB::table('docs')->insert([
['title' => 'WAL', 'body' => 'Readers do not block writers'],
['title' => 'Rollback', 'body' => 'The journal is deleted at commit'],
]);
$rows = DB::select('SELECT title FROM docs WHERE docs MATCH ? ORDER BY bm25(docs)', ['writer*']);
$this->assertSame('WAL', $rows[0]->title);
$this->assertTrue(Schema::hasTable('docs'));
}
public function test_strict_table_rejects_wrong_type(): void
{
DB::statement('CREATE TABLE strict_t (a INTEGER) STRICT');
$this->expectException(\Illuminate\Database\QueryException::class);
DB::insert('INSERT INTO strict_t (a) VALUES (?)', ['abc']);
}
}Mechanics
Files on disk, sidecar files and URI parameters
| File | When it exists | Meaning | Safe to delete? |
|---|---|---|---|
app.db | Always | Main database | No |
app.db-journal | Rollback mode during a write, or after a crash | Original pages for rollback; hot journal = pending recovery | Never while a hot journal exists |
app.db-wal | WAL mode while open, or after a crash | Committed frames not yet checkpointed | Never: it holds committed data |
app.db-shm | WAL mode while open | wal-index in shared memory (rebuilt from the WAL) | Only when no process has the database open |
Temporary files (named etilqs_...) | Large sorts, VACUUM, temp_store=FILE | Temporary spill | Handled by SQLite |
URI filenames (file:app.db?mode=ro&immutable=1, enabled by SQLITE_OPEN_URI or the file: prefix in the drivers): mode=ro / rw / rwc / memory, cache=shared / private, immutable=1 (file will never change: no locking, for read-only media), nolock=1 (skip locking: only if nothing else writes), vfs=name (choose a VFS), psow=1. Threading mode is a compile/start-up choice: single-thread, multi-thread (a connection must not be used by two threads at once; THREADSAFE=2), serialized (THREADSAFE=1, a mutex per connection). The Go and PHP drivers already cope with this.
The 100-byte header and what each field means in practice
| Offset | Size | Field | Practical use |
|---|---|---|---|
| 0 | 16 | SQLite format 3\0 | file app.db detects it; file is not a database (SQLITE_NOTADB, 26) otherwise |
| 16 | 2 | Page size | Fixed at creation (or VACUUM) |
| 18, 19 | 1, 1 | Write and read format version (1 legacy, 2 WAL) | 2 means WAL mode is persistent |
| 24 | 4 | File change counter | Other connections invalidate caches when it changes |
| 28 | 4 | Size in pages | Truncated files are detected |
| 32, 36 | 4, 4 | Freelist trunk page, freelist count | Free space reusable inside the file |
| 40 | 4 | Schema cookie | Bumped on DDL; prepared statements re-prepare |
| 56 | 4 | Text encoding (1 UTF-8, 2 UTF-16le, 3 UTF-16be) | Chosen at creation |
| 60 | 4 | user_version | Your own migration number (PRAGMA user_version) |
| 68 | 4 | application_id | Identify your file format |
Result codes you meet
| Code | Name | Meaning | Action |
|---|---|---|---|
| 5 | SQLITE_BUSY | Lock held by another connection | Retry transaction with backoff |
| 261 | SQLITE_BUSY_RECOVERY | Another process is recovering the WAL | Retry |
| 517 | SQLITE_BUSY_SNAPSHOT | Stale snapshot cannot upgrade to write | Restart transaction |
| 773 | SQLITE_BUSY_TIMEOUT | A blocking POSIX lock request in the VFS timed out (needs SQLITE_ENABLE_SETLK_TIMEOUT; not the ordinary busy_timeout expiry, which returns plain 5) | Retry or fail |
| 6 | SQLITE_LOCKED | Conflict inside one connection or shared cache | Fix code (finalize statements) |
| 262 | SQLITE_LOCKED_SHAREDCACHE | Shared-cache table lock | Drop shared cache, use WAL |
| 8 | SQLITE_READONLY | Cannot write | Check permissions, -shm, directory |
| 10 | SQLITE_IOERR | Disk I/O failure | Treat as fatal, check storage |
| 11 | SQLITE_CORRUPT | Malformed database | Restore from backup |
| 13 | SQLITE_FULL | Disk full or max page count | Free space |
| 14 | SQLITE_CANTOPEN | Cannot open file | Path, permissions, directory |
| 19 | SQLITE_CONSTRAINT | Constraint failed | Subcodes below |
| 2067 / 1555 | ..._UNIQUE / ..._PRIMARYKEY | Duplicate key | Upsert or report conflict |
| 787 / 1299 / 275 | ..._FOREIGNKEY / ..._NOTNULL / ..._CHECK | Constraint violation | Fix data |
| 3091 | SQLITE_CONSTRAINT_DATATYPE | STRICT type mismatch | Fix the type |
Solving the classic problems
Problem 1: "database is locked" under concurrent writers
| Solution | How | Advantage | Cost or limit |
|---|---|---|---|
WAL + busy_timeout | journal_mode=WAL, busy_timeout=5000 | Readers stop colliding with the writer; short waits succeed | Writers still queue |
BEGIN IMMEDIATE | Take the write lock at BEGIN | No stale-snapshot upgrade failures | Read-only work should use plain BEGIN |
| One writer connection | SetMaxOpenConns(1) or a single writer queue | Contention happens in memory, not on file locks | One in-process write at a time |
| Short transactions | No network calls or user waits inside a write transaction | Lock held for microseconds | Needs discipline |
| Batching | One transaction for many rows | One fsync, one lock | Larger rollback on failure |
| Retry with backoff | Re-run on SQLITE_BUSY | Absorbs bursts | Must be idempotent |
The Go program below shows the failure and the cure: with busy_timeout(0) the second writer fails at once with database is locked (5) (SQLITE_BUSY); with a 2 s timeout it waits about 300 ms for the first to commit and succeeds.
// Two connections write at the same time. With the default DEFERRED
// transaction and no busy timeout the loser gets SQLITE_BUSY at once.
package main
import (
"database/sql"
"fmt"
"log"
"os"
"path/filepath"
"strings"
"time"
_ "modernc.org/sqlite"
)
func open(dsn string) *sql.DB {
db, err := sql.Open("sqlite", dsn)
if err != nil {
log.Fatal(err)
}
return db
}
func main() {
dir, err := os.MkdirTemp("", "sqlite-busy")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
path := filepath.Join(dir, "app.db")
// busy_timeout=0 means: fail immediately instead of waiting for the lock.
a := open("file:" + path + "?_pragma=journal_mode(WAL)&_pragma=busy_timeout(0)")
b := open("file:" + path + "?_pragma=journal_mode(WAL)&_pragma=busy_timeout(0)")
defer a.Close()
defer b.Close()
if _, err := a.Exec(`CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT)`); err != nil {
log.Fatal(err)
}
// Writer A takes the write lock and keeps it for 300 ms.
txA, err := a.Begin()
if err != nil {
log.Fatal(err)
}
if _, err := txA.Exec(`INSERT INTO t (v) VALUES ('from A')`); err != nil {
log.Fatal(err)
}
// Writer B tries while A holds the lock.
_, err = b.Exec(`INSERT INTO t (v) VALUES ('from B')`)
fmt.Println("B without timeout:", err, "retryable:", isBusy(err)) // database is locked (5) (SQLITE_BUSY)
time.AfterFunc(300*time.Millisecond, func() { _ = txA.Commit() })
// Now B waits up to 2 s for the lock before giving up.
if _, err := b.Exec(`PRAGMA busy_timeout = 2000`); err != nil {
log.Fatal(err)
}
start := time.Now()
_, err = b.Exec(`INSERT INTO t (v) VALUES ('from B')`)
fmt.Printf("B with 2s timeout: err=%v waited=%s\n", err, time.Since(start).Round(50*time.Millisecond))
var n int
if err := b.QueryRow(`SELECT count(*) FROM t`).Scan(&n); err != nil {
log.Fatal(err)
}
fmt.Println("rows:", n)
}
// isBusy reports whether err is SQLITE_BUSY or SQLITE_LOCKED: the caller may
// retry the whole transaction. modernc.org/sqlite puts the code name in the text.
func isBusy(err error) bool {
return err != nil && (strings.Contains(err.Error(), "SQLITE_BUSY") || strings.Contains(err.Error(), "SQLITE_LOCKED"))
}Laravel equivalent: the transaction_mode => 'IMMEDIATE' and busy_timeout keys shown above, plus the service below, where the $attempts argument of DB::transaction re-runs the closure when Laravel's concurrency-error detector sees database is locked.
<?php
namespace App\Services;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
class Transfer
{
/**
* Move money between two accounts on a SQLite connection configured with
* 'transaction_mode' => 'IMMEDIATE'. The conditional UPDATE is atomic;
* IMMEDIATE makes DB::transaction() acquire the write lock at BEGIN.
*
* The second argument of DB::transaction() is the number of attempts.
* Laravel's ConcurrencyErrorDetector treats "database is locked" as a
* concurrency error, so the closure is run again (immediately, no sleep).
*/
public function run(int $from, int $to, int $amount): void
{
DB::transaction(function () use ($from, $to, $amount) {
$moved = DB::update(
'UPDATE accounts SET balance = balance - ? WHERE id = ? AND balance >= ?',
[$amount, $from, $amount]
);
if ($moved === 0) {
throw new \DomainException('Insufficient funds');
}
DB::update('UPDATE accounts SET balance = balance + ? WHERE id = ?', [$amount, $to]);
}, 3);
}
/** Use this when you want a pause between attempts (backoff with jitter). */
public function runWithBackoff(int $from, int $to, int $amount, int $attempts = 3): void
{
for ($i = 1; ; $i++) {
try {
$this->run($from, $to, $amount);
return;
} catch (QueryException $e) {
$busy = str_contains($e->getMessage(), 'database is locked');
if (! $busy || $i >= $attempts) {
throw $e;
}
usleep(random_int(20_000, 80_000) * $i);
}
}
}
}Problem 2: slow commits
Each commit costs fsyncs. WAL plus synchronous=NORMAL removes most of them, and wrapping many inserts in one transaction removes the rest.
// Compares rollback-journal (DELETE) and WAL for many small commits.
package main
import (
"database/sql"
"fmt"
"log"
"os"
"path/filepath"
"time"
_ "modernc.org/sqlite"
)
func run(mode string, n int) time.Duration {
dir, err := os.MkdirTemp("", "sqlite-bench")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
dsn := fmt.Sprintf("file:%s?_pragma=journal_mode(%s)&_pragma=synchronous(FULL)", filepath.Join(dir, "b.db"), mode)
db, err := sql.Open("sqlite", dsn)
if err != nil {
log.Fatal(err)
}
defer db.Close()
db.SetMaxOpenConns(1)
if _, err := db.Exec(`CREATE TABLE x (id INTEGER PRIMARY KEY, v TEXT)`); err != nil {
log.Fatal(err)
}
start := time.Now()
for i := 0; i < n; i++ { // one implicit transaction (one fsync round) per insert
if _, err := db.Exec(`INSERT INTO x (v) VALUES (?)`, fmt.Sprintf("row %d", i)); err != nil {
log.Fatal(err)
}
}
return time.Since(start)
}
func main() {
const n = 2000
for _, m := range []string{"DELETE", "WAL"} {
d := run(m, n)
fmt.Printf("%-6s %d commits in %s (%.0f commits/s)\n", m, n, d.Round(time.Millisecond), float64(n)/d.Seconds())
}
}Problem 3: backup of a live database
// Online backup of a live database with VACUUM INTO, plus an integrity check.
package main
import (
"database/sql"
"fmt"
"log"
"os"
"path/filepath"
_ "modernc.org/sqlite"
)
func main() {
dir, err := os.MkdirTemp("", "sqlite-backup")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
src, err := sql.Open("sqlite", "file:"+filepath.Join(dir, "live.db")+"?_pragma=journal_mode(WAL)")
if err != nil {
log.Fatal(err)
}
defer src.Close()
if _, err := src.Exec(`CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT); INSERT INTO t (v) VALUES ('a'), ('b')`); err != nil {
log.Fatal(err)
}
// VACUUM INTO writes a compacted, consistent copy while readers and the
// writer keep working. The target file must not exist yet.
dst := filepath.Join(dir, "backup.db")
if _, err := src.Exec(`VACUUM INTO ?`, dst); err != nil {
log.Fatal(err)
}
bk, err := sql.Open("sqlite", "file:"+dst+"?mode=ro")
if err != nil {
log.Fatal(err)
}
defer bk.Close()
var check string
var n int
if err := bk.QueryRow(`PRAGMA integrity_check`).Scan(&check); err != nil {
log.Fatal(err)
}
if err := bk.QueryRow(`SELECT count(*) FROM t`).Scan(&n); err != nil {
log.Fatal(err)
}
fmt.Println("integrity_check:", check, "rows:", n) // ok, 2
}Problem 4: types that are wrong in production
Create tables as STRICT, add CHECK constraints for enumerations and CHECK (json_valid(col)), turn foreign_keys on in every connection, and run PRAGMA foreign_key_check and PRAGMA integrity_check in CI against a copy of production.
Retry and failure handling
| Error | Meaning | Retry? | Rule |
|---|---|---|---|
SQLITE_BUSY at BEGIN IMMEDIATE | Lock held | Yes | Backoff with jitter; the busy handler already waited busy_timeout |
SQLITE_BUSY mid-transaction (deferred upgrade) | Stale snapshot or deadlock avoidance | Yes, the whole transaction | Switch to BEGIN IMMEDIATE so it stops happening |
SQLITE_BUSY_RECOVERY | Another process replaying WAL | Yes | Short wait |
SQLITE_LOCKED | Same-connection conflict | No | Fix code |
SQLITE_FULL, SQLITE_IOERR, SQLITE_CORRUPT | Environment | No | Alert, restore |
SQLITE_CONSTRAINT_* | Data rule | No | Report to caller |
Rules: retry the whole transaction, never a single statement inside it; make the transaction idempotent (use INSERT ... ON CONFLICT, idempotency keys, conditional UPDATE); cap attempts; use exponential backoff with jitter; put the wait before the work by taking the lock at BEGIN IMMEDIATE. The Go classifier is isBusy in the busy-demo snippet; in Laravel pass the attempts argument to DB::transaction (see Transfer::run above), and use runWithBackoff only when you want backoff between attempts. The general retry design is in Deadlocks and Optimistic vs Pessimistic Locking.
Choosing: when SQLite is the right production database
| Workload | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Mobile and desktop apps, browsers, IoT | SQLite | user_version migrations | No server possible; it is the default everywhere |
| Application file format | SQLite | application_id | One file, atomic saves, queryable |
| Unit and integration tests | SQLite :memory: (or temp file) | Also run CI on the real engine | Fast and private |
| Single-server web app, read-heavy, writes under a few hundred per second | SQLite in WAL mode | Litestream backup | One less component, microsecond reads |
| Per-tenant databases | SQLite, one file per tenant | ATTACH for admin queries, Litestream per file | Isolation, easy export and delete |
| Edge or multi-region read-mostly | SQLite plus LiteFS or libSQL replicas | Write forwarding to the primary | Local reads |
| Small HA store with automatic failover | rqlite | Odd node count (3 or 5) | Raft failover |
| Many app servers writing one dataset | PostgreSQL or MySQL | Connection pooler | Network, row locks, roles |
| High write concurrency or long write transactions | PostgreSQL or MySQL | Partitioning | One-writer rule is the limit |
| Heavy analytics over very large data | DuckDB or a warehouse | Export from SQLite | Columnar scans |
| Need roles, RLS, audit, online schema change | PostgreSQL | pgAudit, RLS | Not in SQLite |
| Financial ledger with strict multi-service guarantees | PostgreSQL or CockroachDB | Outbox, idempotency | Replication and HA are first-class |
When it is NOT the right choice: when more than one machine must write the same data; when you need a network protocol and permissions inside the database; when write transactions are long and numerous; when the file would live on NFS, SMB or a shared volume mounted by several hosts; when you need online, zero-downtime schema changes at scale. See Storage & Data Scaling for the general ladder.
In architecture: from a single process to a distributed system
Monolith (one process, one database)
A Laravel or Go monolith on one VPS or container with a persistent volume: database.sqlite on local SSD, WAL on, busy_timeout, one process or a few workers on the same host, Litestream sending the WAL to S3. Sessions, cache and queue can use the same file at low volume. Deploys are a file-level concern: run migrations at start, keep the volume across releases, never mount the same volume in two replicas. This is the simplest correct use and is how many small production sites run.
Modular monolith / multiple databases
Split by file, not by server: one SQLite file per module or per tenant, opened by the same process, with ATTACH DATABASE for the occasional cross-database report. A transaction across attached databases is atomic per file but, in WAL mode, not atomic across them as a set (the WAL page states this), so design module boundaries so no business rule needs a cross-file atomic write; use an outbox row inside each module's own file instead. Per-tenant files make export, deletion and backup per customer trivial (Multi-Tenancy).
Microservices
Each service owns its own SQLite file; nothing else opens it. Cross-service consistency is not SQLite's job: use sagas and the outbox pattern (write the event in the same local transaction, relay it to the broker), and idempotent consumers keyed by message id (INSERT ... ON CONFLICT DO NOTHING). Example: an orders service appends order_created to its local outbox table in the same BEGIN IMMEDIATE transaction as the order row; a relay goroutine polls rows with RETURNING, publishes to the broker, and deletes them. The broker side is covered in the messaging section. With a container orchestrator, one replica per SQLite file (a StatefulSet with one pod and a local volume, not a Deployment with replicas: 3 on a shared volume).
Distributed data (replicas, caches, multi-region)
Reads can be local everywhere (LiteFS, libSQL embedded replicas, Litestream-restored read-only copies); writes go to one primary. That introduces replica lag and the usual read-your-writes problem: a user writes through the primary and the next request hits a replica that has not applied the transaction yet. Cures are routing the user's next reads to the primary for a short window, passing a transaction id or position token, or writing then reading from the primary. rqlite trades latency for consensus: each write is replicated by Raft to a majority before it is acknowledged, and read consistency (none to linearizable) decides whether a read may be stale. Caches in front of SQLite are rarely needed for latency (it is already in-process) but still need invalidation if shared across processes. A cross-region write-heavy design should use a distributed SQL database (Distributed SQL & Consensus).
Scaling path
| Load | Design |
|---|---|
| 1x: one app, hundreds of requests per second | One SQLite file, WAL, one writer connection, reader pool, Litestream |
| 10x: more CPUs and traffic, still one machine | Tune cache_size, mmap_size, indexes; batch writes; move queue/session/cache to Redis; scale vertically |
| 100x: several app servers or regions | LiteFS or libSQL read replicas with write forwarding, or move the system of record to PostgreSQL and keep SQLite for per-device or per-tenant data |
| Beyond: global write throughput | PostgreSQL/MySQL with replicas and sharding, or CockroachDB; SQLite stays at the edges |
Lab
Needs the sqlite3 CLI (3.37.0 or newer for STRICT, 3.45.0 or newer for JSONB; check sqlite3 --version) and, for the Go steps, Go 1.24 or newer with the snippets above. Use two terminals for experiments 1 and 2.
-- setup (terminal 1)
-- sqlite3 lab.db
PRAGMA journal_mode = WAL; -- wal
CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT);
INSERT INTO t (v) VALUES ('seed');Experiment 1: two writers and SQLITE_BUSY.
1 T1: sqlite3 lab.db T2: sqlite3 lab.db
2 T1: BEGIN IMMEDIATE; INSERT INTO t(v) VALUES('A'); -- T1 now holds the write lock
3 T2: BEGIN IMMEDIATE; -- error: database is locked (SQLITE_BUSY)
4 T2: PRAGMA busy_timeout = 10000; BEGIN IMMEDIATE; -- blocks (waiting)
5 T1: COMMIT; -- T2's BEGIN now returns
6 T2: INSERT INTO t(v) VALUES('B'); COMMIT; -- ok
7 T2: SELECT count(*) FROM t; -- 3 (seed, A, B)
-- reads in a third terminal never block during steps 2-5 (WAL); try it
-- the CLI words the error "Runtime error: ..." interactively or "Error near line N: ..." from a script, by versionExperiment 2: the stale-snapshot upgrade (BUSY_SNAPSHOT).
1 T1: BEGIN; SELECT count(*) FROM t; -- deferred read, snapshot taken
2 T2: INSERT INTO t(v) VALUES('C'); -- autocommit write succeeds, T1 not blocked
3 T1: INSERT INTO t(v) VALUES('D'); -- error: database is locked, at once, no waiting (stale snapshot)
4 T1: ROLLBACK; BEGIN IMMEDIATE; INSERT ...; COMMIT; -- works: the write lock first, then fresh data
-- the C API reports this as SQLITE_BUSY_SNAPSHOT (517); the CLI prints only the messageExperiment 3: WAL against rollback journal timing. Run go run ./bench from docs/snippets/database/sqlite/go. On the author's laptop (macOS, local SSD) it printed:
DELETE 2000 commits in 975ms (2051 commits/s)
WAL 2000 commits in 166ms (12084 commits/s)
-- three consecutive runs on the author's laptop: DELETE 391 ms to 1.29 s, WAL 166 to 657 msYour numbers will differ (macOS fsync does not force a full disk flush by default, so on Linux with a real flush the gap is usually larger). Repeat with PRAGMA synchronous=NORMAL in WAL mode and with all inserts inside one BEGIN ... COMMIT to see the cost of per-commit flushes disappear.
Experiment 4: STRICT table.
CREATE TABLE loose (a INTEGER);
INSERT INTO loose VALUES ('abc'), ('12');
SELECT a, typeof(a) FROM loose; -- abc | text ; 12 | integer
CREATE TABLE strict_t (a INTEGER) STRICT;
INSERT INTO strict_t VALUES ('12'); -- ok, stored as integer
INSERT INTO strict_t VALUES ('abc'); -- error: cannot store TEXT value in INTEGER column strict_t.aExperiment 5: an FTS5 query.
CREATE VIRTUAL TABLE docs USING fts5(title, body, tokenize = 'porter unicode61');
INSERT INTO docs VALUES ('WAL mode', 'Readers do not block writers in write-ahead logging'),
('Rollback', 'The rollback journal is deleted at commit');
SELECT title, bm25(docs) AS score, snippet(docs, 1, '[', ']', '...', 8)
FROM docs WHERE docs MATCH 'writer* OR journal' ORDER BY score;
-- Rollback | -1.07e-06 | The rollback [journal] is deleted at commit
-- WAL mode | -9.39e-07 | Readers do not block [writers] in write-ahead...Experiment 6: checkpoint and the growing WAL. In terminal 1 run BEGIN; SELECT * FROM t; and leave it open. In terminal 2 insert 100000 rows then PRAGMA wal_checkpoint(TRUNCATE); and note the returned row 1|1|0 (busy flag 1, one frame in the log, none checkpointed) and the non-zero -wal size (ls -l lab.db-wal showed 4152 bytes in the author's run). COMMIT in terminal 1 and repeat: it returns 0|0|0 and the WAL file is 0 bytes.
Common misconceptions
| Belief | Reality |
|---|---|
| SQLite is only for prototypes and tests | Most widely deployed database; many single-node production systems run on it |
| It is not ACID | Fully ACID: atomic commit via journal or WAL, serializable isolation |
| WAL means multiple writers | One writer; WAL stops readers and the writer blocking each other |
A bigger busy_timeout fixes every "database is locked" | Not stale-snapshot upgrades; use BEGIN IMMEDIATE and retry |
| Column types are enforced | Only in STRICT tables; otherwise they are affinities |
PRAGMA foreign_keys persists in the file | It is per connection and off by default |
cp app.db backup.db is a backup | Not for a live database; use .backup, VACUUM INTO or Litestream |
Two connections to :memory: share data | Each :memory: is separate; use shared cache or one connection |
| Putting the file on NFS or a shared volume scales it | Locks and shared memory break; it can corrupt |
synchronous=OFF is safe if the app is stable | An OS crash or power cut can corrupt; use NORMAL in WAL |
| A deleted-row table shrinks the file | Pages go to the freelist; run VACUUM or use auto_vacuum |
| Litestream gives high availability | It gives continuous backup and restore, not automatic failover |
Row locks exist, so lockForUpdate protects a row in Laravel | SQLite has none; the whole database write lock is what protects you |
Cheat sheet
| Topic | What to remember |
|---|---|
| Model | In-process library, one file, no server, no network |
| Concurrency | Many readers, one writer; lock granularity is the whole database |
| WAL | PRAGMA journal_mode=WAL; readers do not block the writer; same host only |
| Server preset | WAL, synchronous=NORMAL, foreign_keys=ON, busy_timeout=5000, cache_size=-65536, temp_store=MEMORY |
| Writes | BEGIN IMMEDIATE, short transactions, retry on SQLITE_BUSY |
| Checkpoint | Auto at 1000 pages; long readers stall it; wal_checkpoint(TRUNCATE) to reset |
| Types | Affinity coerces; use STRICT for enforcement |
| Backup | .backup, VACUUM INTO, sqlite3_rsync, Litestream; never cp a live file |
| FTS5 | Virtual table, MATCH, bm25(), snippet(), external content with triggers |
| JSON | JSON1 built in since 3.38; ->, ->>, json_each, JSONB 3.45+, index expressions |
| Go | Writer SetMaxOpenConns(1) + _txlock=immediate; PRAGMAs in DSN; :memory: needs one connection |
| Laravel | DB_CONNECTION=sqlite; busy_timeout, journal_mode, synchronous, transaction_mode keys; :memory: in tests |
| Scale | Litestream for backup, LiteFS/libSQL for read replicas, rqlite for Raft failover |
| Leave when | Many writers, many app servers, need roles and online DDL |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why is SQLite called serverless, and who coordinates two processes that open the same file? Must-know
Answer
Answer: There is no server process; each process links the library and coordinates through operating-system file locks on the database file (and, in WAL mode, a shared-memory wal-index in -shm). That is also why the files must be on one host.
2 — In rollback-journal mode, what is the commit point, and what is a hot journal? Good to know
Answer
Answer: The commit point is deleting (or zeroing) the journal after the changed pages are written and flushed. A hot journal is one left behind by a crash: the next connection finds it, takes the locks and copies the original pages back, so the transaction is rolled back.
3 — What does WAL change about concurrency, and what does it not change? Must-know
Answer
Answer: Readers and the writer no longer block each other because readers use an end mark and read the WAL up to it. There is still exactly one writer, because there is one WAL file.
4 — Why can a long-running read transaction make the -wal file grow without bound? Important
Answer
Answer: A checkpoint cannot copy frames past the end mark of the oldest reader, and the WAL can only be reset when no reader needs it, so with a permanent reader checkpoints stall and the WAL keeps growing.
5 — Order the lock states and say what PENDING is for. Good to know
Answer
Answer: UNLOCKED, SHARED, RESERVED, PENDING, EXCLUSIVE. PENDING stops new SHARED locks while existing readers finish, so a waiting writer is not starved.
6 — Why does BEGIN DEFERRED followed by a read and then a write sometimes fail with SQLITE_BUSY even with a large busy timeout? Important
Answer
Answer: The upgrade from a read snapshot to a write is impossible if the database changed since the snapshot (SQLITE_BUSY_SNAPSHOT), and waiting cannot make the snapshot fresh. Use BEGIN IMMEDIATE so the lock is taken before reading, and retry the whole transaction otherwise.
7 — What isolation does SQLite give, and how? Must-know
Answer
Answer: Serializable, by actually serializing writers (one at a time); readers see one snapshot (WAL end mark or held SHARED lock). Only shared-cache connections with read_uncommitted can see uncommitted data.
8 — What do type affinity and STRICT do differently when you insert 'abc' into an INTEGER column? Important
Answer
Answer: With affinity the text is stored as TEXT because it cannot be converted losslessly; with STRICT the insert fails with SQLITE_CONSTRAINT_DATATYPE.
9 — Name three PRAGMAs that are per connection and must be set for every pooled connection. Important
Answer
Answer: foreign_keys, busy_timeout, synchronous (also cache_size, temp_store, mmap_size). journal_mode=WAL is the notable one that persists in the file.
10 — Why does a Go test using :memory: fail with "no such table" intermittently? Must-know
Answer
Answer: The database/sql pool opens several connections and each :memory: connection is a separate database. Limit the pool to one connection, use a shared-cache in-memory URI, or use a temporary file.
11 — Give three safe ways to back up a live database and one unsafe way. Important
Answer
Answer: .backup / backup API, VACUUM INTO, Litestream (also sqlite3_rsync). Unsafe: copying the files with cp while writers are active.
12 — What does Litestream replicate and what does it not give you? Good to know
Answer
Answer: It streams the WAL as LTX files to object storage after taking over checkpointing, enabling point-in-time restore. It is asynchronous, has one writer, and provides no automatic failover or read scaling.
Glossary
| Term | One line |
|---|---|
| Embedded database | A database engine linked into the application as a library |
| Serverless (SQLite sense) | No separate database server process |
| Page | Fixed-size block (512 to 65536 bytes) that the file is made of |
| B-tree | Tree of pages used for every table and index |
| rowid | 64-bit integer key of an ordinary SQLite table row |
INTEGER PRIMARY KEY | Column that aliases the rowid |
WITHOUT ROWID | Table whose B-tree is keyed by its primary key |
sqlite_schema | Table (page 1 root) listing all schema objects, also sqlite_master |
| Overflow page | Page holding the tail of a row too large for its leaf |
| Freelist | Pages freed by deletes, reused before the file grows |
| Varint | Variable-length integer encoding (1 to 9 bytes) |
| Rollback journal | Side file with original pages used to undo an unfinished transaction |
| Hot journal | Journal left after a crash that must be replayed on next open |
| WAL | Write-ahead log: appended frames instead of in-place page writes |
| Frame | One page image plus header in the WAL |
| wal-index | Shared-memory map from page to newest WAL frame (-shm file) |
| End mark | Last commit frame a reader may see; fixes its snapshot |
| Checkpoint | Copying committed WAL frames back into the main file |
PASSIVE, FULL, RESTART, TRUNCATE | Checkpoint modes, increasing in how much they wait and reset |
| SHARED, RESERVED, PENDING, EXCLUSIVE | The lock states of a connection |
SQLITE_BUSY | Result code 5: a needed lock is held elsewhere |
SQLITE_BUSY_SNAPSHOT | Read-to-write upgrade on a stale snapshot |
SQLITE_LOCKED | Conflict inside a connection or shared cache |
Busy handler / busy_timeout | Callback or milliseconds to wait for a lock |
BEGIN DEFERRED / IMMEDIATE / EXCLUSIVE | When a transaction takes its locks |
| Type affinity | Column preference that coerces stored values |
| Storage class | NULL, INTEGER, REAL, TEXT or BLOB |
STRICT table | Table with enforced column types (3.37.0+) |
synchronous | How aggressively commits are fsynced (OFF, NORMAL, FULL, EXTRA) |
foreign_keys | PRAGMA enabling FK enforcement, per connection |
mmap_size | Bytes of the file read through memory mapping |
temp_store | Where temp tables and sort spill live |
| FTS5 | Full-text search virtual table module |
bm25 | Relevance ranking function used by FTS5 |
| JSON1 | The JSON extension (3.9.0), built into SQLite since 3.38.0 |
| JSONB | Binary JSON encoding stored in a BLOB (3.45.0+) |
| Upsert | INSERT ... ON CONFLICT DO UPDATE |
RETURNING | Clause returning rows changed by DML |
| Shared cache | Obsolete mode where connections in a process share a page cache |
VACUUM INTO | Writes a compacted consistent copy of the database to a new file |
| Online backup API | sqlite3_backup_* incremental live copy |
| Litestream | Streams SQLite WAL to object storage for backup and restore |
| LiteFS | FUSE-based replication of SQLite across nodes (Fly.io) |
| rqlite | Raft-replicated distributed database built on SQLite |
| libSQL | Open-contribution fork of SQLite by Turso |
| MC/DC | Modified condition/decision coverage, achieved by SQLite's tests |
References
All pages below were fetched and read; the texts are saved under the session's sources/sqlite/ folder.
- About SQLite
- Appropriate Uses For SQLite
- SQLite Is Serverless
- Database File Format
- Write-Ahead Logging
- File Locking And Concurrency In SQLite Version 3
- Atomic Commit In SQLite
- Isolation In SQLite
- Transaction (BEGIN DEFERRED, IMMEDIATE, EXCLUSIVE)
- PRAGMA statements
- Datatypes In SQLite and STRICT Tables
- SQLite FTS5 Extension
- JSON Functions And Operators
- The SQLite Query Planner
- UPSERT, RETURNING, Window Functions
- How SQLite Is Tested
- Limits In SQLite and Release History (changes)
- In-Memory Databases and SQLite Shared-Cache Mode
- How To Corrupt An SQLite Database File
- Online Backup API, VACUUM, Result and error codes, sqlite3_wal_checkpoint_v2
- Litestream: How it works
- LiteFS on Fly.io
- rqlite README and read consistency
- libSQL README (Turso)
- modernc.org/sqlite and mattn/go-sqlite3
- Laravel 13 Database, Database Testing, Queries (JSON where clauses), the Laravel 13 skeleton
config/database.phpandphpunit.xml, and the framework sourcesConcurrencyErrorDetector.php,ManagesTransactions.phpandSQLiteGrammar.php - DuckDB: Why DuckDB
Related pages: ACID & Transactions, Isolation Levels, Locks & Concurrency, Durability, WAL & Crash Recovery, Storage Engines, Indexing, Connection Pooling, PostgreSQL & Database Fundamentals, MySQL Storage Engines.