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: ATTACH lets one SQLite session query and copy across two files

Sqlite
~/tips/tip-sqlite-attach-two-files

sqlite> ATTACH 'old.db' AS old;

Opens a second SQLite file under a name so you can join or copy between both.

Copying rows from an old SQLite file into a new one doesn’t need an export. One connection can open several files at once and treat them as schemas.

sqlite3 new.db
sqlite> ATTACH 'old.db' AS old;
sqlite> INSERT INTO main.users SELECT * FROM old.users WHERE id NOT IN (SELECT id FROM main.users);
sqlite> DETACH old;

After ATTACH, tables in the second file are reachable as old.tablename, and the file you opened is main. You can join across them, compare them, or create a table from the other side with CREATE TABLE main.users_copy AS SELECT * FROM old.users;. PRAGMA database_list; shows what is attached, with the full paths.

I find this the easiest way to check what changed between a backup and the live file: attach the backup and run an EXCEPT query between the two tables.

Watch the path: a file that does not exist is created as a new empty one, with no error, so a typo gives you queries against nothing. Check with .tables old.*. A transaction across both files is atomic only in rollback journal mode; in WAL mode each file commits on its own, so a crash in the middle can leave one changed and the other not. By default you can attach up to ten files.

Further reading: SQLite ATTACH, SQLite limits

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