SQLite is famously robust: its transactions survive crashes and power cuts, and corruption is rare. Rare is not never, though, and when it happens the message is blunt — database disk image is malformed. The good news is that a corrupted SQLite file is very often partly or almost entirely recoverable, as long as you do not make it worse in the first five minutes. This guide walks through a calm, ordered approach: protect the evidence, diagnose, repair from the least to the most invasive method, verify, and prevent a repeat.

Step 0: stop and make a copy

Before you run a single repair command:

  1. Close every program using the database, so nothing writes to it while you work.
  2. Copy the database together with its companion files — -wal and -shm (WAL mode) or -journal (rollback mode) if they exist. A -wal file can hold committed transactions not yet written to the main file, and a hot -journal holds what SQLite needs to roll back an interrupted write. Deleting either can turn a healthy database into a corrupt one, or a minor problem into a major one.
  3. Work only on the copy. Keep the original untouched so you can start again if a step goes wrong.

Recognising the problem

Not every scary error is corruption. Match the message before you reach for repair tools:

Error What it usually means
database disk image is malformed Real structural corruption (SQLITE_CORRUPT)
file is not a database The header is unreadable: badly damaged, not SQLite at all, or an encrypted database opened without the right key
database is locked Another connection holds a lock — not corruption
database or disk is full Out of disk space or a size limit; free space and retry
row N missing from index (from integrity_check) Index-only damage — usually the easiest fix

That second row matters: if the file came from an app that might use SQLCipher, try opening it with SQLCipher and the key before assuming the worst.

Step 1: diagnose with integrity_check

PRAGMA integrity_check walks the entire file — every page, every b-tree, every index entry — and reports what is inconsistent. It returns a single row saying ok if the database is healthy.

PRAGMA integrity_check;        -- full check; up to 100 problems by default
PRAGMA integrity_check(1000);  -- report up to 1000 problems
PRAGMA quick_check;            -- faster, skips index-vs-table cross checks
PRAGMA foreign_key_check;      -- logical: rows pointing at missing parents

Read the output carefully. If every message mentions an index (“row 1234 missing from index idx_orders_date”, “wrong # of entries in index”), the table data is probably fine and only the indexes are damaged. Messages about pages, freelists or b-tree structure (“Page 52 is never used”, “invalid page number”, “2nd reference to page”) point to deeper damage. Note that foreign_key_check finds data problems, not file corruption — useful afterwards, not as a diagnosis.

🔧 BackendSide Tool

SQLiteDesk — Integrity Check and Maintenance from a Menu

No shell required for the first diagnosis. SQLiteDesk runs an integrity check, shows database stats, and runs VACUUM, ANALYZE and REINDEX straight from its Maintenance menu. When the check points at a damaged index, REINDEX is one click away.

Explore SQLiteDesk →

Step 2: the repair ladder

Work up from the gentlest method, re-running integrity_check after each one. Stop as soon as you get a clean result.

Rung 1: REINDEX (index-only damage)

If only indexes are affected, rebuilding them from the table data fixes it completely:

REINDEX;                       -- rebuild every index
REINDEX idx_orders_date;       -- or just the damaged one
PRAGMA integrity_check;

Rung 2: rebuild into a new file

If the tables can still be read, copying everything into a fresh file leaves the damaged structure behind. VACUUM INTO does it in one statement (SQLite 3.27+):

VACUUM INTO 'C:/recovery/rebuilt.db';

A plain-text dump is the more forgiving alternative, because you can inspect and edit it. With the sqlite3 command-line shell:

sqlite3 damaged.db ".output dump.sql" ".dump"
sqlite3 rebuilt.db ".read dump.sql"

If .dump hits errors along the way, it ends the script with ROLLBACK; -- due to errors instead of COMMIT;. Change that last line to COMMIT; before loading, or the reload will discard everything it just inserted.

🔧 BackendSide Tool

SQLiteDesk — Dump to .sql and Rebuild

If the database is still readable, a dump-and-reload is often all it takes. SQLiteDesk can dump an entire database to .sql, create a fresh database, and run that .sql script into it. Dumps replay cleanly with generated columns, full-text search and AUTOINCREMENT counters. You can also export individual tables to CSV, JSON or SQL INSERT to rescue the data that matters most first.

Explore SQLiteDesk →

Rung 3: .recover (deep damage)

When VACUUM INTO and .dump fail partway, the sqlite3 shell’s .recover command (version 3.29 and later) is the strongest tool available. Instead of reading the database through its normal, now-broken structure, it scans the pages directly and salvages every row it can find:

sqlite3 damaged.db ".output recovered.sql" ".recover"
sqlite3 recovered.db ".read recovered.sql"

-- useful options:
--   .recover --ignore-freelist        skip pages on the freelist (fewer old deleted rows)
--   .recover --lost-and-found orphans name the table for unplaceable rows

Rows that .recover finds but cannot tie back to a known table are placed in a lost_and_found table, with columns describing where they came from and their values in c0, c1 and so on. Look there before declaring data lost. Be aware that recovery can also resurrect rows that were deleted but whose pages were not yet overwritten — check the results rather than trusting them blindly.

For a SQLCipher database, run the recovery with SQLCipher’s own shell and supply the key first; a stock sqlite3 cannot read the encrypted pages.

Rung 4: restore from backup

If recovery leaves too many gaps, the remaining option is the last good backup — possibly combined with whatever newer rows .recover salvaged.

Step 3: verify the result

A repaired file is not finished until you have checked it:

PRAGMA integrity_check;        -- must return 'ok'
PRAGMA foreign_key_check;      -- orphaned child rows after partial recovery
SELECT count(*) FROM orders;   -- compare key tables against what you expect
SELECT count(*) FROM lost_and_found;  -- if .recover created it

Also check settings that a rebuild may not carry over, such as PRAGMA user_version (many apps use it to track schema migrations) and PRAGMA journal_mode, and set them on the new file if needed. Only then swap the repaired file in place of the original.

Why it happened, and how to stop it happening again

SQLite’s own documentation lists the realistic causes, and nearly all of them are environmental:

Cause Prevention
Copying the file while a transaction was in progress Use the online backup API, .backup or VACUUM INTO
Deleting or separating the -wal / -journal file Always move and back up the companion files together
Database on a network share used by several machines Keep SQLite files on local disks; use a server database for shared access
Power loss with synchronous = OFF or a drive that ignores sync requests Use synchronous = FULL (or NORMAL in WAL mode) and reliable storage
USB drive removed during a write Close the app before unplugging
Failing disk or memory Run hardware checks if corruption recurs

Add a scheduled PRAGMA quick_check to your app or maintenance routine, keep regular online backups on a different drive, and test a restore now and then. Corruption you catch early, with a recent backup at hand, is a minor inconvenience instead of a disaster.

🔧 BackendSide Tool

SQLiteDesk — The Backup You Will Be Glad You Made

The best repair is a restore. SQLiteDesk makes an online backup that is safe on a live database while writes are happening, and restores from a backup file when you need it — for encrypted databases too, with the option to re-encrypt. Backups keep the database’s user_version, application_id and journal mode. Available on the Microsoft Store with a free trial.

Explore SQLiteDesk →

Key takeaways

  • First close everything and copy the database with its -wal, -shm or -journal files; never delete them.
  • “File is not a database” may just mean an encrypted database without its key.
  • Diagnose with PRAGMA integrity_check; index-only errors are fixed by REINDEX.
  • For deeper damage, rebuild with VACUUM INTO or .dump (fix a trailing ROLLBACK), then escalate to .recover and check lost_and_found.
  • Verify with integrity_check, foreign_key_check and row counts, and restore user_version if needed.
  • Prevent repeats with online backups, local disks, sane synchronous settings and regular checks; SQLiteDesk puts the backups, integrity checks and REINDEX in one Windows app.