SQLite Cheatsheet
A dense quick reference for the sqlite3 shell, PRAGMAs, SQL dialect features, FTS5, backup and the Go and Laravel connection details. Concepts live in the SQLite in Depth chapter.
CLI dot-commands
| Task | Command | Notes |
|---|---|---|
| Open or create a file | sqlite3 app.db | No argument opens a transient in-memory DB |
| Run one statement | sqlite3 app.db "SELECT count(*) FROM t;" | -cmd, -init file, -batch also exist |
| Read a script | .read schema.sql | Or sqlite3 app.db < schema.sql |
| List tables | .tables | Accepts a LIKE pattern: .tables 'user%' |
| Show DDL | .schema or .schema users | .fullschema adds stat tables |
| Column list | .schema users | Also PRAGMA table_info(users) |
| Output mode | .mode box / column / csv / json / markdown / line | .mode --list lists modes; --title on adds headers (.headers on still works but is not in the 3.54 help) |
| Import CSV | .import --csv data.csv t | --skip 1 skips the header row; if the table is missing it is created from the first row, otherwise every row is data |
| Export to file | .output out.txt then .output stdout | .once file redirects only the next result |
| Dump as SQL | .dump or .dump users | Text backup; replay with .read |
| Reopen on another file | .open other.db | Closes the current DB and opens the file; to attach, use ATTACH 'other.db' AS o; in SQL |
| Show databases | .databases | Lists main, temp and attached files |
| Settings | .show | Current settings; works in 3.54 but is not in its .help list |
| Timing | .timer on | Prints user and system time per statement |
| Query plan | .eqp on | Auto-prefix EXPLAIN QUERY PLAN |
| Stop on error | .bail on | Useful in scripts |
| Binary backup | .backup main backup.db | Online, uses the Backup API |
| Restore | .restore main backup.db | Replaces the target DB contents |
| Database info | .dbinfo | Shows status information about the database |
| Quit | .quit or .exit | .exit ?CODE? sets the exit code |
References: sqlite3 CLI, CLI output modes.
Connection: DSN, Go and Laravel
| Task | Command | Notes |
|---|---|---|
| File DB | file:app.db or app.db | file: URIs allow query parameters |
| In-memory | :memory: | One private DB per connection |
| Shared in-memory | file::memory:?cache=shared | All connections in the process share it; the DB dies with the last connection |
| Named shared memory | file:memdb1?mode=memory&cache=shared | Several names in one process |
| Read-only open | file:app.db?mode=ro | Also immutable=1 for read-only media |
| Create-if-missing control | file:app.db?mode=rwc | rw fails when the file is absent |
| Go driver (cgo) | import _ "github.com/mattn/go-sqlite3", driver sqlite3 | Needs a C toolchain |
| Go driver (pure Go) | import _ "modernc.org/sqlite", driver sqlite | No cgo, easy cross-compile |
| mattn DSN pragmas | file:app.db?_busy_timeout=5000&_journal_mode=WAL&_foreign_keys=on&_synchronous=NORMAL | Underscore-prefixed names; aliases like _fk |
| modernc DSN pragmas | file:app.db?_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)&_pragma=foreign_keys(1) | Repeat _pragma per setting; applied on every new connection |
| Laravel driver | DB_CONNECTION=sqlite, DB_DATABASE=/abs/path/app.sqlite | config/database.php connection sqlite |
| Laravel in-memory | DB_DATABASE=:memory: | Not on the 13.x database page: not verified for Laravel; commonly used in tests |
| Laravel foreign keys | DB_FOREIGN_KEYS=false | Foreign key constraints are enabled by default for SQLite connections; this env var disables them |
| Laravel pragmas | busy_timeout, journal_mode, synchronous, transaction_mode connection keys | Not in the 13.x database page: not verified. Run DB::statement('PRAGMA journal_mode=WAL') in a service provider instead |
| Laravel create DB file | touch database/database.sqlite | The Laravel installer creates and migrates the file when you choose SQLite |
db, err := sql.Open("sqlite", "file:app.db?_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)&_pragma=foreign_keys(1)")
if err != nil { log.Fatal(err) }
db.SetMaxOpenConns(1) // simplest writer discipline; or split into a writer pool of 1 and a reader poolReferences: URI filenames, modernc.org/sqlite, mattn/go-sqlite3, Laravel database.
PRAGMAs
| Task | Command | Notes |
|---|---|---|
| Journal mode | PRAGMA journal_mode = WAL; | WAL persists in the file; others: DELETE, TRUNCATE, PERSIST, MEMORY, OFF |
| Durability level | PRAGMA synchronous = NORMAL; | OFF=0, NORMAL=1, FULL=2, EXTRA=3; NORMAL is the usual WAL choice |
| Foreign keys | PRAGMA foreign_keys = ON; | Off by default; per connection, not persisted; no-op inside a transaction |
| Busy timeout | PRAGMA busy_timeout = 5000; | Milliseconds to retry on lock; per connection |
| Page cache | PRAGMA cache_size = -64000; | Negative means KiB (64 MB); positive means pages |
| Memory-map | PRAGMA mmap_size = 268435456; | Bytes; 0 disables; capped by compile option |
| Page size | PRAGMA page_size = 4096; | Power of two, 512 to 65536; applies when the DB is created or at the next VACUUM (not in WAL mode) |
| Auto checkpoint | PRAGMA wal_autocheckpoint = 1000; | Pages; default 1000; zero or negative disables |
| Manual checkpoint | PRAGMA wal_checkpoint(TRUNCATE); | PASSIVE, FULL, RESTART, TRUNCATE, NOOP |
| Temp storage | PRAGMA temp_store = MEMORY; | DEFAULT=0, FILE=1, MEMORY=2 |
| Journal size cap | PRAGMA journal_size_limit = 67108864; | Bytes; bounds the WAL file after checkpoint |
| Auto vacuum | PRAGMA auto_vacuum = INCREMENTAL; | Set before creating tables, or follow with VACUUM |
| Reclaim pages | PRAGMA incremental_vacuum(100); | Needs auto_vacuum INCREMENTAL |
| Integrity | PRAGMA integrity_check; | quick_check is faster; foreign_key_check for FK violations |
| Optimize | PRAGMA optimize; | Run before closing or periodically; refreshes stats |
| Analysis limit | PRAGMA analysis_limit = 400; | Bounds work done by optimize |
| Schema version | PRAGMA user_version = 3; | App-defined integer for migrations |
| Query-only | PRAGMA query_only = ON; | Rejects writes on this connection |
| Recursive triggers | PRAGMA recursive_triggers = ON; | Off by default |
| Untrusted schema | PRAGMA trusted_schema = OFF; | ON by default; the docs encourage turning it OFF on every connection |
| Read any PRAGMA | PRAGMA journal_mode; | No = reads the current value |
Common production preset: journal_mode=WAL, synchronous=NORMAL, foreign_keys=ON, busy_timeout=5000, cache_size=-64000, temp_store=MEMORY.
References: PRAGMA statements, Write-ahead logging.
DDL
| Task | Command | Notes |
|---|---|---|
| Create table | CREATE TABLE IF NOT EXISTS t (id INTEGER PRIMARY KEY, name TEXT NOT NULL); | INTEGER PRIMARY KEY aliases the rowid |
| Strict typing | CREATE TABLE t (id INTEGER PRIMARY KEY, n INT, s TEXT) STRICT; | Types: INT, INTEGER, REAL, TEXT, BLOB, ANY; since 3.37 |
| Without rowid | CREATE TABLE kv (k TEXT PRIMARY KEY, v BLOB) WITHOUT ROWID; | Clustered on the PK; needs a PRIMARY KEY |
| Combine options | ... ) STRICT, WITHOUT ROWID; | Comma-separated table options |
| AUTOINCREMENT | id INTEGER PRIMARY KEY AUTOINCREMENT | Never reuses ids; adds sqlite_sequence overhead |
| Generated column | total REAL GENERATED ALWAYS AS (qty * price) VIRTUAL | STORED writes it to disk; since 3.31 |
| Default expression | created_at TEXT NOT NULL DEFAULT (datetime('now')) | Expressions need parentheses |
| CHECK | CHECK (qty > 0) | Enforced in both strict and flexible tables |
| Foreign key | FOREIGN KEY (uid) REFERENCES users(id) ON DELETE CASCADE | Requires PRAGMA foreign_keys = ON |
| Rename table | ALTER TABLE t RENAME TO t2; | Also RENAME COLUMN a TO b |
| Add column | ALTER TABLE t ADD COLUMN c TEXT; | No PRIMARY KEY or UNIQUE; no default of CURRENT_TIME, CURRENT_DATE, CURRENT_TIMESTAMP or a parenthesized expression; no STORED generated column |
| Drop column | ALTER TABLE t DROP COLUMN c; | Fails if the column is a PRIMARY KEY or UNIQUE, indexed, or used in a CHECK, foreign key, generated column, trigger or view |
| Other changes | Create new table, copy rows, drop old, rename new | The documented 12-step procedure; wrap in a transaction |
| View | CREATE VIEW v AS SELECT ...; | Read-only unless INSTEAD OF triggers exist |
| Trigger | CREATE TRIGGER tg AFTER INSERT ON t BEGIN UPDATE ...; END; | Use NEW. and OLD. |
| Temp table | CREATE TEMP TABLE x (...); | Lives in the temp database for the connection |
| Drop | DROP TABLE IF EXISTS t; | Also DROP INDEX, DROP VIEW |
Type affinity (non-STRICT tables): INTEGER, TEXT, BLOB, REAL, NUMERIC decide how values are coerced; any value can land in any column. Use STRICT to enforce types.
References: CREATE TABLE, STRICT tables, Generated columns, ALTER TABLE, WITHOUT ROWID.
DML: UPSERT, RETURNING, windows, JSON
| Task | Command | Notes |
|---|---|---|
| Insert | INSERT INTO t (a, b) VALUES (1, 'x'); | Multi-row: repeat the tuple |
| Upsert, update | INSERT INTO t (id, n) VALUES (1, 5) ON CONFLICT(id) DO UPDATE SET n = n + excluded.n; | excluded is the proposed row; conflict target must be unique |
| Upsert, ignore | INSERT INTO t (id) VALUES (1) ON CONFLICT DO NOTHING; | Since 3.24 |
| Replace | INSERT OR REPLACE INTO t ... | Deletes the conflicting row first; delete triggers fire only if recursive_triggers is on; the update hook and change counter ignore the deletion |
| Ignore errors | INSERT OR IGNORE INTO t ... | Skips rows violating constraints |
| RETURNING | INSERT INTO t (a) VALUES (1) RETURNING id; | Also on UPDATE and DELETE; since 3.35 |
| Update with join | UPDATE t SET x = s.x FROM s WHERE t.id = s.id; | UPDATE FROM since 3.33 |
| Delete limit | DELETE FROM t WHERE ts < ? RETURNING id; | LIMIT needs a special compile option; batch by rowid instead |
| Last id | SELECT last_insert_rowid(); | Per connection; Go: res.LastInsertId() |
| Changed rows | SELECT changes(); | Rows affected by the latest statement |
| CTE | WITH c AS (SELECT ...) SELECT * FROM c; | WITH RECURSIVE for trees |
| Window | SELECT id, sum(n) OVER (PARTITION BY g ORDER BY ts) FROM t; | Also row_number(), rank(), lag(), lead(); since 3.25 |
| Frame | ROWS BETWEEN 2 PRECEDING AND CURRENT ROW | RANGE and GROUPS frames also supported |
| Pagination | WHERE (ts, id) < (?, ?) ORDER BY ts DESC, id DESC LIMIT 50 | Row values supported; prefer keyset to OFFSET |
| JSON extract | SELECT json_extract(doc, '$.a.b') FROM t; | Or doc -> '$.a' (JSON) and doc ->> '$.a' (SQL value) |
| JSON set | json_set(doc, '$.a', 1) | json_insert, json_replace, json_remove, json_patch |
| JSON build | json_object('k', v), json_array(1, 2) | json_group_array(x) and json_group_object(k, v) aggregate |
| JSON iterate | SELECT value FROM t, json_each(t.doc, '$.tags'); | json_tree walks recursively |
| JSON validity | json_valid(x), json_type(x, path) | CHECK (json_valid(doc)) guards a column |
| JSONB | jsonb(x), jsonb_set(...) | Binary form since 3.45; store as BLOB |
| Dates | date('now'), datetime('now','-7 days'), strftime('%s','now') | No native type; store ISO 8601 text, Unix integers or Julian days |
| Case-insensitive | COLLATE NOCASE | Folds the 26 ASCII letters only; no full Unicode folding |
| Concat, format | a || b, printf('%05d', n) | format() is an alias of printf |
References: UPSERT, RETURNING, Window functions, JSON functions, Date and time.
Indexes
| Task | Command | Notes |
|---|---|---|
| Create | CREATE INDEX idx_t_a ON t (a); | Composite: (a, b); leftmost-prefix rule |
| Unique | CREATE UNIQUE INDEX ux ON t (email); | NULLs are distinct from each other |
| Partial | CREATE INDEX ix ON t (a) WHERE deleted_at IS NULL; | Query must repeat a matching WHERE |
| Expression | CREATE INDEX ix ON t (lower(email)); | Query must use the identical expression |
| Descending | CREATE INDEX ix ON t (ts DESC); | Mostly irrelevant, the b-tree scans both ways |
| Covering | CREATE INDEX ix ON t (a, b, c); | Plan shows USING COVERING INDEX |
| Collation | CREATE INDEX ix ON t (name COLLATE NOCASE); | Must match the query collation |
| Drop | DROP INDEX IF EXISTS ix; | |
| Rebuild | REINDEX t; | After collation changes |
| Refresh stats | ANALYZE; or PRAGMA optimize; | Fills sqlite_stat1 |
| List indexes | PRAGMA index_list(t); | index_info(idx) and index_xinfo(idx) show columns |
| Force index | SELECT ... FROM t INDEXED BY ix WHERE ...; | Errors if the index cannot be used; NOT INDEXED forbids |
References: CREATE INDEX, Partial indexes, Indexes on expressions, Query planner.
Transactions and SQLITE_BUSY
| Task | Command | Notes |
|---|---|---|
| Deferred (default) | BEGIN; or BEGIN DEFERRED; | Takes locks on first read or write; read-to-write upgrade can fail with BUSY |
| Immediate | BEGIN IMMEDIATE; | Takes the write lock now; use for any transaction that will write |
| Exclusive | BEGIN EXCLUSIVE; | In WAL equals IMMEDIATE; in rollback-journal modes also blocks readers |
| Commit / rollback | COMMIT; / ROLLBACK; | END equals COMMIT |
| Savepoint | SAVEPOINT sp1; ... ROLLBACK TO sp1; ... RELEASE sp1; | Nested transactions |
| Go: IMMEDIATE (mattn) | DSN _txlock=immediate | Applies to every db.Begin |
| Go: IMMEDIATE (modernc) | DSN _txlock=immediate | Same _txlock parameter (deferred, immediate, exclusive) |
| Go: manual | conn.ExecContext(ctx, "BEGIN IMMEDIATE") on a *sql.Conn | Pin one connection; end with COMMIT |
| Laravel | DB::transaction(fn () => ...) | Default BEGIN is deferred; sqlite connection options such as transaction_mode are not verified for 13.x |
| Retry on BUSY | Catch code 5, back off with jitter, retry the whole transaction | busy_timeout does not help a deferred read-to-write upgrade |
| Concurrency model | Many readers plus one writer (WAL); one writer and no readers during commit (rollback journal) | Keep write transactions short |
| Single writer in Go | db.SetMaxOpenConns(1) or a dedicated writer *sql.DB | Avoids lock contention inside the process |
| Long reader | Blocks WAL checkpoint from finishing | WAL file grows until the reader ends |
References: Transactions, Locking and concurrency, Result codes.
FTS5 full-text search
| Task | Command | Notes |
|---|---|---|
| Create | CREATE VIRTUAL TABLE docs USING fts5(title, body); | Column names only; no types |
| Tokenizer | ... USING fts5(title, body, tokenize = 'porter unicode61'); | Also trigram for substring search, ascii |
| External content | ... USING fts5(body, content='articles', content_rowid='id'); | Keep in sync with triggers |
| Insert | INSERT INTO docs (title, body) VALUES ('a', 'b'); | |
| Match | SELECT * FROM docs WHERE docs MATCH 'sqlite AND fts5'; | Operators AND, OR, NOT, NEAR |
| Phrase and prefix | MATCH '"full text" OR data*' | Quotes for phrases, * for prefix |
| Column filter | MATCH 'title : sqlite' | Also {title body} : x |
| Rank | SELECT * FROM docs WHERE docs MATCH ? ORDER BY rank; | Hidden rank column is BM25 by default; lower is better |
| Weighted rank | ORDER BY bm25(docs, 10.0, 1.0) | Per-column weights |
| Snippet | snippet(docs, 1, '[', ']', '...', 12) | Highlight in a column |
| Highlight | highlight(docs, 1, '[', ']') | Whole text with markers |
| Rebuild | INSERT INTO docs (docs) VALUES ('rebuild'); | Re-reads external content |
| Merge or optimize | INSERT INTO docs (docs) VALUES ('optimize'); | Compacts the index |
| Delete in external content | INSERT INTO docs (docs, rowid, body) VALUES ('delete', old_id, old_body); | Needed in an update or delete trigger |
| Integrity | INSERT INTO docs (docs, rank) VALUES ('integrity-check', 1); |
References: FTS5.
Backup, introspection and maintenance
| Task | Command | Notes |
|---|---|---|
| CLI backup | .backup main out.db | Safe while other connections are active |
| Copy into new file | VACUUM INTO 'out.db'; | Compact consistent snapshot; target must not exist or must be an empty file; since 3.27 |
| Reclaim space | VACUUM; | Rewrites the file; needs free disk of about the DB size |
| Do not copy live files | Never cp app.db while writers run | In WAL mode also copy -wal and -shm, or use the methods above |
| Online backup API | sqlite3_backup_init | Go mattn exposes Backup() on SQLiteConn |
| List objects | SELECT type, name, sql FROM sqlite_master; | sqlite_schema is the modern alias |
| Table columns | PRAGMA table_info(t); | table_xinfo includes hidden and generated columns |
| Foreign keys | PRAGMA foreign_key_list(t); | |
| Table list | PRAGMA table_list; | Includes type, strict and WITHOUT ROWID flags |
| Query plan | EXPLAIN QUERY PLAN SELECT ...; | Look for SEARCH ... USING INDEX versus SCAN |
| Bytecode | EXPLAIN SELECT ...; | Low level; rarely needed |
| Stats | SELECT * FROM sqlite_stat1; | After ANALYZE |
| Page usage | sqlite3_analyzer app.db | Separate tool; or the dbstat virtual table |
| Free pages | PRAGMA freelist_count; | Pages reclaimable by VACUUM |
| Size | PRAGMA page_count; | Times page_size gives bytes |
| Version | SELECT sqlite_version(); | Check feature availability |
References: Backup API, VACUUM, EXPLAIN QUERY PLAN, Schema table.
Limits
| Limit | Default | Notes |
|---|---|---|
| Max database size | about 281 TB | page_size 65536 times 4,294,967,294 pages |
| Max row or BLOB or string | 1,000,000,000 bytes | SQLITE_MAX_LENGTH |
| Max SQL statement length | 1,000,000,000 bytes | SQLITE_MAX_SQL_LENGTH |
| Max columns per table | 2000 | Up to 32767 at compile time |
| Max bound parameters | 32766 | Was 999 before 3.32 |
| Max attached databases | 10 | Up to 125 at compile time |
| Max expression depth | 1000 | |
| Max compound SELECT terms | 500 | |
| Writers at once | 1 per database | Reads are concurrent |
| Max page size | 65536 | Power of two, 512 or more |
References: Limits.
Common errors
| Error | Cause | Fix |
|---|---|---|
database is locked (SQLITE_BUSY, 5) | Another connection holds a conflicting lock | Set busy_timeout, use WAL, BEGIN IMMEDIATE, shorten transactions |
database table is locked (SQLITE_LOCKED, 6) | Conflict inside one connection or shared cache | Finish or reset open statements; avoid shared cache |
FOREIGN KEY constraint failed | FK violated with foreign_keys=ON | Insert parents first; PRAGMA foreign_key_check |
UNIQUE constraint failed: t.col | Duplicate key | Use ON CONFLICT |
NOT NULL constraint failed | Missing value | Fix input or default |
cannot start a transaction within a transaction | Nested BEGIN | Use SAVEPOINT |
attempt to write a readonly database | File or directory permissions, mode=ro, or missing -wal access | Fix owner; directory must be writable for WAL |
no such table | Wrong file path (relative path resolved from another cwd) or a fresh :memory: per connection | Use an absolute path or shared-cache memory URI |
database disk image is malformed | Corruption | Restore from backup; .recover in CLI may salvage rows |
unable to open database file | Missing directory or no permission | Create the directory first |
too many SQL variables | Over the bound parameter limit | Batch the IN list |
cannot ALTER ... column | Unsupported ALTER form | 12-step table rebuild |
cannot store TEXT value in INT column t.a | STRICT table type violation (SQLITE_CONSTRAINT_DATATYPE) | Cast or fix the value |
datatype mismatch (SQLITE_MISMATCH, 20) | E.g. a non-integer rowid | Use an integer rowid |
References: Result codes, How to corrupt SQLite.