101

I am working with sqlite3 file.

First, I entered relatively big database, file size was about 100 mb.

Than I made

$db->exec("DELETE FROM table");

and entered just a small part of that database. But file size remained 100 mb.

What should you do to change sqlite file size when deleting it's content?

3 Answers 3

157

The command you are looking for is vacuum. There is also a pragma to turn auto-vacuuming on.

From the documentation:

When an object (table, index, trigger, or view) is dropped from the database, it leaves behind empty space. This empty space will be reused the next time new information is added to the database. But in the meantime, the database file might be larger than strictly necessary. Also, frequent inserts, updates, and deletes can cause the information in the database to become fragmented - scrattered out all across the database file rather than clustered together in one place.

The VACUUM command cleans the main database by copying its contents to a temporary database file and reloading the original database file from the copy. This eliminates free pages, aligns table data to be contiguous, and otherwise cleans up the database file structure.

3
  • 4
    is there a way to restore the not-yet-overriden deleted table rows?
    – phil294
    Commented May 23, 2016 at 12:01
  • 4
    VACUUMing a database required twice the size of the original database file in internal/external memory. Read SQLite Query Language: VACUUM to know more. Commented May 1, 2019 at 18:53
  • @phil294 your best bet is to load the .db file into a text editor and look for what you want. There's a whole book on the forensic analysis of sqlite databases if you really want to delve into the weeds here. Commented Jul 14, 2022 at 18:30
68

You can do this

$db->exec("DELETE FROM table");
$db->exec("vacuum");

and the file size will be changed.

-2

Cleaning Databases SQLite has two commands designed for cleaning—reindex and vacuum.

reindex is used to rebuild indexes. It has two forms:

reindex collation_name;
reindex table_name|index_name;

vacuum has the form:

VACUUM;

Not the answer you're looking for? Browse other questions tagged or ask your own question.