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: VACUUM INTO writes a compact copy of a SQLite database and leaves the original alone

Database
~/tips/tip-database-sqlite-vacuum-into-copy

sqlite3 app.db "VACUUM INTO '/backups/app-compact.db'"

Writes a compact, consistent copy of a SQLite database to a new file.

VACUUM normally rewrites the database file in place. VACUUM INTO writes a fresh, tidy copy somewhere else, and I find that a more relaxed way to shrink a file.

The syntax is short:

sqlite3 app.db "VACUUM INTO '/backups/app-compact.db'"

Per the docs, the original file stays unchanged and a new database is created with the same logical content, minus the deleted content. The command is not a write operation on the source, so it does not need the write lock that a plain VACUUM does. The copy is a consistent snapshot.

Caveats from the docs, and they matter:

  • The target file must not exist yet. An existing empty file is fine, anything else gives an error.
  • If power is lost or the process dies during the operation, the output file may be incomplete and corrupt, so do not trust a copy until the command has finished.
  • If the source uses synchronous NORMAL or FULL, SQLite syncs the output to disk once it is written.

Disk space is the other thing to watch. The docs say a plain VACUUM can need up to roughly twice the size of the database in free space, and VACUUM INTO has the same needs without the copy-back step.

I would not use it as my only backup, but it is handy for a smaller copy of an app database. Open the copy with PRAGMA integrity_check; before you swap anything.

Further reading: VACUUM (SQLite documentation)

More Database tips mariadb -e 'CREATE DATABASE IF NOT EXISTS blog' mariadb-dump --no-create-info --insert-ignore shop orders > orders-rows.sql SELECT table_schema, table_name, CHECKSUM TABLE shop.orders; services: All Database tips (53) All topics

Link