SQLite in Practice: Give Your Vibe Project a Database with No Server to Install
Your vibe project has outgrown JSON files when two writes collide and every question means reading the whole file. SQLite is a database with no server: one file, zero third-party packages. This guide builds a reading log end to end with Python's stdlib sqlite3: 8 books, 15 sessions, 675 minutes, 548 pages, an index that turns SCAN into SEARCH, a rollback from 16 rows back to 15, and a 16384-byte backup. Python 3.12.3, SQLite 3.45.1.

Small projects that AI helps you write usually start by storing data in JSON files, and that feels smooth at first: open the file, read it in, change something, write it back. But once the data grows, that road starts breaking: two writes at the same time overwrite each other, answering "which books did I read last week" means reading the whole file and filtering it by hand, and if the program crashes halfway through a write, the file can end up half-written. SQLite takes over that job: it is a database with no server, no installation, and no username or password — the whole database is a single file in your project directory. Python ships a sqlite3 module, zero third-party packages, and this guide works through a fictional "Morning Light Reading" log: 8 books and 15 reading sessions, with every number measured by running the demo script demo246_zh.py. The English rerun script is rerun_en_demo246_g1.py and its numbers match. The demo stores the book titles as Chinese strings, so the transcripts keep them verbatim; this article uses English translations of the titles. The local environment is Python 3.12.3 and SQLite 3.45.1.
One sentence first: SQLite is not a replacement for PostgreSQL, it is a replacement for fopen(). That is the SQLite website's own wording on its "Appropriate Uses" page. If your vibe project serves just you or a handful of people, with the data and the program on the same machine, one writer at a time, and a data size nowhere near the terabyte range, SQLite is almost always the lower-effort choice. It is fast, reliable, needs no configuration and no maintenance, and deleting the database means deleting one file. The other way round, any one of these three means you should pick a client/server database: the data is separated from the application by a network, many concurrent writers cannot queue up and take turns, or the data will grow too big to fit in a single file. The website's rule of thumb is that a site with fewer than 100K hits per day works fine with SQLite — a conservative estimate, not a hard upper bound — and a single SQLite database supports up to 281 terabytes. Those numbers come from the SQLite website, not from this article.
The simplest test for the choice is this: does your data need to leave this machine? If the answer is "no, the data lives on this machine and the program reads it on the same machine", that is SQLite's home ground: personal tools, desktop apps, phone apps, command-line scripts, prototypes. If the answer is "yes, several machines and several people need to read and write the same data at once", go straight to a client/server database such as PostgreSQL. Once that question is settled, the choice is hard to get wrong, and what is left is how to write the code — which is what this guide is about.
Create the database first: one file is one database
Section 1 of the demo does three things: connect to the database file, flip two switches, and create two tables. The line sqlite3.connect("reading.db") creates the database itself: if the file does not exist it is created, if it exists it is opened. The fresh database file is only 4096 bytes, an empty shell — another measured number. The two tables are plain: books holds books, sessions holds each reading session, and the book_id in a session points at a book's id. That is a foreign key, and section 7 verifies it properly.
import sqlite3
con = sqlite3.connect("reading.db")
con.execute("PRAGMA foreign_keys = ON")
con.execute("PRAGMA journal_mode = WAL")
con.execute("""CREATE TABLE books(
id INTEGER PRIMARY KEY, title TEXT NOT NULL,
pages INTEGER NOT NULL, rating REAL)""")
con.execute("""CREATE TABLE sessions(
id INTEGER PRIMARY KEY, book_id INTEGER NOT NULL REFERENCES books(id),
minutes INTEGER NOT NULL, pages_read INTEGER NOT NULL, day TEXT NOT NULL)""")
con.commit()
Two switches deserve their own explanation. The first is PRAGMA foreign_keys = ON: SQLite ships with foreign keys switched off, and without this line the session pointing at a nonexistent book in section 7 would insert just fine and the data would quietly go bad. The second is journal_mode = WAL: write-ahead logging, so reads and writes block each other less — the usual mode for single-machine apps. The demo prints wal back, confirming the switch took effect. Note that PRAGMA foreign_keys is per connection: open a new connection and you have to turn it on again. That is the most common beginner mistake here — you turned it on in one script, then a different connection reads with it off again.
Write with placeholders, never by building strings
Section 2 of the demo inserts 8 books and 15 reading sessions with executemany, commits, and counts again to confirm: 8 rows in books, 15 rows in sessions. There is one rule in the writing: values always go through ? placeholders, never through string building. The Python docs say the same thing: always use placeholders to bind values instead of string formatting, or you are opening the door to SQL injection.
con.executemany("INSERT INTO books VALUES(?, ?, ?, ?)", BOOKS)
con.executemany(
"INSERT INTO sessions(book_id, minutes, pages_read, day) VALUES(?, ?, ?, ?)",
SESSIONS)
con.commit()
Saying "do not build strings" is not vivid enough on its own, so section 4 of the demo tries an attack string directly: inserting x'; DROP TABLE books; -- as a book title. The result is that the string is stored as ordinary text, the books table survives, the row count goes from 8 to 9, and deleting that test row brings it back to 8. The principle in one sentence: a value is always just a value, never part of the SQL statement. Code that AI generates often builds SQL with f-strings; fix it every time you see it, no discussion needed.
Reading the data: three queries cover a small project
Data is stored so it can be read back. Section 3 runs three kinds of queries, and the numbers are: 15 sessions add up to 675 minutes of reading and 548 pages finished; the average rating of the 7 books that have been read is 4.49; the most-read book is Algorithms Illustrated at 225 minutes; and 1 book has no reading sessions yet, Deep Learning Intro. You can check each number against the demo transcript, or add them up yourself: Python Basics 95 minutes, Git in Practice 90, Design Patterns 85, SQL Basics 75, Bash Handbook 60, Regex Cheat Sheet 45 — that sums to 675.
SELECT SUM(minutes) FROM sessions;
SELECT SUM(pages_read) FROM sessions;
SELECT ROUND(AVG(rating), 2) FROM books WHERE rating IS NOT NULL;
SELECT b.title, SUM(s.minutes) AS m FROM books b
JOIN sessions s ON s.book_id = b.id
GROUP BY b.id ORDER BY m DESC LIMIT 1;
SELECT b.title FROM books b
LEFT JOIN sessions s ON s.book_id = b.id WHERE s.id IS NULL;
The last two queries are worth a second look. The fourth joins books to sessions, groups by book, sums the minutes, and takes the top row — that is how you ask "which book did I read the longest". The fifth uses a LEFT JOIN to find "books with no sessions": all the books on the left, sessions on the right, and the rows where the right side matches nothing are the unread books. Many beginners answer "unread books" by fetching all the books and then querying each one for sessions — 8 queries. One LEFT JOIN does it, and that is what a database is for.
The chart above shows the minutes per book, with numbers identical to the demo transcript. The conclusion you can read off at a glance: Algorithms Illustrated alone accounts for 225 minutes, more than twice the runner-up Python Basics at 95, while Deep Learning Intro does not appear at all because it has zero minutes. That is the payoff of putting data in a database: to see a distribution you run one query and draw one chart, instead of opening a JSON file and counting by hand.
Indexes: read the query plan before you build one
With 15 rows you cannot feel the difference an index makes, but the habit should start now: look at the query plan before writing a query. Section 5 asks for "all sessions for book 6". Before the index, the plan has one line: SCAN sessions, meaning the whole table is read from start to finish. After creating the index and running the same query, the plan reads SEARCH sessions USING INDEX idx_sessions_book (book_id=?) — it follows the index straight to those rows instead of scanning the table.
EXPLAIN QUERY PLAN SELECT * FROM sessions WHERE book_id = 6;
-- Before the index: SCAN sessions
CREATE INDEX idx_sessions_book ON sessions(book_id);
-- After the index: SEARCH sessions USING INDEX idx_sessions_book (book_id=?)
Two things not to mix up. First, more indexes are not better: every index takes space, and every write has to maintain it, so indexing a column you never query is pure waste. Second, reading the plan matters more than building the index: many slow queries are not missing an index, they are written badly — computing a function on every row, for example, or wrapping the indexed column in a function in the condition. Build the habit: when a query feels slow, run EXPLAIN QUERY PLAN first, and only think about an index when you see a SCAN.
Transactions: nothing counts until it is committed
Section 6 does one thing: insert a session, do not commit, count 16 rows, then rollback and count 15 again. That is the whole meaning of a transaction: until you commit, every change is only a trial, and rolling back makes it as if it never happened. In a real project the point is "all or nothing": recording one payment might write two tables, and if one write lands and the other does not, the data no longer adds up. The right way is to wrap both steps in one transaction and roll everything back if anything in the middle fails.
con.execute("INSERT INTO sessions(book_id, minutes, pages_read, day) "
"VALUES(1, 10, 8, '2026-11-20')")
con.rollback() # that row never happened; sessions is back to 15 rows
Python's sqlite3 also has a lazier form: use the connection as a context manager, and a with con: block commits automatically when it ends normally and rolls back automatically on an exception. The demo uses explicit commit and rollback so you can see each step; in real projects prefer with con:. One more beginner trap: the program exits and the data is not there — most of the time you forgot commit. The Python docs are explicit: an INSERT implicitly opens a transaction, and it has to be committed before the change is saved to disk.
Foreign keys and backups: too late once the data is already broken
Section 7 first checks the foreign key: inserting a session with book_id = 999, a book that does not exist, is refused outright with FOREIGN KEY constraint failed. That is the payoff for turning PRAGMA foreign_keys = ON in section 1: bad data is stopped at the door instead of surfacing weeks later when the summary numbers stop adding up. One honest note from the demo: after the rejected insert, if you do not rollback first, the failed write still holds an open transaction and the lock, and the backup step that follows hangs. A failed write needs a rollback too — remember that one.
Backups use the backup interface that ships with sqlite3, not a plain file copy. The measured numbers: the database file is 4096 bytes, the backup file is 16384 bytes, and both hold 8 books and 15 sessions — identical. Why not just copy the file? Because a copy taken while a write is in progress can catch a half-finished write; the backup interface makes one consistent copy and is safe even while writing. One more detail: with WAL mode on, the disk holds a .db-wal and a .db-shm file next to the .db file, so copying only the .db file is not enough. Use the backup interface, or copy only after every connection is closed and the WAL has been merged back into the main file.
with sqlite3.connect("reading-backup.db") as bcon:
con.backup(bcon) # backup file 16384 bytes, same row counts as the original
SQLite types are flexible — do not let them fool you
SQLite differs from PostgreSQL and MySQL in one important way: its typing is flexible. Writing INTEGER in a table definition only sets a "type affinity" for the column, not an iron gate. Section 8 runs a small experiment: a table with a single x INTEGER column, into which the string '42', the integer 42, and the string 'abc' are inserted one by one, then typeof(x) is asked what each value really is. The result: '42' comes back as the integer 42, type integer; 42 is integer of course; 'abc' cannot be converted to a number, so it is stored as text, type text. The Python docs say the same thing: thanks to SQLite's flexible typing, specifying data types when creating a table is optional.
con.execute("CREATE TABLE probe(x INTEGER)")
con.execute("INSERT INTO probe VALUES(?)", ("42",)) -- comes back as integer 42
con.execute("INSERT INTO probe VALUES(?)", (42,)) -- comes back as integer 42
con.execute("INSERT INTO probe VALUES(?)", ("abc",)) -- comes back as text 'abc'
SELECT x, typeof(x) FROM probe;
That has two practical consequences for a vibe project. First, do not expect the database to catch every piece of bad data: an age column will happily store 'abc' without complaining, and you only notice when an average comes out strange. So validate in your program anyway — check that pages are integers and ratings sit between 0 and 5 before inserting. Second, data moved over from JSON files is often strings, such as "42", and storing it in an INTEGER column silently turns it into 42. That is convenient, but keep it in mind: you thought you stored a string and you get an integer back, and string concatenation will notice the difference. When in doubt, ask typeof() — it will honestly tell you each value's real type.
The same section has a handy trick: by default every row comes back as a tuple, so you can only fetch by position — row[0] is the title, row[1] is the rating, and with many columns it is easy to grab the wrong one. Set the connection's row_factory to sqlite3.Row and rows can be fetched by column name. The demo reads book 6: row['title'] is Algorithms Illustrated, row['rating'] is 4.9. One extra line of code, much easier to read — worth making a habit.
con.row_factory = sqlite3.Row
row = con.execute("SELECT title, rating FROM books WHERE id = 6").fetchone()
row["title"] # Algorithms Illustrated
row["rating"] # 4.9
Does the database file belong in git?
A database is just a file, so should it go into version control? It depends. The demo's reading.db is only 4096 bytes and the backup file 16384 bytes; files that small are fine in git, and there is a real benefit: whoever clones your project gets a working sample database right away and does not have to run the setup script first. Many vibe projects do exactly this: the repo holds a seed database with a few sample rows so a newcomer can run the project immediately.
But data that real users actually produce should not go into git. Your reading log is yours, someone else's is theirs, and the data keeps changing; every commit would carry a changed binary file, the repo would bloat quickly, and a merge conflict in a binary file cannot be resolved the way a text conflict can. The right way: keep the table-creation and sample-data script in the repo, put the real database file in .gitignore, and let everyone generate their own database by running the script once on their machine. One more detail: with WAL mode on, the disk also holds .db-wal and .db-shm files next to the .db file. Those are runtime state and should never go into version control either — ignore them together. By the way, the SQLite website lists "application file format" as an appropriate use: many desktop apps use a SQLite file as their save format, opening the file means opening the database, edits save automatically, and the "Save" menu can even go away. If your vibe project is a small desktop tool, that path is worth serious thought.
Three scenarios you can copy directly
That covers the reasoning; here are the three most common scenarios in vibe projects, ready to adapt. The first is the demo itself, a reading log: books, minutes, pages, ratings — four queries cover everything a habit-tracking app needs, add a date filter and you have a working prototype. The second is an AI conversation archive: every model call writes its question, answer, token count and time into a table, and a week later "which topic ate the most tokens this week" is one GROUP BY away — faster than scrolling through chat history and cheaper than calling the API again. The third is a collector's deduplication cache: a crawler or news collector asks the database SELECT COUNT(*) FROM seen WHERE url = ? for each link, skips the ones it has seen, and only fetches new ones. One table with a unique index solves duplicate fetching, and the records survive a restart, unlike a set kept in memory.
What the three share is this: the data is small, there is one writer, and the ways you want to query it keep growing. At first you only want to filter by date, then by book title, then sort by rating, then total the minutes per month. With JSON files every new way of asking means another block of filtering code; with SQLite it means one more SQL statement. Data gets more alive the more you use it — that is the real advantage of a database over files: not that it can store the data, but that you can ask it questions.
Closing checklist and boundaries
Here is the whole guide as a checklist for the next time you add a database to a vibe project: the database is one file in the project directory, no server to install; write the foreign-key relationships into the table definitions and turn PRAGMA foreign_keys = ON on every connection; always pass values through ? placeholders, never build strings; decide what question you want to ask before writing the SQL, do not read the whole table and filter by hand; when a query feels slow, run EXPLAIN QUERY PLAN first and only think about an index when you see a SCAN; wrap grouped operations in a transaction and roll back on error; back up with the backup interface, never copy a file that is being written; and when you are unsure what type a value is, ask typeof() instead of guessing.
Finally, what this guide does not cover, so you do not take SQLite into a fight it should not be in: it does not cover migrating from SQLite to PostgreSQL — that deserves its own guide; it does not cover ORMs such as SQLAlchemy — get comfortable writing SQL itself first; and it does not teach the SQL language systematically, window functions and complex queries included — the site already has a SQL basics guide, while this one is about embedding SQLite in a vibe project so it remembers things for you. One last reminder on the choice: one writer at a time, data and program on the same machine — SQLite is the answer. Many users writing at high concurrency from the start — go straight to a client/server database and do not force SQLite to carry that load.
Comments (0)
Sources
Related articles
Five books in stock, 150930 cents in total, 35 copies; stock.json is 372 bytes, Promise.all reads 3 files into A+B+C, and the small service answers 200, 200, 404. Node v24.22.1 stdlib only, measured.
Adding a book parses to price=59.9, count=3, total 179.7; listing by price takes 2; four errors all exit with code 2; --pri abbreviates, and no subcommand parses to None. Python 3.12.3 stdlib, measured.
Building stock of 2000 books moves current memory from 0.3 KiB to 582.7 KiB; subtracting two snapshots, the biggest line is line 85 at 568.1 KiB and 9699 blocks; getsizeof sees only 15.8 KiB, and clearing brings the line back to 0.0 KiB. Python 3.12.3 stdlib, measured.