Database Cost of Indexes
What you will learn
- See how indexes affect inserts
- See how they affect file size
- Know the other costs
- Decide when to drop an index
1. Every index must be kept up to date
An index is a second sorted copy of part of the data. When you insert a row, the database writes the row and adds an entry to every index on the table. An UPDATE of an indexed column and a DELETE also touch the indexes. So each index you add makes writes slower.
2. Measure it
We insert the same 100,000 orders into a file database with no extra index, one index and four, and measure time and file size:
import os, tempfile, sqlite3, time
CITIES = ["Dhaka", "Khulna", "Sylhet", "Rajshahi", "Barishal", "Chattogram", "Rangpur", "Mymensingh"]
def load(indexes):
path = os.path.join(tempfile.mkdtemp(), "t.db")
con = sqlite3.connect(path)
con.execute("CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER, city TEXT, status TEXT, amount INTEGER, placed TEXT)")
for i, col in enumerate(indexes):
con.execute("CREATE INDEX i%d ON orders (%s)" % (i, col))
rows = [(i, (i*7919)%5000+1, CITIES[i%8], "shipped", (i*37)%1000, "2026-%02d-%02d" % (i%12+1, i%28+1))
for i in range(1, 100001)]
t = time.perf_counter()
con.executemany("INSERT INTO orders VALUES (?,?,?,?,?,?)", rows)
con.commit()
ms = (time.perf_counter() - t) * 1000
con.close()
return ms, os.path.getsize(path) // 1024
for label, idx in [("no extra index", []), ("1 index", ["customer_id"]), ("4 indexes", ["customer_id", "city", "amount", "placed"])]:
ms, kb = load(idx)
print("%-15s insert 100000 rows: %5.0f ms, file %5d KB" % (label, ms, kb))
no extra index insert 100000 rows: 157 ms, file 4080 KB
1 index insert 100000 rows: 218 ms, file 5224 KB
4 indexes insert 100000 rows: 966 ms, file 10224 KB
On the machine used to write this lesson, four indexes made the load about six times slower and the file about two and a half times larger than with no extra index. Your numbers will differ, but the direction will be the same: more indexes, slower writes, bigger files. Reads, as lesson 7.4 showed, can be far faster. Indexes move cost from reading to writing.
The size cost on the sample data. This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). A time depends on the computer, but the size of the database file does not. Each index you create lives in your browser's copy and makes the file bigger (Reset data removes them):
SELECT page_count * page_size / 1024 AS size_kb FROM pragma_page_count(), pragma_page_size();
CREATE INDEX idx_orders_customer ON orders (customer_id);
SELECT page_count * page_size / 1024 AS size_kb FROM pragma_page_count(), pragma_page_size();
CREATE INDEX idx_orders_date ON orders (order_date);
CREATE INDEX idx_orders_city ON orders (ship_city);
SELECT page_count * page_size / 1024 AS size_kb FROM pragma_page_count(), pragma_page_size();
size_kb
-------
524
(1 row)
size_kb
-------
556
(1 row)
size_kb
-------
648
(1 row)
SELECT page_count * page_size / 1024 AS size_kb FROM pragma_page_count(), pragma_page_size();
CREATE INDEX idx_txn_account ON transactions (account_id);
SELECT page_count * page_size / 1024 AS size_kb FROM pragma_page_count(), pragma_page_size();
CREATE INDEX idx_txn_date ON transactions (txn_date);
CREATE INDEX idx_txn_kind ON transactions (kind);
SELECT page_count * page_size / 1024 AS size_kb FROM pragma_page_count(), pragma_page_size();
size_kb
-------
516
(1 row)
size_kb
-------
592
(1 row)
size_kb
-------
852
(1 row)
SELECT page_count * page_size / 1024 AS size_kb FROM pragma_page_count(), pragma_page_size();
CREATE INDEX idx_sub_student ON submissions (student_id);
SELECT page_count * page_size / 1024 AS size_kb FROM pragma_page_count(), pragma_page_size();
CREATE INDEX idx_sub_date ON submissions (submitted_on);
CREATE INDEX idx_sub_points ON submissions (points);
SELECT page_count * page_size / 1024 AS size_kb FROM pragma_page_count(), pragma_page_size();
size_kb
-------
640
(1 row)
size_kb
-------
684
(1 row)
size_kb
-------
824
(1 row)
The three results are the size with no extra index, with one, and with three. Every insert, update of an indexed column and delete on that table must also update these indexes.
Load first, index afterwards. For a huge one-off import, it is often quicker to insert the rows into a table with no extra indexes and build the indexes once at the end, instead of updating them row by row. A test with 100,000 rows and three indexes (customer, amount, placed), run twice:
import sqlite3, time
rows = [(i, (i*7919)%5000+1, "Dhaka", "shipped", (i*37)%1000, "2026-01-01") for i in range(1, 100001)]
def run(index_first):
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER, city TEXT, status TEXT, amount INTEGER, placed TEXT)")
t = time.perf_counter()
if index_first:
for c in ("customer_id", "amount", "placed"): con.execute(f"CREATE INDEX i_{c} ON orders ({c})")
con.executemany("INSERT INTO orders VALUES (?,?,?,?,?,?)", rows)
if not index_first:
for c in ("customer_id", "amount", "placed"): con.execute(f"CREATE INDEX i_{c} ON orders ({c})")
con.commit()
return (time.perf_counter() - t) * 1000
for k in range(2):
print("run", k+1, "indexes first: %.0f ms, indexes after load: %.0f ms" % (run(True), run(False)))
run 1 indexes first: 665 ms, indexes after load: 246 ms
run 2 indexes first: 762 ms, indexes after load: 485 ms
Both runs favour building afterwards, though the size of the gap varies a lot. That is why the lesson says "measure on your system".
3. Other costs
- Memory and cache: bigger files compete for the computer's memory.
- Backups and copies: bigger databases take longer to back up and restore (chapter 8).
- Planning: with many indexes the planner has more choices, and a poor choice is possible.
- Maintenance: someone must remember why each index exists.
4. Dropping indexes you do not need
An index is worth keeping if some important query uses it. To check, read the plans of your real queries (lesson 7.6). An index no plan uses, or one that repeats another (such as (city) next to (city, status), lesson 7.5), is a candidate to remove with DROP INDEX (lesson 7.3). Before dropping on a real system, try it first on a copy and time the queries that matter.
Worked example: reading versus writing
A bank's transaction log receives thousands of new rows every minute but is searched only once a day for reports. Here writes dominate, so keep few indexes, only what the report needs. A product catalogue is changed rarely and searched constantly, so it can afford more indexes. The right number depends on the read/write balance of your table. Both examples are made up.
Common mistakes
- Believing indexes are free speed.
- Leaving old indexes in place after queries change.
- Judging by one timing. Measure several times on realistic data.
- Keeping indexes during a huge one-off load without testing whether building them afterwards is quicker.
Key takeaways
- Each index must be updated on every insert, and on updates and deletes of its columns.
- In the test, four indexes made loading about six times slower and the file about 2.5 times bigger.
- Indexes also cost memory, backup time and upkeep.
- Keep indexes that important queries use; drop repeated or unused ones after testing.
Practice
1. Why does adding an index slow down INSERT?
Show answer
The database must add an entry to the index for each new row, besides storing the row.
2. In the lesson's test, what happened to the file size with four indexes?
Show answer
It grew from 4080 KB to 10224 KB.
3. Which kind of table can afford many indexes: one that is mostly read, or one that is mostly written?
Show answer
A mostly read table; a write-heavy table pays for every index on every write.
4. Name two costs of indexes apart from slower writes.
Show answer
Disk space, and bigger/slower backups (also memory use and planning/maintenance).
5. Is an index on (city) needed if (city, status) exists?
Show answer
Usually not: the composite index already serves queries on city.
6. A big one-off import is slow. What could you try?
Show answer
Create the indexes after loading the data, so each is built once instead of being updated row by row. Measure it to confirm on your system.