brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: PRAGMA user_version gives a SQLite file a built-in schema version number

Sqlite
~/tips/tip-database-sqlite-pragma-user-version

sqlite3 app.db "PRAGMA user_version = 3;"

Reads or sets a free integer in the SQLite file header, handy for tracking the schema version.

Apps that keep a SQLite file around for years need to know which version of the schema that file has. Many people add a one-row table for that. SQLite already has a spare number in the file header that you can use for the same job.

sqlite3 app.db "PRAGMA user_version;"
sqlite3 app.db "PRAGMA user_version = 3;"

The docs describe user_version as an integer stored at offset 60 in the database header, which applications can use however they like. SQLite itself makes no use of it. The first command reads it, the second sets it.

The pattern for a migration is then simple: on start-up the app reads the number, runs the steps for every version above it, and sets the new number at the end.

PRAGMA user_version;          -- 2
-- run the migration for version 3 here
PRAGMA user_version = 3;

It is the plain way to answer "which schema is this file on?" from the command line as well, without opening the app. The docs also point to two neighbouring pragmas, application_id and schema_version.

The caveat is that nothing checks the number for you. If two tools use the same file and both set user_version for their own purposes, they overwrite each other. Also, the value is an integer only, so there is no room for a name like "v1.2". If you need more, use a normal table.

Further reading: SQLite: PRAGMA Statements (user_version)

More Sqlite tips SELECT unixepoch('2026-01-01 00:00:00'); SELECT name, iif(qty > 0, 'in stock', 'sold out') AS state sqlite3 -bail app.db < migrate.sql CREATE INDEX 'orders_user_id' ON 'orders'('user_id'); –> users(id) CREATE INDEX users_active_email ON users(email) WHERE active = 1; All Sqlite tips (27) All topics

Link