DEV Community

Cover image for Why SQLite Is Everywhere: The Database That Is Just a File
Abdeldjalil Chougui
Abdeldjalil Chougui

Posted on Originally published at abdeldjalilchougui.biz

Why SQLite Is Everywhere: The Database That Is Just a File

There is a good chance that the device you are reading this on holds dozens of SQLite databases. Android and iOS ship it. Browsers use it to store history and bookmarks. Desktop apps, messaging apps and many command-line tools keep their data in it. Python includes it in the standard library. It is widely described by its authors as the most deployed database engine in the world, and it is easy to see why once you understand what it is and what it is not.

The problem SQLite solves

Most databases are servers. PostgreSQL and MySQL run as separate processes, you connect to them over a socket, you create users, set passwords, manage ports and keep the service running. That makes sense for a shared backend with many clients.

But a lot of software just needs to store structured data for itself. A mobile app with a local cache, a desktop editor with its settings and recent files, a test suite, a small website, a data-processing script. For these, running a database server is overhead. The usual alternative was writing your own file format: JSON, CSV or a custom binary layout, and then handling partial writes, crashes, concurrent access and queries by hand.

SQLite gives you a real SQL database with transactions, without any of the server work.

How it works

SQLite is a C library that you link into your program. There is no separate process. When your code runs a query, the library reads and writes a single ordinary file on disk.

  1. Open the file. sqlite3_open("app.db") (or sqlite3.connect("app.db") in Python) opens or creates the database. The whole database, tables, indexes and schema, lives in that one file.
  2. Compile the SQL. The library parses your SQL and compiles it into bytecode for its internal virtual machine.
  3. Run it. The virtual machine walks B-trees stored in fixed-size pages inside the file. Each table and each index is a B-tree.
  4. Commit safely. Changes are written through a journal, so a crash or power loss in the middle of a transaction leaves the database in its previous state.

A complete example in Python, no install needed:

import sqlite3

db = sqlite3.connect("notes.db")
db.execute("CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, body TEXT NOT NULL)")
with db:  # one transaction: commit on success, rollback on error
    db.execute("INSERT INTO notes (body) VALUES (?)", ("buy milk",))
for row in db.execute("SELECT id, body FROM notes"):
    print(row)
Enter fullscreen mode Exit fullscreen mode

That is the whole setup. Copy notes.db to another machine and it works there too: the file format is cross-platform and stable, and the SQLite project has committed to supporting it long term.

Why it spread so far

  • Zero configuration. No server, no users, no ports. It works the moment you open a file.
  • Small and self-contained. The library is compact, has very few dependencies, and is distributed as a single C file (the "amalgamation"), which makes it easy to embed in any project or language.
  • Reliable. It is full ACID: transactions are atomic and durable even across crashes. The project is known for very extensive automated testing.
  • Public domain. There is no license to negotiate, so any company can ship it in any product.
  • Fast for local work. Reading from a local file inside your own process avoids network round trips. For many small queries this is faster than talking to a server.
  • A good file format. Because one file holds everything, SQLite is often used as an application file format, and as a way to move datasets around.

Journal modes and WAL

By default SQLite uses a rollback journal: before changing pages, it copies the original pages to a side file, so it can restore them if something goes wrong.

Many applications switch to WAL mode:

PRAGMA journal_mode = WAL;
Enter fullscreen mode Exit fullscreen mode

In WAL mode, changes are appended to a separate write-ahead log file and merged into the main database later at a checkpoint. The practical gain is concurrency: readers keep reading the last committed state while a writer is writing, so reads and writes no longer block each other.

The limits you need to know

SQLite is not a smaller PostgreSQL. It made different trade-offs, and they matter.

  • One writer at a time. Many connections can read at once, but writes are serialized for the whole database. With short transactions this is fine for a lot of workloads. With many concurrent writers, you will see database is locked errors. Set a busy timeout so connections wait instead of failing immediately, and keep write transactions short.
  • Local only. The database is a file accessed by processes on the same machine. Putting it on a network file system is risky because file locking there is often unreliable. If several application servers must write to the same data, use a client-server database.
  • Flexible typing. By default a column's declared type is a preference, not a rule: SQLite will store a string in an INTEGER column if it cannot convert it. Newer versions support STRICT tables if you want enforced types.
  • Foreign keys off by default. Foreign key constraints are only enforced after PRAGMA foreign_keys = ON; on each connection. This surprises many people.
  • Fewer server features. No user accounts or permissions inside the database, no built-in replication. Access control is the file's permissions.

Where SQLite fits on servers

SQLite on the server used to be dismissed, but it is a sound choice in some cases: read-heavy websites on a single machine, internal tools, prototypes, per-tenant or per-user databases, caches, and test suites that want a fast real SQL engine. Tools exist that stream SQLite changes to object storage for backups and replicas, which removes some of the old concerns.

It is a poor fit when you need many processes on different machines writing at the same time, heavy concurrent writes, or fine-grained database permissions.

Common mistakes

  • Forgetting PRAGMA foreign_keys = ON and assuming constraints are checked.
  • Long write transactions that hold the lock while the app does slow work.
  • No busy timeout, so a brief lock turns into an error.
  • Copying the database file while it is being written instead of using the backup API or VACUUM INTO.
  • Storing the file on a network share.

In short

SQLite is a library, not a server: a full ACID SQL engine that reads and writes one file. That design, plus its small size, stability and public domain status, is why it is inside phones, browsers and countless apps. Use it whenever your data lives with one application on one machine. Reach for a client-server database when many machines must write to the same data.

Watch the animated version: https://youtu.be/qh_vFKxYV7w


Originally published at abdeldjalilchougui.biz.

Top comments (0)