Database Maintenance: Vacuum, Statistics and Reindexing
What you will learn
- Why a database needs maintenance even when nothing is wrong
- What VACUUM does, with real before and after sizes
- What statistics are and what ANALYZE does
- When to REINDEX
- How to check that a database file is healthy
This lesson runs on the sample database you chose in lesson 4.1, and it changes your browser's copy of the data (not the server). Run the examples from top to bottom; Reset data at the top starts again.
1. Databases collect clutter
A database file is like a warehouse. When you delete products, the shelves are emptied but the building does not shrink. New products can use the empty shelves, but until then the space is just reserved.
Over weeks and months a busy database collects three kinds of clutter:
| Clutter | What it means |
|---|---|
| Empty space | pages freed by DELETE and UPDATE, still part of the file |
| Stale statistics | the database's picture of the data (how many rows, how varied) no longer matches reality, so its choice of plan (lesson 7.6) may get worse |
| Bloated indexes | an index that has been changed many times may be larger or less tidy than a fresh one |
Maintenance tools clean these up. The names and automation differ in each product: some run maintenance by themselves in the background, others need you to schedule it. Check your product's documentation for the names and settings. This lesson uses SQLite, where you run the commands yourself.
2. VACUUM: giving back empty space
A SQLite database is one file made of fixed-size pages. Three numbers describe it: the page size in bytes, the page count (how many pages the file has) and the freelist count (how many pages are empty and waiting to be reused). The file size in bytes is page count times page size. First, the numbers as the database arrives, and how many rows the table we are about to shrink has:
SELECT COUNT(*) AS order_lines FROM order_items;
SELECT pc.page_count, fl.freelist_count, ps.page_size, pc.page_count * ps.page_size AS bytes
FROM pragma_page_count() pc, pragma_freelist_count() fl, pragma_page_size() ps;
order_lines
-----------
5790
(1 row)
page_count freelist_count page_size bytes
---------- -------------- --------- ------
131 0 4096 536576
(1 row)
SELECT COUNT(*) AS ledger_entries FROM transactions;
SELECT pc.page_count, fl.freelist_count, ps.page_size, pc.page_count * ps.page_size AS bytes
FROM pragma_page_count() pc, pragma_freelist_count() fl, pragma_page_size() ps;
ledger_entries
--------------
7415
(1 row)
page_count freelist_count page_size bytes
---------- -------------- --------- ------
129 0 4096 528384
(1 row)
SELECT COUNT(*) AS attendance_rows FROM attendance;
SELECT pc.page_count, fl.freelist_count, ps.page_size, pc.page_count * ps.page_size AS bytes
FROM pragma_page_count() pc, pragma_freelist_count() fl, pragma_page_size() ps;
attendance_rows
---------------
6012
(1 row)
page_count freelist_count page_size bytes
---------- -------------- --------- ------
160 0 4096 655360
(1 row)
Now delete a large part of the rows (the oldest ones, as if they were archived) and look at the file again:
DELETE FROM order_items WHERE order_id <= 2000;
SELECT COUNT(*) AS order_lines FROM order_items;
SELECT pc.page_count, fl.freelist_count, pc.page_count * ps.page_size AS bytes
FROM pragma_page_count() pc, pragma_freelist_count() fl, pragma_page_size() ps;
order_lines
-----------
1344
(1 row)
page_count freelist_count bytes
---------- -------------- ------
131 34 536576
(1 row)
DELETE FROM transactions WHERE txn_date < '2024-01-01';
SELECT COUNT(*) AS ledger_entries FROM transactions;
SELECT pc.page_count, fl.freelist_count, pc.page_count * ps.page_size AS bytes
FROM pragma_page_count() pc, pragma_freelist_count() fl, pragma_page_size() ps;
ledger_entries
--------------
4603
(1 row)
page_count freelist_count bytes
---------- -------------- ------
129 31 528384
(1 row)
DELETE FROM attendance WHERE class_date < '2026-01-01';
SELECT COUNT(*) AS attendance_rows FROM attendance;
SELECT pc.page_count, fl.freelist_count, pc.page_count * ps.page_size AS bytes
FROM pragma_page_count() pc, pragma_freelist_count() fl, pragma_page_size() ps;
attendance_rows
---------------
1728
(1 row)
page_count freelist_count bytes
---------- -------------- ------
160 40 655360
(1 row)
The rows are gone, but the file is exactly the same size: the page count did not change. The pages that held the deleted rows are now free (the freelist count is no longer 0): they are reserved for future rows. VACUUM rebuilds the file without the empty space:
VACUUM;
SELECT pc.page_count, fl.freelist_count, pc.page_count * ps.page_size AS bytes
FROM pragma_page_count() pc, pragma_freelist_count() fl, pragma_page_size() ps;
page_count freelist_count bytes
---------- -------------- ------
95 0 389120
(1 row)
VACUUM;
SELECT pc.page_count, fl.freelist_count, pc.page_count * ps.page_size AS bytes
FROM pragma_page_count() pc, pragma_freelist_count() fl, pragma_page_size() ps;
page_count freelist_count bytes
---------- -------------- ------
96 0 393216
(1 row)
VACUUM;
SELECT pc.page_count, fl.freelist_count, pc.page_count * ps.page_size AS bytes
FROM pragma_page_count() pc, pragma_freelist_count() fl, pragma_page_size() ps;
page_count freelist_count bytes
---------- -------------- ------
105 0 430080
(1 row)
Read the three results together: before the delete the file has a number of pages and none are free; after the delete it has the same number of pages, but part of them are now free; after VACUUM the page count and the size in bytes drop and the freelist is 0 again. The page counts depend on SQLite's version and settings, so numbers elsewhere may differ, but the pattern is the same.
VACUUM has costs: it rewrites the whole file, needs extra disk space while it works, and in SQLite it locks the database while running. So it is a scheduled, occasional job, not something to run on every request. If a table will fill up again soon, the free pages will be reused anyway, and vacuuming gains nothing.
3. Statistics and ANALYZE
To choose a plan (lesson 7.6), the database estimates things: how many rows match, how selective an index is. It keeps statistics for that. If the data changes a lot and the statistics stay old, the estimates are wrong and the database can choose a poor plan.
In SQLite, ANALYZE collects the statistics into a table called sqlite_stat1. We create an index on a column with only a few different values, run ANALYZE, and read the table (it does not exist before the first ANALYZE):
SELECT name FROM sqlite_master WHERE name = 'sqlite_stat1';
CREATE INDEX idx_orders_status ON orders (status);
ANALYZE;
SELECT tbl, idx, stat FROM sqlite_stat1 WHERE idx = 'idx_orders_status';
name
----
(0 rows)
tbl idx stat
------ ----------------- --------
orders idx_orders_status 2600 520
(1 row)
SELECT name FROM sqlite_master WHERE name = 'sqlite_stat1';
CREATE INDEX idx_transactions_kind ON transactions (kind);
ANALYZE;
SELECT tbl, idx, stat FROM sqlite_stat1 WHERE idx = 'idx_transactions_kind';
name
----
(0 rows)
tbl idx stat
------------ --------------------- --------
transactions idx_transactions_kind 4603 768
(1 row)
SELECT name FROM sqlite_master WHERE name = 'sqlite_stat1';
CREATE INDEX idx_attendance_status ON attendance (status);
ANALYZE;
SELECT tbl, idx, stat FROM sqlite_stat1 WHERE idx = 'idx_attendance_status';
name
----
(0 rows)
tbl idx stat
---------- --------------------- --------
attendance idx_attendance_status 1728 576
(1 row)
The stat text has two numbers: the number of rows in the table, and the average number of rows that match one value of the indexed column. With only a few different values, an index on this column is not very selective (it narrows down to a large share of the table), and the database now knows it. Collecting statistics after big changes (a large import, a big delete) is a good habit. Other products have their own commands and often collect statistics automatically; check the documentation.
4. REINDEX and integrity checks
REINDEX rebuilds an index from the table:
REINDEX idx_orders_status;
(done)
REINDEX idx_transactions_kind;
(done)
REINDEX idx_attendance_status;
(done)
You rarely need it. Reasons to run it: an index looks bloated after heavy changes, or a check reports a problem with the index, or the rules for comparing text changed. It does not change any answer your queries return; it only rebuilds the index.
To check that the file is healthy, SQLite has two checks:
PRAGMA integrity_check;
PRAGMA quick_check;
integrity_check
---------------
ok
(1 row)
quick_check
-----------
ok
(1 row)
PRAGMA integrity_check;
PRAGMA quick_check;
integrity_check
---------------
ok
(1 row)
quick_check
-----------
ok
(1 row)
PRAGMA integrity_check;
PRAGMA quick_check;
integrity_check
---------------
ok
(1 row)
quick_check
-----------
ok
(1 row)
ok means no problems were found. quick_check is faster and does less. If either prints something else, the file is damaged: stop writing to it, and restore a good backup (lesson 8.3). Running such a check on the restored copy of a backup is also a good way of proving the backup is usable.
Worked example: a monthly care routine
A small business keeps its SQLite database on one server. The owner wants a short routine.
| Step | When | Why |
|---|---|---|
| Copy the database file with the backup API (lesson 8.2) | before everything else | so a mistake in the steps below can be undone |
PRAGMA integrity_check on the copy |
monthly | detect damage early |
ANALYZE |
after the end-of-year import of 50,000 rows | so plans fit the new data |
VACUUM |
after the owner deletes last year's archived rows | give the freed space back |
| Note sizes before and after (page count times page size) | each time | to see the trend (lesson 12.4) |
Each step is small, and each has a reason. The business and numbers are made up.
Common mistakes
- Expecting DELETE to shrink the file. It frees pages for reuse; only a rebuild such as
VACUUMgives the space back to the system. - Running VACUUM at busy times, or without enough free disk space for the rebuild.
- Never refreshing statistics after a big change, then blaming the database for slow queries.
- Running a repair-style command without a backup first.
- Never checking backups. A backup that has not been restored and checked is only a hope.
Key takeaways
- Databases accumulate empty space, stale statistics and untidy indexes; maintenance cleans them.
DELETEmakes pages reusable but does not shrink the file;VACUUMrebuilds it smaller.- Statistics help the database pick plans; refresh them after big changes (
ANALYZE). REINDEXrebuilds an index; it is needed rarely.PRAGMA integrity_checktells you whether the file is healthy. Other products have their own tools and often automate this.
Practice
1. After deleting most rows, the file did not shrink. Why?
Show answer
DELETE only marks pages as free for reuse. The file keeps its size until a rebuild such as VACUUM returns the space.
2. What does ANALYZE store, and who uses it?
Show answer
It stores statistics about tables and indexes (row counts, selectivity). The query planner uses them to estimate costs and choose a plan.
3. Why is it a bad idea to run VACUUM every few seconds?
Show answer
It rewrites the whole file, needs extra space and locks the database in SQLite, so it would slow everything down for little gain, especially if the free pages would be reused soon.
4. When might you run REINDEX?
Show answer
When an index seems bloated after heavy changes, when a check reports a problem in the index, or when the text comparison rules changed. It is rarely needed.
5. PRAGMA integrity_check returns something other than ok. What do you do?
Show answer
Treat the file as damaged: stop writing to it, keep a copy of it for study, and restore the most recent good backup (lesson 8.3).
6. Why check a backup by restoring it and running a check on the restored copy?
Show answer
Only a restore proves the backup works. A backup that has never been restored might be incomplete or damaged, and you would find out too late.