Lesson 3 of 9 · 21m
PRAGMAs That Matter: Storage, Safety, and Predictable Performance
The configuration surface production SQLite users actually tune: journal mode, synchronous, foreign keys, cache size, mmap, temp storage, and schema design choices.
SQLite has no server configuration file. Behavior is controlled per database and per connection, mostly through PRAGMA statements. That is the first operational trap: tuning one connection does not automatically tune every process that opens the file.
Separate per-database from per-connection settings
Some pragmas persist in the database file:
PRAGMA journal_mode = WAL; -- persists for the database
PRAGMA user_version = 12; -- often used for application schema versioningOthers are connection-local and must be set every time the application opens the database:
PRAGMA foreign_keys = ON;
PRAGMA busy_timeout = 5000;
PRAGMA cache_size = -20000; -- about 20 MiB of page cacheIf your driver exposes connection setup hooks, use them. Relying on defaults is how foreign-key enforcement quietly differs between tests and production.
synchronous is a durability dial, not a speed hack
PRAGMA synchronous = FULL; -- strongest, slower
PRAGMA synchronous = NORMAL; -- common with WAL, usually safe across app crashes
PRAGMA synchronous = OFF; -- fast, dangerous across power lossIn WAL mode, NORMAL is the standard production choice. Commits can lose durability only in relatively narrow operating-system crash or power-loss scenarios, while application crashes remain protected. OFF is for rebuildable caches and bulk imports where losing the file is acceptable.
foreign_keys is off by default
PRAGMA foreign_keys;
-- 0 unless your connection enabled itSQLite parses foreign-key syntax even when enforcement is disabled, so schemas look disciplined while orphaned rows accumulate. Enable it on every connection and test constraint behavior explicitly.
cache, mmap, and temp storage
cache_size controls SQLite's page cache; negative values are approximate KiB. mmap_size can map the file into virtual memory and reduce copying on read-heavy workloads, but it is not magic. Temporary tables and some sorts use temp storage; PRAGMA temp_store = MEMORY helps only when the workload actually spills there.
Schema tuning starts with write shape
Use narrower indexes, batch imports inside transactions, and prefer stable monotonic keys when insertion order matters. Random UUID text keys fragment B-trees and enlarge indexes; if you need externally opaque IDs, store them beside an integer rowid.
Field notes
- Read pragmas back from the same connection that set them; process-wide assumptions are usually wrong.
user_versionis stored in the database header and updated transactionally, making it useful as a migration counter.PRAGMA optimizeis lighter-weight maintenance than blindly runningANALYZEafter every deployment.- Changing
page_sizeafter creation does nothing until the database is rebuilt withVACUUM.
Was this lesson helpful?