SQLite¶
Scope: SQLite embedded in an application as its local database or file format: mobile and desktop apps, local-first data, game saves, tools, and small servers that keep the database on their own disk. The guidelines cover SQLite 3.54, the current release, and point out features that need a minimum version, because apps often use the copy of SQLite that the operating system provides. Hosted services built on SQLite, such as Cloudflare D1, aren't covered. Architecture-level data rules, such as versioned migrations and backups, are in general/data.md (DATA-2, DATA-8), and validating input in general/security.md (SEC-10). For save data in games, this file shows how to apply GAMEDEV-10 and GAMEDEV-11 from Game development in SQLite, and Steam Cloud saves are in Steam and PC games (STEAM-9). Offline-first mobile apps with a local database are covered in Android (ANDROID-7) and Flutter, and backends that sync data to the cloud in Firebase and Supabase. When the data lives on a server that many clients share, see PostgreSQL.
Entries are sorted by score from 1 to 10 (criteria): 9โ10 start here or strongly recommended, 6โ8 recommended, 1โ5 further reading or conditional.
Adopted references¶
- 9 SQLite Documentation (SQLite): the baseline. The SQL dialect, the C interface, pragmas, file format, locking, transactions and the technical notes on using SQLite well.
- 8 Appropriate Uses For SQLite (SQLite): where SQLite works well, where a client/server database works better, and a checklist for choosing between them.
- 8 How To Corrupt An SQLite Database File (SQLite): the ways databases get corrupted in practice, such as copying files during a transaction, deleting journals, broken file locking and disabled syncs, and how to avoid each one.
- 8 Defense Against The Dark Arts (SQLite): precautions for applications that run untrusted SQL or open database files of uncertain origin.
- 7 Pragma statements supported by SQLite (SQLite): the settings for each connection and database, such as
foreign_keys,journal_mode,synchronous,busy_timeout,user_version,optimizeandintegrity_check. - 7 Quirks, Caveats, and Gotchas In SQLite (SQLite): where SQLite differs from other SQL databases, such as flexible typing, foreign keys being off by default, and primary keys that can contain NULLs.
- 7 Write-Ahead Logging (SQLite): how WAL mode works, its advantages and limits, checkpoints and WAL file growth.
- 7 Best practices for SQLite performance (Android Developers): WAL, synchronous mode, indexes, transactions and connection handling for SQLite on Android.
- 6 SQLite As An Application File Format (SQLite): why an SQLite database can replace custom document or save file formats, and its security considerations.
Key rules¶
Choosing and placing SQLite¶
- 8
SQLITE-1Use SQLite where the data is on the same machine as the code that queries it and writers can take turns; choose a client/server database, such as PostgreSQL, when the data is on another machine, many processes must write at the same instant, or the data is heading for terabytes. SQLite allows one writer at a time for each database file, but a write transaction usually takes only milliseconds. (SQLite, Appropriate Uses: checklist for choosing the right database engine, SQLite Over a Network, Caveats and Considerations) - 8
SQLITE-2Never share a database between processes or machines through a network file system, such as NFS or SMB. File locking is often broken on network file systems, which can corrupt the database, and WAL mode doesn't work over a network file system at all. (SQLite, How To Corrupt: file systems with broken or missing lock implementations, FAQ (5), Write-Ahead Logging: overview)
Connections and concurrency¶
- 8
SQLITE-3Configure every connection in one place as soon as it opens:PRAGMA foreign_keys=ON, a busy timeout, andPRAGMA trusted_schema=OFF. These settings belong to the connection, not the database file. Foreign key enforcement is off by default, must be turned on for each connection and can't be changed inside a transaction, and the SQLite docs encourage every application to turntrusted_schemaoff. (SQLite, Foreign Key Support: enabling foreign key support, PRAGMA foreign_keys, PRAGMA busy_timeout, PRAGMA trusted_schema) - 7
SQLITE-4Use WAL mode (PRAGMA journal_mode=WAL) for databases that are read while they are written, setPRAGMA synchronous=NORMALwhen each connection opens, and never setsynchronous=OFFfor data you need to keep. In WAL mode, readers and the writer don't block each other, andNORMALcan't corrupt the database, though the last commits can be lost on a power failure; withOFF, a power failure can corrupt it. On Android, enable WAL through the framework rather than with the pragma; Room does so by default on devices that aren't low on RAM. (SQLite, Write-Ahead Logging, PRAGMA synchronous, How To Corrupt: disabling sync using pragmas, Android, Best practices for SQLite performance) - 7
SQLITE-5Send all writes through one connection or a serial queue, start transactions that will write withBEGIN IMMEDIATE, and keep write transactions short. Only one write transaction can run at a time. A transaction that starts with a read and then writes fails withSQLITE_BUSYif another connection has written in the meantime, and SQLite skips the busy handler when waiting could deadlock. (SQLite, Transaction: read transactions versus write transactions, DEFERRED, IMMEDIATE, and EXCLUSIVE transactions, sqlite3_busy_handler(), Android, Best practices for SQLite performance)
Schema and queries¶
- 9
SQLITE-6Bind values with SQLite's placeholders,?or:name, through the driver's parameter API, such as the second argument of Python'sexecute(). This is how SQLite appliesSEC-18, whose allowlist covers table and column names, which placeholders can't stand for. (Python, sqlite3: how to use placeholders to bind values, SQLite, Binding Values To Prepared Statements, OWASP SQL Injection Prevention Cheat Sheet: parameterized queries, allow-list input validation) - 7
SQLITE-7Record the schema version inPRAGMA user_version, and when the app opens a database, apply the missing migrations in order, each in a transaction. For changes thatALTER TABLEcan't make, follow SQLite's 12-step procedure for rebuilding a table and finish withPRAGMA foreign_key_check. This is how to applyDATA-2, andGAMEDEV-10for saves, in SQLite:user_versionis an integer in the database header that SQLite leaves to the application. (SQLite, PRAGMA user_version, ALTER TABLE: making other kinds of table schema changes, Android, Best practices for SQLite performance) - 6
SQLITE-8Create new tables asSTRICTtables once every SQLite version that opens the file is 3.37.0 or later. In ordinary tables, column types are only advisory, so a column can quietly hold values of any type; a strict table rejects values that can't be converted losslessly, andintegrity_checkchecks the types. Older versions of SQLite can't open a database that contains strict tables. (SQLite, STRICT Tables, Backwards compatibility, Quirks: flexible typing) - 6
SQLITE-9Group related writes into one explicit transaction instead of letting each statement commit on its own. Every commit pays the full cost of syncing to disk, so batching makes bulk writes much faster and keeps related changes atomic. (SQLite, FAQ (19), Android, Best practices for SQLite performance) - 5
SQLITE-10Index the columns that frequent queries filter, sort or join on, including the child columns of foreign keys, check plans withEXPLAIN QUERY PLAN, and runPRAGMA optimizeas SQLite recommends: before closing short-lived connections, periodically on long-lived ones, and after schema changes. (SQLite, Query Planning, EXPLAIN QUERY PLAN, PRAGMA optimize, Foreign Key Support: required and suggested indexes)
Backups and file handling¶
- 8
SQLITE-11Copy a live database only with the online backup API,VACUUM INTOorsqlite3_rsync, never copy the database file while a connection may be writing to it, and never delete, rename or separate it from its-walor-journalfile. A file copied during a transaction can mix old and new content, and a database separated from its hot journal can't recover after a crash. For files that users copy or a cloud service syncs, such as game saves (STEAM-9), sync a copy made this way, or close every connection first: the last connection to close checkpoints and deletes the WAL file. (SQLite, How To Corrupt: backup or restore while a transaction is active, deleting a hot journal, SQLite Backup API, VACUUM INTO, sqlite3_rsync, Write-Ahead Logging: the WAL file) - 6
SQLITE-12Check backups and saves withPRAGMA integrity_check, or the fasterquick_check, before you rely on them, and keep the previous good copy until the new one passes. This is how to applyGAMEDEV-11and the restore tests ofDATA-8in SQLite.integrity_checkdoesn't find foreign key violations; usePRAGMA foreign_key_checkfor those. (SQLite, PRAGMA integrity_check, PRAGMA quick_check)
Untrusted databases and SQL¶
- 6
SQLITE-13Treat a database file that someone else could have written, such as a shared save, a mod or a downloaded file, as untrusted input (SEC-10): keeptrusted_schemaoff, and in security-sensitive apps runPRAGMA quick_checkbefore any other statement, reject files that fail, and setPRAGMA cell_size_check=ONandPRAGMA mmap_size=0. SQLite is built to reject malformed files safely; these steps add defense against undiscovered bugs and against schemas that call the application's own SQL functions. (SQLite, Defense Against The Dark Arts: untrusted SQLite database files, PRAGMA cell_size_check, PRAGMA mmap_size, SQLite As An Application File Format: security considerations) - 5
SQLITE-14If the app runs SQL written by users or mods, turn onSQLITE_DBCONFIG_DEFENSIVE, lower the limits withsqlite3_limit(), and restrict what statements may do with an authorizer callback. The defensive flag stops ordinary SQL from deliberately corrupting the database file, for example throughPRAGMA writable_schema=ONorjournal_mode=OFF. (SQLite, Defense Against The Dark Arts: untrusted SQL inputs, SQLITE_DBCONFIG_DEFENSIVE)
How to enforce¶
Tools that check the key rules above automatically, in CI, the IDE or a commit hook. "Partly" means the tool covers only some of what the rule asks.
- 6 CodeQL, SQL query built from user-controlled sources: code-scanning queries that trace untrusted input into SQL strings, also for JavaScript and TypeScript, Java and Kotlin and Swift, whose examples use SQLite. Partly checks
SQLITE-6. - 6 Ruff
hardcoded-sql-expression(S608): flags Python strings that look like SQL and are built with formatting or concatenation. Partly checksSQLITE-6. - 6
PRAGMA foreign_key_checkandPRAGMA integrity_check: built into SQLite; run them in tests against databases created and migrated by the app's own code, and fail the build on any result other than an empty list orok.foreign_key_checkreports rows that break foreign key constraints, such as rows written by a connection that never turned enforcement on. Partly checksSQLITE-3andSQLITE-7.
Tutorials and further reading¶
- 6 Query Planning (SQLite): how SQLite uses indexes to find and sort rows, and how to design indexes for your queries.
- 6 Persist data with SQLite (Flutter cookbook): opening a database, creating a table, and inserting, querying, updating and deleting rows with bound parameters from a Flutter app.
- 5 Atomic Commit In SQLite (SQLite): how SQLite makes transactions atomic across crashes and power failures, and what can go wrong.
- 5 Persistent Storage Options (SQLite Wasm): keeping SQLite databases in the browser with the Origin-Private File System (OPFS), and choosing between its storage back ends.