SQLite Interview Questions
Master SQLite technical interview questions covering WAL mode internals, B-Tree page layouts, single-writer multi-reader concurrency, PRAGMA synchronous tuning, and distributed edge architectures.
Practice SQLite Interview Questions
Showing 16 of 16 verified technical questions
What is SQLite, what architectural model does it follow, and how does its process-level storage model differ from client-server relational databases like PostgreSQL or MySQL?
SQLite is an embedded, serverless, zero-configuration relational database engine implemented as a compact C library. Unlike client-server RDBMS engines (PostgreSQL, MySQL) where clients communicate over TCP sockets or UNIX domain sockets to a standalone daemon process with dedicated background workers, SQLite executes directly within the host application process address space. SQLite stores the entire database (schema, tables, indexes, metadata) in a single cross-platform disk file. Concurrency is governed by operating system file locks (posix fcntl locks or win32 locks) rather than an independent lock manager process, completely eliminating network latency, IPC serialization overhead, and connection pool management.
-- Inspect SQLite connection and active storage pragmas
PRAGMA database_list;
PRAGMA compile_options;
PRAGMA journal_mode;Explain the fundamental differences between Rollback Journal mode and Write-Ahead Logging (WAL) mode in SQLite.
In traditional Rollback Journal mode (DELETE, TRUNCATE, PERSIST, MEMORY), when a transaction modifies database pages, the original uncommitted disk pages are copied into a rollback journal file before in-place overwrites happen in the main DB file. Readers and writers block each other completely: while a write transaction holds an EXCLUSIVE lock, no readers can query the database. In contrast, Write-Ahead Logging (WAL mode, enabled via PRAGMA journal_mode = WAL) inverts this workflow: original pages remain untouched in the main database file while newly committed pages append sequentially to a separate WAL file (-wal). Because readers query the main database file and read recent modifications from the WAL index (-shm), readers never block writers, and writers never block readers.
-- Switch SQLite connection to high-performance Write-Ahead Logging
PRAGMA journal_mode = WAL;
-- Check current mode
PRAGMA journal_mode;How does SQLite enforce the single-writer multiple-reader invariant in WAL mode, and how does the WAL index (-shm) facilitate zero-overhead snapshot isolation?
In WAL mode, SQLite enforces an architectural invariant: exactly one write transaction can execute at any instant in time, but an arbitrary number of concurrent read transactions can execute simultaneously without locks. When a reader starts a transaction, it records a read mark representing the end of the WAL at that timestamp. As the reader executes queries, it searches for required page numbers using the WAL index file (-shm, shared memory). The -shm file maps page numbers to their most recent frame in the WAL via hash tables in shared memory. If a page exists in the WAL up to the reader mark, the WAL version is returned; otherwise, the page is read from the main database file. Writers append new frames to the WAL without invalidating active readers.
-- Inspect WAL checkpoint statistics
PRAGMA wal_checkpoint(PASSIVE);
-- Returns: (busy, log_size_in_pages, checkpointed_pages)How do you diagnose, mitigate, and eliminate SQLITE_BUSY (database is locked) errors in high-throughput applications?
SQLITE_BUSY occurs when a transaction attempts to acquire a lock currently held by another thread or process. To eliminate SQLITE_BUSY: (1) Enable WAL mode (PRAGMA journal_mode = WAL) so readers never contend with writers. (2) Configure a busy timeout handler via sqlite3_busy_timeout() or PRAGMA busy_timeout = 5000 (ms), causing blocked connections to sleep with exponential backoff before throwing an error. (3) Direct all write operations through a single dedicated write connection or background channel (e.g., Node.js event loop or Go channel worker) while using a pool of read connections. (4) Use BEGIN IMMEDIATE or BEGIN EXCLUSIVE at transaction start to acquire write locks upfront rather than upgrading mid-transaction from deferred reads, preventing lock upgrade deadlocks.
-- Configure connection busy timeout to 5000ms
PRAGMA busy_timeout = 5000;
-- Start transaction immediately reserving the write lock
BEGIN IMMEDIATE;
UPDATE accounts SET balance = balance - 100 WHERE id = 42;
COMMIT;What is the role of PRAGMA synchronous, and what are the performance and crash-durability trade-offs between FULL, NORMAL, and OFF?
PRAGMA synchronous governs how aggressively SQLite invokes operating system sync primitives (fsync/fdatasync on POSIX, FlushFileBuffers on Windows) to guarantee disk controller cache flushes: (1) synchronous = FULL: SQLite synchronizes every transaction to physical non-volatile storage before returning. In WAL mode, it syncs the WAL file on every commit. Maximum durability, but throughput is limited by physical drive I/O operations per second. (2) synchronous = NORMAL: In WAL mode, SQLite syncs only during checkpoints and leaves commits un-fsynced between frames. The database is 100% crash-proof against OS crashes and power losses (WAL maintains integrity), with an order of magnitude higher write IOPS. (3) synchronous = OFF: SQLite passes data to the OS write buffer without fsync; power loss can corrupt the DB, suitable only for ephemeral caches or tests.
-- Enterprise high-performance recommended configuration for WAL mode
PRAGMA journal_mode = WAL;
PRAGMA synchronous = NORMAL;
PRAGMA temp_store = MEMORY;Describe SQLite on-disk B-Tree page layout, distinguishing between Table B-Trees and Index B-Trees, and Interior vs Leaf pages.
SQLite files consist of fixed-size pages (default 4096 bytes, up to 65536 bytes). SQLite utilizes two distinct B-Tree structures: (1) Table B-Trees: organize table rows keyed by 64-bit integer rowid. Leaf pages store the rowid and row payload (record format). Interior pages store rowid keys and child page pointers. (2) Index B-Trees: organize indexed values. Both leaf and interior pages store arbitrary key payloads. Every page begins with an 8-byte (leaf) or 12-byte (interior) page header (page 1 has an extra 100-byte database header). The header contains: page flag (0x02 interior index, 0x05 interior table, 0x0A leaf index, 0x0D leaf table), first freeblock offset, number of cells, cell content area start offset, and fragmented free bytes. Cell pointer arrays grow downward from the top of the page, while cell payloads grow upward from the bottom, meeting in the middle.
-- Inspect database page size and total page allocation
PRAGMA page_size;
PRAGMA page_count;
PRAGMA freelist_count;How do PRAGMA cache_size and PRAGMA mmap_size optimize memory management and avoid kernel page cache overhead in SQLite?
PRAGMA cache_size configures the size of the user-space page cache in memory. Positive integers specify page counts (e.g. 2000 pages = 8 MB); negative integers specify kibibytes (e.g. -64000 = 64 MB). When cached in user space, page lookups bypass read() syscalls. PRAGMA mmap_size instructs SQLite to map the database file directly into the application process virtual memory address space via mmap(). When enabled (e.g., PRAGMA mmap_size = 2147483648 for 2 GB), read requests access file pages directly via pointer dereferencing without copying data across kernel-user buffer boundaries, significantly accelerating sequential scans and index traversals.
-- Allocate 64MB user-space cache and up to 2GB memory-mapped I/O
PRAGMA cache_size = -64000;
PRAGMA mmap_size = 2147483648;How does Full-Text Search 5 (FTS5) work in SQLite, and how do you implement BM25 relevance ranking and prefix queries?
FTS5 is an SQLite virtual table module designed for fast full-text searching across millions of documents. FTS5 constructs an inverted index mapping token stems to docids and column offsets. It supports Unicode61 tokenizers, porter stemming, trigram sub-token indexing, phrase queries, and prefix matching. Searching uses the MATCH operator. Ranking is computed via the built-in bm25() auxiliary function, which calculates Okapi BM25 scores reflecting term frequency (TF) and inverse document frequency (IDF) weighted by column significance.
-- Create an FTS5 search index
CREATE VIRTUAL TABLE articles_fts USING fts5(
title,
body,
tokenize = "porter unicode61"
);
-- Execute BM25 ranked search
SELECT rowid, title, bm25(articles_fts, 5.0, 1.0) AS score
FROM articles_fts
WHERE articles_fts MATCH "distributed systems*"
ORDER BY score;What is the SQLite Virtual Table Mechanism (sqlite3_module), and how is it used to bridge arbitrary external datasources into SQL queries?
A Virtual Table in SQLite is a custom C/C++ struct conforming to the sqlite3_module interface. It allows developers to present arbitrary external data (CSV files, Git commits, Redis keys, OS processes, remote REST endpoints) as if they were standard relational SQLite tables. The module implements lifecycle callbacks: xCreate/xConnect (schema initialization), xBestIndex (query planner constraint negotiation and cost estimation), xFilter (query cursor initialization), xNext (row traversal), xColumn (data extraction), xRowid (unique identification), and xUpdate (insert/update/delete mutations). The SQLite query planner negotiates with xBestIndex to push down WHERE filters and index lookups directly to the external engine.
-- Querying virtual tables (such as CSV or JSON virtual tables)
CREATE VIRTUAL TABLE temp.logs USING csv(filename="access.log", schema="CREATE TABLE logs(ip TEXT, status INT)");
SELECT ip, COUNT(*) FROM logs WHERE status >= 500 GROUP BY ip;How do you perform hot online zero-downtime backups of an active production SQLite database under concurrent WAL writes?
Traditional file-copy commands (cp, rsync) across active SQLite databases cause database corruption because the main file and WAL file are read at non-atomic, shifting offsets during write operations. To guarantee atomic, zero-downtime backups: (1) Use the SQLite Online Backup API (sqlite3_backup_init, sqlite3_backup_step), which locks pages incrementally without blocking concurrent readers or writers. (2) From the CLI, use the atomic VACUUM INTO command: VACUUM INTO /path/to/backup.db; which produces a pristine, defragmented, standalone snapshot of the database at that exact transaction commit point. (3) Alternatively, use litestream or LiteFS for continuous physical frame-level replication to S3 or block storage.
-- Atomic hot backup executed within live application query stream
VACUUM INTO "/var/backups/production-snapshot-20261129.db";How does SQLite VACUUM work, and what is the difference between PRAGMA auto_vacuum and manual VACUUM?
When rows or tables are deleted in SQLite, empty B-Tree pages are not returned to the operating system; instead, they are linked into an in-file freelist for future page allocations. Over time, deletions create fragmentation and bloat the file. The VACUUM command rebuilds the entire database file from scratch into a temporary file, defragmenting all B-Tree pages and repacking cells into contiguous disk sectors, then atomically replaces the original file. In contrast, PRAGMA auto_vacuum = FULL / INCREMENTAL stores pointer maps on special pages to shift trailing free pages to the end of the file upon deletion, allowing truncate operations without a full database rebuild.
-- Check freelist count and reclaim space
PRAGMA freelist_count;
VACUUM;
PRAGMA freelist_count;How do you inspect and optimize SQLite query execution plans using EXPLAIN QUERY PLAN?
Prepend EXPLAIN QUERY PLAN to any SELECT, UPDATE, or DELETE statement. SQLite outputs a hierarchical execution graph showing: (1) SCAN TABLE table_name: indicates an unindexed full table scan (O(N) cost). (2) SEARCH TABLE table_name USING INDEX index_name (column=?): indicates an indexed B-Tree traversal (O(log N) cost). (3) COVERING INDEX: signifies all requested SELECT columns exist in the index B-Tree, completely eliminating secondary table leaf page lookups. (4) USE TEMP B-TREE: indicates in-memory or on-disk temporary sorting for ORDER BY or GROUP BY.
-- Analyze query execution path
EXPLAIN QUERY PLAN
SELECT customer_id, SUM(amount)
FROM orders
WHERE created_at >= "2026-01-01"
GROUP BY customer_id;How does SQLite handle JSON columns and the modern JSONB binary format introduced in recent releases?
SQLite includes first-class JSON support via built-in scalar and table-valued functions (json_extract, json_object, json_array, json_each, json_tree). In modern releases, SQLite introduced JSONB: an optimized binary serialization format. Unlike textual JSON which requires character-by-character re-parsing on every query execution, JSONB stores pre-parsed type tags and byte offsets. JSON functions (jsonb(), jsonb_extract()) operate directly on the binary BLOB, executing up to 3x faster and consuming up to 10% less disk storage.
-- Store and query binary JSON in SQLite
CREATE TABLE events (
id INTEGER PRIMARY KEY,
payload BLOB CHECK(json_valid(payload))
);
INSERT INTO events (payload) VALUES (jsonb('{"service":"auth","latency_ms":12.4}'));
SELECT id, json_extract(payload, '$.service') AS service
FROM events
WHERE json_extract(payload, '$.latency_ms') > 10;Explain Generated Columns (STORED vs VIRTUAL) and Expression Indexes in SQLite.
SQLite supports Generated (computed) Columns that calculate values dynamically from other columns: (1) VIRTUAL generated columns: computed on-the-fly during read operations, taking 0 extra bytes of storage on disk. (2) STORED generated columns: computed during write operations (INSERT/UPDATE) and physically stored on disk like regular columns. Expression Indexes allow indexing arbitrary expressions or functions (e.g. CREATE INDEX idx ON users(LOWER(email))), allowing index searches on function results without altering table schema or adding triggers.
CREATE TABLE products (
id INTEGER PRIMARY KEY,
price_cents INTEGER NOT NULL,
tax_rate REAL NOT NULL,
total_cents INTEGER GENERATED ALWAYS AS (price_cents + CAST(price_cents * tax_rate AS INT)) STORED
);
CREATE INDEX idx_products_total ON products(total_cents);How does SQLite enforce foreign key constraints, and why are they disabled by default for backwards compatibility?
For historical backwards compatibility with legacy versions prior to 3.6.19, SQLite disables foreign key constraint enforcement by default on new connections. To enforce referential integrity (RESTRICT, CASCADE, SET NULL on foreign keys), every connection must explicitly issue PRAGMA foreign_keys = ON; immediately after opening the database handle. When enabled, SQLite checks foreign key integrity on INSERT, UPDATE, and DELETE statements, rolling back violating transactions.
-- Enable foreign key constraints on the current connection
PRAGMA foreign_keys = ON;
-- Verify active enforcement status (must return 1)
PRAGMA foreign_keys;How do distributed SQLite architectures (such as Litestream, LiteFS, and Turso libSQL) enable global edge replication while preserving ACID guarantees?
Distributed SQLite architectures decouple single-writer replication from embedded query execution: (1) Litestream: acts as a continuous background process monitoring the SQLite WAL file; whenever a transaction commits and appends frames, Litestream streams those WAL frames asynchronously to S3 or object storage, providing physical point-in-time recovery without application modifications. (2) LiteFS: implements a FUSE virtual filesystem that intercepts SQLite file locks. LiteFS elects a single primary node via Raft or Consul that holds the exclusive write lock; all read replicas mount the LiteFS volume, receive live WAL transaction frames over LTX (LiteFS Transaction) streams, and execute reads locally with sub-millisecond latency. (3) Turso (libSQL): forks SQLite with native HTTP/WebSocket protocols, sqld daemons, and embedded replicas, allowing multi-region edge nodes to serve local reads while transparently delegating write transactions to a central primary.
-- libSQL embedded replica configuration
-- Read queries execute directly against local in-process SQLite cache;
-- Write queries transparently proxy to primary cloud database.
PRAGMA journal_mode = WAL;SQLite Track Coverage & Difficulty Profile
16 of 16 prompts include code examplesThis SQLite preparation set groups 16 prompts across Junior (3), Mid-Level (5), Senior (5), Staff / Principal (3) roles with 1 fundamental, 2 core architecture, 1 production engineering, 1 system internals, 1 internals & data structures, 2 performance tuning, 1 search & algorithms, 1 advanced systems, 1 reliability & operations, 1 storage internals, 1 modern features, 1 data modeling, 1 schema & invariants, 1 distributed systems exercises tailored to Databases & Storage.
What is SQLite, what architectural model does it follow, and how does its process-level storage model differ from client-server relational databases like PostgreSQL or MySQL?
Explain the fundamental differences between Rollback Journal mode and Write-Ahead Logging (WAL) mode in SQLite.
How does SQLite enforce the single-writer multiple-reader invariant in WAL mode, and how does the WAL index (-shm) facilitate zero-overhead snapshot isolation?
How do you diagnose, mitigate, and eliminate SQLITE_BUSY (database is locked) errors in high-throughput applications?
What is the role of PRAGMA synchronous, and what are the performance and crash-durability trade-offs between FULL, NORMAL, and OFF?
Describe SQLite on-disk B-Tree page layout, distinguishing between Table B-Trees and Index B-Trees, and Interior vs Leaf pages.
Frequently Asked Technical Interview Questions (SQLite)
Essential theoretical concepts, architecture trade-offs, and runtime design questions asked by hiring committees.
Can SQLite handle concurrent reads and writes simultaneously?
Why should every SQLite connection set a busy timeout?
What is the maximum recommended size for an SQLite database?
Pair Interview Prep with Cheat Sheets & Roadmaps
Review syntax formulas on our interactive cheat sheets, test your skills in technical quizzes, and study high-scale system designs.
Want to practice other technologies?
Explore our comprehensive technical interview tracks across all core technology stacks.