SQLite interview questions and answers for app and backend developers
SQLite interview questions check whether you understand an embedded database: a library linked into your app that reads and writes one ordinary file, with no server, flexible column types, and only one writer at a time. Expect questions on type affinity, transactions and locking, WAL mode, indexes and EXPLAIN QUERY PLAN, schema migrations on a phone or desktop app, and when a client-server database such as PostgreSQL fits better.
By Evin JohnPublished 9 min read
Where SQLite questions come up
SQLite shows up in more interviews than people expect, because it sits inside so much software. Android and iOS developers meet it under Room and Core Data. Desktop and Electron developers use it for local caches and settings. Embedded and IoT engineers pick it for devices with no administrator. Backend teams use it in tests, in small services, and more and more in production for read-heavy sites with a single server. The questions change with the job: mobile interviews lean on migrations and threading, backend ones on concurrency and durability, and data roles on SQL features such as window functions and JSON. For general query writing, see SQL interview questions.
- Concept screenWhat makes SQLite different from MySQL or PostgreSQL, how types work, and what the database file actually contains.
- Hands-on SQLWrite a query against a small schema, often in the sqlite3 shell or a notebook, then improve it with an index.
- Platform roundFor mobile and desktop: schema versions, migrations, background threads and what happens when two parts of the app write at once.
- Design discussionWould you use SQLite for this product? Defend the choice with write volume, number of servers and backup plans.
Fundamentals: the engine and its file
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What does serverless mean for SQLite? | Architecture | The engine runs inside your process as a library. There is no daemon, no port and no login; the app opens a file path and calls functions directly. |
| What is stored in a SQLite database file? | File format | Tables, indexes, the schema and metadata, all in one cross-platform file made of fixed-size pages, organized as B-trees. |
| What are the storage classes? | Type system | NULL, INTEGER, REAL, TEXT and BLOB. A value has a storage class; a column only has a preferred type called its affinity. |
| What is type affinity? | Flexible typing | The column's declared type nudges stored values toward a class. Text that looks like a number becomes an INTEGER in an INTEGER column, but text that does not stays text. |
| What is special about INTEGER PRIMARY KEY? | Rowid | It becomes an alias for the table's rowid, so lookups by that key are the fastest path in the table. Other spellings such as INT PRIMARY KEY do not get this behavior. |
| What does AUTOINCREMENT add? | Key generation | It stops SQLite from reusing the IDs of deleted rows at the top of the range, at a small cost of an extra internal table. Most tables do not need it. |
| How do you store dates? | No date type | As ISO-8601 text, a Unix time integer or a Julian day number, then use the built-in date and time functions. Pick one format per column and stick to it. |
| Are foreign keys enforced by default? | Common gotcha | No. Enforcement is off unless each connection runs PRAGMA foreign_keys = ON, which is a frequent source of orphaned rows. |
| What is an in-memory database? | Testing | Opening :memory: gives a private database that disappears when the connection closes, which makes it popular for fast unit tests. |
| How do you inspect a schema in the shell? | Tooling | .tables and .schema in the sqlite3 shell, or a query on the sqlite_schema table, which older code calls sqlite_master. |
CREATE TABLE loose (qty INTEGER, note TEXT);
INSERT INTO loose VALUES ('42', 42), ('forty-two', 3.5);
SELECT qty, typeof(qty), note, typeof(note) FROM loose;
-- 42|integer|42|text
-- forty-two|text|3.5|text
CREATE TABLE tight (qty INTEGER, note TEXT) STRICT;
INSERT INTO tight VALUES ('42', 'ok'); -- converted to integer 42
INSERT INTO tight VALUES ('forty-two', 'no'); -- errorInterviewers like this example because it exposes whether you have actually used SQLite or only assumed it behaves like other engines. The flexible behavior is by design, and STRICT tables arrived in later releases (3.37, per the SQLite release notes) for teams that want type errors instead of silent storage. If you work with an older library bundled in a phone OS, check the version before relying on it.
Intermediate: transactions, locking and WAL
- How does SQLite handle concurrent writes? It allows one writer at a time for the whole database file. Other writers wait or get SQLITE_BUSY. Reads can run in parallel. The design trades write concurrency for simplicity and safety.
- What is the difference between the rollback journal and WAL? In the default rollback mode, SQLite copies original pages to a journal before changing the main file. In write-ahead logging, changes are appended to a separate WAL file and copied back later during a checkpoint, so readers see a consistent snapshot while a writer works.
- Why is WAL often faster for apps? Writers do not block readers and readers do not block the writer, and appends are mostly sequential I/O. The costs are an extra WAL file and shared-memory index beside the database, and it should not be used on network file systems.
- What is a checkpoint? The step that moves committed pages from the WAL into the main database file. It runs automatically when the WAL passes a size threshold; long-running readers can hold it back and let the WAL grow.
- What do BEGIN DEFERRED, IMMEDIATE and EXCLUSIVE change? When locks are taken. Deferred waits until the first read or write. Immediate takes the write lock at the start, which avoids a deadlock where two readers both try to upgrade to writers later.
- Your app logs "database is locked". What do you check first? Whether a busy timeout is set, whether some code holds a transaction open too long (a cursor not finished, a network call inside a transaction), and whether several connections write when one shared writer would be simpler.
- What does `PRAGMA synchronous` control? How often SQLite waits for data to reach disk. In WAL mode, NORMAL is a common choice: the database stays consistent after a power cut, but the last few commits might be lost. FULL trades speed for that last bit of durability.
- Why are batch inserts slow without an explicit transaction? Every statement outside a transaction is its own transaction with its own sync to disk. Wrapping thousands of inserts in one BEGIN and COMMIT is often many times faster.
PRAGMA journal_mode = WAL; -- persists in the file
PRAGMA foreign_keys; -- 0: off unless this connection turns it on
PRAGMA busy_timeout = 5000; -- wait up to 5 seconds for a lockimport sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT UNIQUE)")
rows = [("a@example.com",), ("b@example.com",), ("a@example.com",)]
try:
with con: # commits on success, rolls back on error
con.executemany("INSERT INTO users (email) VALUES (?)", rows)
except sqlite3.IntegrityError as err:
print("rolled back:", err)
print(con.execute("SELECT count(*) FROM users").fetchone()[0])Intermediate: indexes and query plans
| Question | What it tests | What a strong answer shows |
|---|---|---|
| How do you see whether a query uses an index? | Plans | EXPLAIN QUERY PLAN before the statement. SEARCH means an index narrows the rows; SCAN means it reads the whole table or a whole index. |
| Why might a composite index not be used? | Column order | The leftmost column must be constrained. An index on (customer_id, created_at) helps a filter on customer_id, not a filter on created_at alone. |
| What is a covering index? | Avoiding lookups | An index that holds every column the query needs, so SQLite never visits the table rows. The plan says USING COVERING INDEX. |
| When does SQLite build a temporary B-tree? | Sorting | When ORDER BY or GROUP BY cannot follow an index order, so it sorts in a temporary structure. A matching index removes that step. |
| What does ANALYZE do? | Statistics | Collects statistics into internal tables so the planner can choose between indexes better. PRAGMA optimize is a lighter way to keep them fresh, often run before closing a connection. |
| What are partial and expression indexes? | Index features | A partial index covers only rows matching a WHERE clause; an expression index stores a computed value such as lower(email) so filters on that expression can use it. |
| The file stays large after deleting most rows. Why? | Free pages | Deleted pages go on a free list for reuse. VACUUM rebuilds the file to shrink it, and needs temporary space roughly the size of the database. |
CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER,
created_at TEXT, total REAL);
CREATE INDEX idx_orders_customer_created ON orders (customer_id, created_at);
EXPLAIN QUERY PLAN
SELECT id, total FROM orders
WHERE customer_id = 7 ORDER BY created_at DESC LIMIT 10;
-- SEARCH orders USING INDEX idx_orders_customer_created (customer_id=?)
EXPLAIN QUERY PLAN
SELECT id, total FROM orders WHERE created_at > '2026-01-01';
-- SCAN ordersNotice that the first plan has no temporary B-tree for the ORDER BY: the index already stores rows in created_at order within each customer, so SQLite walks it backwards. Saying that out loud is the kind of detail that separates someone who reads plans from someone who adds indexes and hopes.
Modern SQL features in SQLite
- How do you write an upsert?
INSERT ... ON CONFLICT (key) DO UPDATE SET ..., using theexcludedalias for the incoming values. It needs a unique constraint or primary key to conflict on. - What does RETURNING give you? The rows an INSERT, UPDATE or DELETE touched, in the same statement, which saves a second query to fetch a new ID or updated total.
- Does SQLite support window functions and CTEs? Yes, including recursive CTEs for trees and series, and window functions such as
row_number()and running sums, in any reasonably recent build. - How do you query JSON stored in a column? With the built-in JSON functions such as
json_extract, or the->and->>operators in newer builds. For heavy filtering, add an expression index on the extracted value. - What is FTS5? A full-text search extension that builds an inverted index in virtual tables, with ranking and phrase queries. Many builds include it, but check, because it is a compile-time option.
- What does ATTACH do? Opens a second database file on the same connection under a schema name, so one query can join or copy across files, which is handy for archiving old rows.
CREATE TABLE stock (sku TEXT PRIMARY KEY, qty INTEGER NOT NULL);
INSERT INTO stock VALUES ('A1', 5);
INSERT INTO stock (sku, qty) VALUES ('A1', 3), ('B2', 7)
ON CONFLICT (sku) DO UPDATE SET qty = qty + excluded.qty
RETURNING sku, qty;CREATE TABLE events (id INTEGER PRIMARY KEY, body TEXT);
INSERT INTO events (body) VALUES
('{"user":"ana","type":"login","ms":120}'),
('{"user":"ana","type":"search","ms":340}'),
('{"user":"raj","type":"login","ms":95}');
SELECT body ->> '$.user' AS user, count(*) AS n, avg(body ->> '$.ms') AS avg_ms
FROM events GROUP BY user ORDER BY user;Senior and scenario questions
| Scenario | What it tests | What a strong answer shows |
|---|---|---|
| Version 2 of your mobile app must change a column's type. How do you migrate? | Schema changes | ALTER TABLE can rename, add and drop columns but not change a type, so create a new table, copy the data, drop the old one and rename, inside one transaction, with foreign keys checked afterwards. Track the schema version with PRAGMA user_version. |
| Would you run a production web app on SQLite? | Fit | It can work well for one server with mostly reads and moderate writes, using WAL and short transactions. It fits poorly with many app servers writing to one database, or heavy concurrent writes; then use a client-server engine such as PostgreSQL. |
| How do you back up a live SQLite database? | Operations | Not by copying the file mid-write. Use the online backup API, the shell's .backup command or VACUUM INTO to write a consistent copy, then test a restore. |
| Two threads in the app share one connection and crash occasionally. What do you change? | Threading | Give each thread its own connection, or route all writes through a single writer queue. Know which threading mode your build or wrapper uses rather than guessing. |
| Users report a corrupted database after the app was force-closed. What could cause it? | Durability | Usually something outside SQLite's assumptions: the file copied or edited while open, journal or WAL files deleted, a filesystem that lies about syncing, or two copies of the library in one process. Run PRAGMA integrity_check and keep backups. |
| Queries that took 5 ms now take 2 seconds after months of use. Where do you look? | Diagnosis | Plans with EXPLAIN QUERY PLAN, missing or stale statistics, a WAL that never checkpoints because a reader stays open, and tables that outgrew a design meant for hundreds of rows. |
| How would you encrypt a SQLite database on a device? | Security | The public-domain core does not encrypt files. Options include a commercial or third-party encryption extension, OS-level file encryption and keeping secrets out of the database, with the key in the platform keystore. |
Fictional example
- We built a field-inspection app for tablets that had to work for whole shifts without signal. I chose SQLite because it runs inside the app, needs no setup on the device, and gives us real transactions, so a half-saved inspection never shows up. We turned on WAL so the UI could read while a background sync wrote, set a busy timeout, and sent all writes through one queue to avoid lock errors. Each release bumps
user_versionand runs a tested migration. The trade-off I named to the team was that the server side would not be SQLite: many devices syncing into one store needed PostgreSQL, so SQLite was the local cache and outbox, not the system of record.
A one-week practice plan
- Day 1: the shellInstall nothing beyond the sqlite3 shell, create a schema, and use
.schema,.modeandtypeof()until the type rules feel natural. - Day 2: plansLoad a few hundred thousand generated rows, write five queries, read each plan, and add or reorder indexes until SCAN turns into SEARCH where it should.
- Day 3: concurrencyOpen two shells on one file, start a write transaction in one, and watch what the other can do in rollback and WAL modes.
- Day 4: migrationsChange a column's type with the copy-and-rename pattern and write down every step, including foreign key checks.
- Day 5: your platformReview how your stack wraps SQLite (Room, Core Data, an ORM, or a driver) and how it handles threads and transactions.
- Day 6 and 7: say it aloudAnswer the scenario table out loud with a timer, then compare SQLite with MySQL and PostgreSQL in two minutes each.
Engine questions reward precise words, such as reserved lock, checkpoint or affinity, and you only notice vague phrasing when you hear it back. Natively, an AI interview assistant for Mac and Windows, can transcribe a mock SQLite round on your computer and keep the transcript and notes so you can find where an answer drifted. While you practice, it can read a schema or a query plan from a screenshot and suggest how to explain it, and with Pro or the free trial it can shape suggestions around the résumé and job description you add.
Questions people ask
What SQLite questions are asked in interviews?
How an embedded, serverless database works, storage classes and type affinity, INTEGER PRIMARY KEY and rowid, transactions and locking, WAL mode, EXPLAIN QUERY PLAN and indexes, migrations, and when SQLite is the wrong choice.
Why does SQLite say the database is locked?
Another connection holds the write lock or a long transaction is still open. Set a busy timeout, keep transactions short, consider WAL mode, and send writes through a single connection or queue.
Is SQLite good enough for production?
For embedded, mobile, desktop and single-server apps with modest write volume, often yes. For many servers writing to one database or heavy concurrent writes, a client-server database fits better.
How is SQLite different from MySQL or PostgreSQL?
It is a library inside your process that writes one file, with no server, users or network protocol, flexible column typing by default, and one writer at a time.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
