Skip to content

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 ​

TaskCommandNotes
Open or create a filesqlite3 app.dbNo argument opens a transient in-memory DB
Run one statementsqlite3 app.db "SELECT count(*) FROM t;"-cmd, -init file, -batch also exist
Read a script.read schema.sqlOr sqlite3 app.db < schema.sql
List tables.tablesAccepts a LIKE pattern: .tables 'user%'
Show DDL.schema or .schema users.fullschema adds stat tables
Column list.schema usersAlso 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 usersText backup; replay with .read
Reopen on another file.open other.dbCloses the current DB and opens the file; to attach, use ATTACH 'other.db' AS o; in SQL
Show databases.databasesLists main, temp and attached files
Settings.showCurrent settings; works in 3.54 but is not in its .help list
Timing.timer onPrints user and system time per statement
Query plan.eqp onAuto-prefix EXPLAIN QUERY PLAN
Stop on error.bail onUseful in scripts
Binary backup.backup main backup.dbOnline, uses the Backup API
Restore.restore main backup.dbReplaces the target DB contents
Database info.dbinfoShows 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 ​

TaskCommandNotes
File DBfile:app.db or app.dbfile: URIs allow query parameters
In-memory:memory:One private DB per connection
Shared in-memoryfile::memory:?cache=sharedAll connections in the process share it; the DB dies with the last connection
Named shared memoryfile:memdb1?mode=memory&cache=sharedSeveral names in one process
Read-only openfile:app.db?mode=roAlso immutable=1 for read-only media
Create-if-missing controlfile:app.db?mode=rwcrw fails when the file is absent
Go driver (cgo)import _ "github.com/mattn/go-sqlite3", driver sqlite3Needs a C toolchain
Go driver (pure Go)import _ "modernc.org/sqlite", driver sqliteNo cgo, easy cross-compile
mattn DSN pragmasfile:app.db?_busy_timeout=5000&_journal_mode=WAL&_foreign_keys=on&_synchronous=NORMALUnderscore-prefixed names; aliases like _fk
modernc DSN pragmasfile:app.db?_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)&_pragma=foreign_keys(1)Repeat _pragma per setting; applied on every new connection
Laravel driverDB_CONNECTION=sqlite, DB_DATABASE=/abs/path/app.sqliteconfig/database.php connection sqlite
Laravel in-memoryDB_DATABASE=:memory:Not on the 13.x database page: not verified for Laravel; commonly used in tests
Laravel foreign keysDB_FOREIGN_KEYS=falseForeign key constraints are enabled by default for SQLite connections; this env var disables them
Laravel pragmasbusy_timeout, journal_mode, synchronous, transaction_mode connection keysNot in the 13.x database page: not verified. Run DB::statement('PRAGMA journal_mode=WAL') in a service provider instead
Laravel create DB filetouch database/database.sqliteThe Laravel installer creates and migrates the file when you choose SQLite
go
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 pool

References: URI filenames, modernc.org/sqlite, mattn/go-sqlite3, Laravel database.

PRAGMAs ​

TaskCommandNotes
Journal modePRAGMA journal_mode = WAL;WAL persists in the file; others: DELETE, TRUNCATE, PERSIST, MEMORY, OFF
Durability levelPRAGMA synchronous = NORMAL;OFF=0, NORMAL=1, FULL=2, EXTRA=3; NORMAL is the usual WAL choice
Foreign keysPRAGMA foreign_keys = ON;Off by default; per connection, not persisted; no-op inside a transaction
Busy timeoutPRAGMA busy_timeout = 5000;Milliseconds to retry on lock; per connection
Page cachePRAGMA cache_size = -64000;Negative means KiB (64 MB); positive means pages
Memory-mapPRAGMA mmap_size = 268435456;Bytes; 0 disables; capped by compile option
Page sizePRAGMA 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 checkpointPRAGMA wal_autocheckpoint = 1000;Pages; default 1000; zero or negative disables
Manual checkpointPRAGMA wal_checkpoint(TRUNCATE);PASSIVE, FULL, RESTART, TRUNCATE, NOOP
Temp storagePRAGMA temp_store = MEMORY;DEFAULT=0, FILE=1, MEMORY=2
Journal size capPRAGMA journal_size_limit = 67108864;Bytes; bounds the WAL file after checkpoint
Auto vacuumPRAGMA auto_vacuum = INCREMENTAL;Set before creating tables, or follow with VACUUM
Reclaim pagesPRAGMA incremental_vacuum(100);Needs auto_vacuum INCREMENTAL
IntegrityPRAGMA integrity_check;quick_check is faster; foreign_key_check for FK violations
OptimizePRAGMA optimize;Run before closing or periodically; refreshes stats
Analysis limitPRAGMA analysis_limit = 400;Bounds work done by optimize
Schema versionPRAGMA user_version = 3;App-defined integer for migrations
Query-onlyPRAGMA query_only = ON;Rejects writes on this connection
Recursive triggersPRAGMA recursive_triggers = ON;Off by default
Untrusted schemaPRAGMA trusted_schema = OFF;ON by default; the docs encourage turning it OFF on every connection
Read any PRAGMAPRAGMA 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 ​

TaskCommandNotes
Create tableCREATE TABLE IF NOT EXISTS t (id INTEGER PRIMARY KEY, name TEXT NOT NULL);INTEGER PRIMARY KEY aliases the rowid
Strict typingCREATE TABLE t (id INTEGER PRIMARY KEY, n INT, s TEXT) STRICT;Types: INT, INTEGER, REAL, TEXT, BLOB, ANY; since 3.37
Without rowidCREATE 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
AUTOINCREMENTid INTEGER PRIMARY KEY AUTOINCREMENTNever reuses ids; adds sqlite_sequence overhead
Generated columntotal REAL GENERATED ALWAYS AS (qty * price) VIRTUALSTORED writes it to disk; since 3.31
Default expressioncreated_at TEXT NOT NULL DEFAULT (datetime('now'))Expressions need parentheses
CHECKCHECK (qty > 0)Enforced in both strict and flexible tables
Foreign keyFOREIGN KEY (uid) REFERENCES users(id) ON DELETE CASCADERequires PRAGMA foreign_keys = ON
Rename tableALTER TABLE t RENAME TO t2;Also RENAME COLUMN a TO b
Add columnALTER 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 columnALTER 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 changesCreate new table, copy rows, drop old, rename newThe documented 12-step procedure; wrap in a transaction
ViewCREATE VIEW v AS SELECT ...;Read-only unless INSTEAD OF triggers exist
TriggerCREATE TRIGGER tg AFTER INSERT ON t BEGIN UPDATE ...; END;Use NEW. and OLD.
Temp tableCREATE TEMP TABLE x (...);Lives in the temp database for the connection
DropDROP 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 ​

TaskCommandNotes
InsertINSERT INTO t (a, b) VALUES (1, 'x');Multi-row: repeat the tuple
Upsert, updateINSERT 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, ignoreINSERT INTO t (id) VALUES (1) ON CONFLICT DO NOTHING;Since 3.24
ReplaceINSERT 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 errorsINSERT OR IGNORE INTO t ...Skips rows violating constraints
RETURNINGINSERT INTO t (a) VALUES (1) RETURNING id;Also on UPDATE and DELETE; since 3.35
Update with joinUPDATE t SET x = s.x FROM s WHERE t.id = s.id;UPDATE FROM since 3.33
Delete limitDELETE FROM t WHERE ts < ? RETURNING id;LIMIT needs a special compile option; batch by rowid instead
Last idSELECT last_insert_rowid();Per connection; Go: res.LastInsertId()
Changed rowsSELECT changes();Rows affected by the latest statement
CTEWITH c AS (SELECT ...) SELECT * FROM c;WITH RECURSIVE for trees
WindowSELECT id, sum(n) OVER (PARTITION BY g ORDER BY ts) FROM t;Also row_number(), rank(), lag(), lead(); since 3.25
FrameROWS BETWEEN 2 PRECEDING AND CURRENT ROWRANGE and GROUPS frames also supported
PaginationWHERE (ts, id) < (?, ?) ORDER BY ts DESC, id DESC LIMIT 50Row values supported; prefer keyset to OFFSET
JSON extractSELECT json_extract(doc, '$.a.b') FROM t;Or doc -> '$.a' (JSON) and doc ->> '$.a' (SQL value)
JSON setjson_set(doc, '$.a', 1)json_insert, json_replace, json_remove, json_patch
JSON buildjson_object('k', v), json_array(1, 2)json_group_array(x) and json_group_object(k, v) aggregate
JSON iterateSELECT value FROM t, json_each(t.doc, '$.tags');json_tree walks recursively
JSON validityjson_valid(x), json_type(x, path)CHECK (json_valid(doc)) guards a column
JSONBjsonb(x), jsonb_set(...)Binary form since 3.45; store as BLOB
Datesdate('now'), datetime('now','-7 days'), strftime('%s','now')No native type; store ISO 8601 text, Unix integers or Julian days
Case-insensitiveCOLLATE NOCASEFolds the 26 ASCII letters only; no full Unicode folding
Concat, formata || b, printf('%05d', n)format() is an alias of printf

References: UPSERT, RETURNING, Window functions, JSON functions, Date and time.

Indexes ​

TaskCommandNotes
CreateCREATE INDEX idx_t_a ON t (a);Composite: (a, b); leftmost-prefix rule
UniqueCREATE UNIQUE INDEX ux ON t (email);NULLs are distinct from each other
PartialCREATE INDEX ix ON t (a) WHERE deleted_at IS NULL;Query must repeat a matching WHERE
ExpressionCREATE INDEX ix ON t (lower(email));Query must use the identical expression
DescendingCREATE INDEX ix ON t (ts DESC);Mostly irrelevant, the b-tree scans both ways
CoveringCREATE INDEX ix ON t (a, b, c);Plan shows USING COVERING INDEX
CollationCREATE INDEX ix ON t (name COLLATE NOCASE);Must match the query collation
DropDROP INDEX IF EXISTS ix;
RebuildREINDEX t;After collation changes
Refresh statsANALYZE; or PRAGMA optimize;Fills sqlite_stat1
List indexesPRAGMA index_list(t);index_info(idx) and index_xinfo(idx) show columns
Force indexSELECT ... 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 ​

TaskCommandNotes
Deferred (default)BEGIN; or BEGIN DEFERRED;Takes locks on first read or write; read-to-write upgrade can fail with BUSY
ImmediateBEGIN IMMEDIATE;Takes the write lock now; use for any transaction that will write
ExclusiveBEGIN EXCLUSIVE;In WAL equals IMMEDIATE; in rollback-journal modes also blocks readers
Commit / rollbackCOMMIT; / ROLLBACK;END equals COMMIT
SavepointSAVEPOINT sp1; ... ROLLBACK TO sp1; ... RELEASE sp1;Nested transactions
Go: IMMEDIATE (mattn)DSN _txlock=immediateApplies to every db.Begin
Go: IMMEDIATE (modernc)DSN _txlock=immediateSame _txlock parameter (deferred, immediate, exclusive)
Go: manualconn.ExecContext(ctx, "BEGIN IMMEDIATE") on a *sql.ConnPin one connection; end with COMMIT
LaravelDB::transaction(fn () => ...)Default BEGIN is deferred; sqlite connection options such as transaction_mode are not verified for 13.x
Retry on BUSYCatch code 5, back off with jitter, retry the whole transactionbusy_timeout does not help a deferred read-to-write upgrade
Concurrency modelMany readers plus one writer (WAL); one writer and no readers during commit (rollback journal)Keep write transactions short
Single writer in Godb.SetMaxOpenConns(1) or a dedicated writer *sql.DBAvoids lock contention inside the process
Long readerBlocks WAL checkpoint from finishingWAL file grows until the reader ends

References: Transactions, Locking and concurrency, Result codes.

TaskCommandNotes
CreateCREATE 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
InsertINSERT INTO docs (title, body) VALUES ('a', 'b');
MatchSELECT * FROM docs WHERE docs MATCH 'sqlite AND fts5';Operators AND, OR, NOT, NEAR
Phrase and prefixMATCH '"full text" OR data*'Quotes for phrases, * for prefix
Column filterMATCH 'title : sqlite'Also {title body} : x
RankSELECT * FROM docs WHERE docs MATCH ? ORDER BY rank;Hidden rank column is BM25 by default; lower is better
Weighted rankORDER BY bm25(docs, 10.0, 1.0)Per-column weights
Snippetsnippet(docs, 1, '[', ']', '...', 12)Highlight in a column
Highlighthighlight(docs, 1, '[', ']')Whole text with markers
RebuildINSERT INTO docs (docs) VALUES ('rebuild');Re-reads external content
Merge or optimizeINSERT INTO docs (docs) VALUES ('optimize');Compacts the index
Delete in external contentINSERT INTO docs (docs, rowid, body) VALUES ('delete', old_id, old_body);Needed in an update or delete trigger
IntegrityINSERT INTO docs (docs, rank) VALUES ('integrity-check', 1);

References: FTS5.

Backup, introspection and maintenance ​

TaskCommandNotes
CLI backup.backup main out.dbSafe while other connections are active
Copy into new fileVACUUM INTO 'out.db';Compact consistent snapshot; target must not exist or must be an empty file; since 3.27
Reclaim spaceVACUUM;Rewrites the file; needs free disk of about the DB size
Do not copy live filesNever cp app.db while writers runIn WAL mode also copy -wal and -shm, or use the methods above
Online backup APIsqlite3_backup_initGo mattn exposes Backup() on SQLiteConn
List objectsSELECT type, name, sql FROM sqlite_master;sqlite_schema is the modern alias
Table columnsPRAGMA table_info(t);table_xinfo includes hidden and generated columns
Foreign keysPRAGMA foreign_key_list(t);
Table listPRAGMA table_list;Includes type, strict and WITHOUT ROWID flags
Query planEXPLAIN QUERY PLAN SELECT ...;Look for SEARCH ... USING INDEX versus SCAN
BytecodeEXPLAIN SELECT ...;Low level; rarely needed
StatsSELECT * FROM sqlite_stat1;After ANALYZE
Page usagesqlite3_analyzer app.dbSeparate tool; or the dbstat virtual table
Free pagesPRAGMA freelist_count;Pages reclaimable by VACUUM
SizePRAGMA page_count;Times page_size gives bytes
VersionSELECT sqlite_version();Check feature availability

References: Backup API, VACUUM, EXPLAIN QUERY PLAN, Schema table.

Limits ​

LimitDefaultNotes
Max database sizeabout 281 TBpage_size 65536 times 4,294,967,294 pages
Max row or BLOB or string1,000,000,000 bytesSQLITE_MAX_LENGTH
Max SQL statement length1,000,000,000 bytesSQLITE_MAX_SQL_LENGTH
Max columns per table2000Up to 32767 at compile time
Max bound parameters32766Was 999 before 3.32
Max attached databases10Up to 125 at compile time
Max expression depth1000
Max compound SELECT terms500
Writers at once1 per databaseReads are concurrent
Max page size65536Power of two, 512 or more

References: Limits.

Common errors ​

ErrorCauseFix
database is locked (SQLITE_BUSY, 5)Another connection holds a conflicting lockSet busy_timeout, use WAL, BEGIN IMMEDIATE, shorten transactions
database table is locked (SQLITE_LOCKED, 6)Conflict inside one connection or shared cacheFinish or reset open statements; avoid shared cache
FOREIGN KEY constraint failedFK violated with foreign_keys=ONInsert parents first; PRAGMA foreign_key_check
UNIQUE constraint failed: t.colDuplicate keyUse ON CONFLICT
NOT NULL constraint failedMissing valueFix input or default
cannot start a transaction within a transactionNested BEGINUse SAVEPOINT
attempt to write a readonly databaseFile or directory permissions, mode=ro, or missing -wal accessFix owner; directory must be writable for WAL
no such tableWrong file path (relative path resolved from another cwd) or a fresh :memory: per connectionUse an absolute path or shared-cache memory URI
database disk image is malformedCorruptionRestore from backup; .recover in CLI may salvage rows
unable to open database fileMissing directory or no permissionCreate the directory first
too many SQL variablesOver the bound parameter limitBatch the IN list
cannot ALTER ... columnUnsupported ALTER form12-step table rebuild
cannot store TEXT value in INT column t.aSTRICT table type violation (SQLITE_CONSTRAINT_DATATYPE)Cast or fix the value
datatype mismatch (SQLITE_MISMATCH, 20)E.g. a non-integer rowidUse an integer rowid

References: Result codes, How to corrupt SQLite.

Built by Morteza Negahi