Small. Fast. Reliable.
Choose any three.

SQLite里的SQL
SQL As Understood By SQLite

[Top]

VACUUM

vacuum-stmt:

syntax diagram vacuum-stmt

VACUUM命令会重建整个数据库。当遇到如下情况时应用可以考虑使用该命令:
The VACUUM command rebuilds the entire database. There are several reasons an application might do this:

VACUUM只能在主数据库上使用,不能在附加库上使用VACUUM。
VACUUM only works on the main database. It is not possible to VACUUM an attached database file.

VACUUM命令首先将数据库的内容复制到一个临时数据库文件中,然后再使用临时文件覆盖原有数据库。当覆盖原始库的时候,对回滚日志或write-ahead logWAL文件的使用就像是在其它数据库事务中一样。也就是说,数据库在执行VACUUM时,大约需要原始数据库文件两倍大小的空闲磁盘空间。
The VACUUM command works by copying the contents of the database into a temporary database file and then overwriting the original with the contents of the temporary file. When overwriting the original, a rollback journal or write-ahead log WAL file is used just as it would be for any other database transaction. This means that when VACUUMing a database, as much as twice the size of the original database file is required in free disk space.

VACUUM命令会修改没有明确指定INTEGER PRIMARY KEY的表的记录的ROWIDs
The VACUUM command may change the ROWIDs of entries in any tables that do not have an explicit INTEGER PRIMARY KEY.

如果有开始的事务或者有一条以上SQL语句正在执行,那么VACUUM会失败。
A VACUUM will fail if there is an open transaction, or if there are one or more active SQL statements when it is run.

从SQLite3.1版开始,增加了一个使用VACUUM命令在数据被删除后回收空间的方法,就是使用auto_vacuum指令开启auto-vacuum模式。当开启了auto_vacuum模式,无需使用VACUUM命令重建整个数据库,就可以在删除数据后空闲的页会被回收,并压缩文件大小。不过使用auto_vacuum会增加数据库文件的碎片化。并且auto_vacuum无法像VACUUM一样压缩部分填满的页。
As of SQLite version 3.1, an alternative to using the VACUUM command to reclaim space after data has been deleted is auto-vacuum mode, enabled using the auto_vacuum pragma. When auto_vacuum is enabled for a database free pages may be reclaimed after deleting data, causing the file to shrink, without rebuilding the entire database using VACUUM. However, using auto_vacuum can lead to extra database file fragmentation. And auto_vacuum does not compact partially filled pages of the database as VACUUM does.