Database Choosing Columns to Index
What you will learn
- Find columns that deserve an index
- Understand why few distinct values make an index weak
- Know what stops an index from being used
- Check your choice with a query plan
1. Where indexes pay off
Look at the queries your program runs. The columns worth considering are those used to find or arrange rows:
| Where the column appears | Why an index can help |
|---|---|
WHERE column = value |
jump straight to matching rows |
JOIN ... ON a.x = b.y |
find the matching rows in the other table (foreign key columns, lesson 3.1) |
ORDER BY column |
read rows already in order instead of sorting |
UNIQUE rules |
the index enforces them |
Setup. These are the same helpers as in lesson 7.1 (build(), plan(), timeit()), copied here so this page runs on its own:
import sqlite3
import time
CITIES = ["Dhaka", "Khulna", "Sylhet", "Rajshahi", "Barishal", "Chattogram", "Rangpur", "Mymensingh"]
def build(n=100000):
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER, city TEXT, status TEXT, amount INTEGER, placed TEXT)")
rows = []
for i in range(1, n + 1):
cust = (i * 7919) % 5000 + 1
rows.append((i, cust, CITIES[cust % 8], "shipped" if i % 10 else "pending", (i * 37) % 1000,
"2026-%02d-%02d" % (i % 12 + 1, i % 28 + 1)))
con.executemany("INSERT INTO orders VALUES (?,?,?,?,?,?)", rows)
con.commit()
return con
def plan(con, sql, args=()):
for r in con.execute("EXPLAIN QUERY PLAN " + sql, args):
print(r[3])
def timeit(con, sql, args=(), reps=20):
t = time.perf_counter()
for _ in range(reps):
con.execute(sql, args).fetchall()
return (time.perf_counter() - t) / reps * 1000
An index helps most when the column has many different values. The word for this is selectivity: a column is selective when a typical value matches only a few rows. You can estimate it by counting distinct values (on our table of 100,000 orders, built with the Setup helpers):
con = build()
for col in ("customer_id", "status", "city", "amount"):
d = con.execute(f"SELECT COUNT(DISTINCT {col}) FROM orders").fetchone()[0]
print(f"{col:12s} distinct values: {d:5d} average rows per value: {100000/d:.1f}")
customer_id distinct values: 5000 average rows per value: 20.0
status distinct values: 2 average rows per value: 50000.0
city distinct values: 8 average rows per value: 12500.0
amount distinct values: 1000 average rows per value: 100.0
A lookup on customer_id returns about 20 rows out of 100,000: very selective, a good index. A lookup on status returns about half the table: not selective. (The average hides uneven data: here 90% of the rows are shipped, so the rare value pending is far more selective than the average suggests. Section 4 uses that.)
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). The Python above needs a big table to show times; the cells below count distinct values and compare plans on the sample tables. Indexes you create live in your browser's copy; Reset data removes them. How selective are some columns?
SELECT 'customer_id' AS column_name, COUNT(DISTINCT customer_id) AS distinct_values, ROUND(COUNT(*) * 1.0 / COUNT(DISTINCT customer_id), 1) AS avg_rows_per_value FROM orders
UNION ALL
SELECT 'status', COUNT(DISTINCT status), ROUND(COUNT(*) * 1.0 / COUNT(DISTINCT status), 1) FROM orders
UNION ALL
SELECT 'ship_city', COUNT(DISTINCT ship_city), ROUND(COUNT(*) * 1.0 / COUNT(DISTINCT ship_city), 1) FROM orders
UNION ALL
SELECT 'order_date', COUNT(DISTINCT order_date), ROUND(COUNT(*) * 1.0 / COUNT(DISTINCT order_date), 1) FROM orders;
column_name distinct_values avg_rows_per_value
----------- --------------- ------------------
customer_id 365 7.1
status 5 520.0
ship_city 23 113.0
order_date 805 3.2
(4 rows)
SELECT 'account_id' AS column_name, COUNT(DISTINCT account_id) AS distinct_values, ROUND(COUNT(*) * 1.0 / COUNT(DISTINCT account_id), 1) AS avg_rows_per_value FROM transactions
UNION ALL
SELECT 'kind', COUNT(DISTINCT kind), ROUND(COUNT(*) * 1.0 / COUNT(DISTINCT kind), 1) FROM transactions
UNION ALL
SELECT 'txn_date', COUNT(DISTINCT txn_date), ROUND(COUNT(*) * 1.0 / COUNT(DISTINCT txn_date), 1) FROM transactions
UNION ALL
SELECT 'balance_after', COUNT(DISTINCT balance_after), ROUND(COUNT(*) * 1.0 / COUNT(DISTINCT balance_after), 1) FROM transactions;
column_name distinct_values avg_rows_per_value
------------- --------------- ------------------
account_id 450 16.5
kind 6 1235.8
txn_date 2338 3.2
balance_after 3853 1.9
(4 rows)
SELECT 'student_id' AS column_name, COUNT(DISTINCT student_id) AS distinct_values, ROUND(COUNT(*) * 1.0 / COUNT(DISTINCT student_id), 1) AS avg_rows_per_value FROM submissions
UNION ALL
SELECT 'assignment_id', COUNT(DISTINCT assignment_id), ROUND(COUNT(*) * 1.0 / COUNT(DISTINCT assignment_id), 1) FROM submissions
UNION ALL
SELECT 'submitted_on', COUNT(DISTINCT submitted_on), ROUND(COUNT(*) * 1.0 / COUNT(DISTINCT submitted_on), 1) FROM submissions
UNION ALL
SELECT 'points', COUNT(DISTINCT points), ROUND(COUNT(*) * 1.0 / COUNT(DISTINCT points), 1) FROM submissions;
column_name distinct_values avg_rows_per_value
------------- --------------- ------------------
student_id 340 12.0
assignment_id 166 24.6
submitted_on 243 16.8
points 842 4.9
(4 rows)
The columns with many distinct values and few rows per value are the selective ones. A column with a handful of values (a status, a kind) matches a large part of the table on every lookup.
2. Many values versus few
In our orders table customer_id has 5,000 different values and status has 2 (90,000 rows shipped, 10,000 pending). We build the table with the Setup helpers above and time both queries before and after indexing:
con = build()
q1 = "SELECT * FROM orders WHERE status = 'shipped'"
q2 = "SELECT * FROM orders WHERE customer_id = 77"
print("shipped rows:", len(con.execute(q1).fetchall()), "of", con.execute("SELECT COUNT(*) FROM orders").fetchone()[0])
print("no index shipped %.2f ms, customer %.2f ms" % (timeit(con, q1, reps=5), timeit(con, q2, reps=5)))
con.execute("CREATE INDEX idx_status ON orders (status)")
con.execute("CREATE INDEX idx_customer ON orders (customer_id)")
print("with index shipped %.2f ms, customer %.3f ms" % (timeit(con, q1, reps=5), timeit(con, q2, reps=5)))
shipped rows: 90000 of 100000
no index shipped 138.59 ms, customer 5.25 ms
with index shipped 162.41 ms, customer 0.058 ms
(Times vary by machine.) The customer_id index made the lookup about 90 times faster. The status index did not help the shipped query: it returns 90% of the table, so the database has to fetch nearly every row anyway, and going through the index first was even a little slower in this run. An index is for picking a few rows out of many.
3. Things that stop an index being used
We index four columns and look at the plan of several queries:
con = build()
for col in ("customer_id", "status", "amount", "placed"):
con.execute("CREATE INDEX idx_%s ON orders (%s)" % (col, col))
for q in ["SELECT * FROM orders WHERE amount = 500",
"SELECT * FROM orders WHERE amount + 0 = 500",
"SELECT * FROM orders WHERE placed LIKE '2026-03%'",
"SELECT * FROM orders WHERE placed LIKE '%-03-05'",
"SELECT * FROM orders ORDER BY placed LIMIT 5",
"SELECT * FROM orders ORDER BY city LIMIT 5"]:
print(q); plan(con, q)
SELECT * FROM orders WHERE amount = 500
SEARCH orders USING INDEX idx_amount (amount=?)
SELECT * FROM orders WHERE amount + 0 = 500
SCAN orders
SELECT * FROM orders WHERE placed LIKE '2026-03%'
SCAN orders
SELECT * FROM orders WHERE placed LIKE '%-03-05'
SCAN orders
SELECT * FROM orders ORDER BY placed LIMIT 5
SCAN orders USING INDEX idx_placed
SELECT * FROM orders ORDER BY city LIMIT 5
SCAN orders
USE TEMP B-TREE FOR ORDER BY
(The loop created indexes on customer_id, status, amount and placed; there is none on city, which matters for the last query.) What each line teaches:
amount = 500uses the index. Butamount + 0 = 500is the same question with a calculation on the column, and the database does not use the index: it would have to compute the expression for every row. Keep the column bare on one side and do any calculation on the value side.LIKE '%-03-05'starts with a wildcard, so the index (sorted by the start of the text) cannot help. EvenLIKE '2026-03%', which fixes the start, scanned here: in SQLite the defaultLIKEignores upper and lower case, which stops a plain index being used. (The SQLite documentation saysLIKEcan use an index only if the pattern does not begin with a wildcard and the column is indexed with the collation that matches theLIKEmode; for the default case-insensitiveLIKEthat isNOCASE.) For dates stored asYYYY-MM-DDtext, compare with>=and<instead. Run on the same table with an index onplaced,WHERE placed >= '2026-03' AND placed < '2026-04'gaveSEARCH orders USING INDEX idx_placed (placed>? AND placed<?), while theLIKE '2026-03%'version gaveSCAN orders.- If you really want case-insensitive prefix searches, build the index to match. Dropping the plain
placedindex and creatingCREATE INDEX idx_placed_nc ON orders (placed COLLATE NOCASE)turned the sameLIKE '2026-03%'query fromSCAN ordersintoSEARCH orders USING INDEX idx_placed_nc (placed>? AND placed<?). ORDER BY placedwith an index reads rows already in order, so there is no sort step.ORDER BY citywithout an index needsUSE TEMP B-TREE FOR ORDER BY: a temporary sort of all the rows.
The same checks on the sample data. Index two columns and look at the plans (the cell shows only the plan text):
CREATE INDEX idx_orders_customer ON orders (customer_id);
CREATE INDEX idx_orders_date ON orders (order_date);
EXPLAIN QUERY PLAN SELECT * FROM orders WHERE customer_id = 17;
EXPLAIN QUERY PLAN SELECT * FROM orders WHERE customer_id + 0 = 17;
EXPLAIN QUERY PLAN SELECT * FROM orders WHERE order_date LIKE '2026-03%';
EXPLAIN QUERY PLAN SELECT * FROM orders WHERE order_date >= '2026-03' AND order_date < '2026-04';
EXPLAIN QUERY PLAN SELECT * FROM orders ORDER BY order_date LIMIT 5;
EXPLAIN QUERY PLAN SELECT * FROM orders ORDER BY ship_city LIMIT 5;
plan
-------------------------------------------------------------
SEARCH orders USING INDEX idx_orders_customer (customer_id=?)
(1 row)
plan
-----------
SCAN orders
(1 row)
plan
-----------
SCAN orders
(1 row)
plan
-------------------------------------------------------------------------
SEARCH orders USING INDEX idx_orders_date (order_date>? AND order_date<?)
(1 row)
plan
---------------------------------------
SCAN orders USING INDEX idx_orders_date
(1 row)
plan
----------------------------
SCAN orders
USE TEMP B-TREE FOR ORDER BY
(2 rows)
CREATE INDEX idx_txn_account ON transactions (account_id);
CREATE INDEX idx_txn_date ON transactions (txn_date);
EXPLAIN QUERY PLAN SELECT * FROM transactions WHERE account_id = 17;
EXPLAIN QUERY PLAN SELECT * FROM transactions WHERE account_id + 0 = 17;
EXPLAIN QUERY PLAN SELECT * FROM transactions WHERE txn_date LIKE '2026-03%';
EXPLAIN QUERY PLAN SELECT * FROM transactions WHERE txn_date >= '2026-03' AND txn_date < '2026-04';
EXPLAIN QUERY PLAN SELECT * FROM transactions ORDER BY txn_date LIMIT 5;
EXPLAIN QUERY PLAN SELECT * FROM transactions ORDER BY kind LIMIT 5;
plan
--------------------------------------------------------------
SEARCH transactions USING INDEX idx_txn_account (account_id=?)
(1 row)
plan
-----------------
SCAN transactions
(1 row)
plan
-----------------
SCAN transactions
(1 row)
plan
------------------------------------------------------------------------
SEARCH transactions USING INDEX idx_txn_date (txn_date>? AND txn_date<?)
(1 row)
plan
------------------------------------------
SCAN transactions USING INDEX idx_txn_date
(1 row)
plan
----------------------------
SCAN transactions
USE TEMP B-TREE FOR ORDER BY
(2 rows)
CREATE INDEX idx_sub_student ON submissions (student_id);
CREATE INDEX idx_sub_date ON submissions (submitted_on);
EXPLAIN QUERY PLAN SELECT * FROM submissions WHERE student_id = 17;
EXPLAIN QUERY PLAN SELECT * FROM submissions WHERE student_id + 0 = 17;
EXPLAIN QUERY PLAN SELECT * FROM submissions WHERE submitted_on LIKE '2025-11%';
EXPLAIN QUERY PLAN SELECT * FROM submissions WHERE submitted_on >= '2025-11' AND submitted_on < '2025-12';
EXPLAIN QUERY PLAN SELECT * FROM submissions ORDER BY submitted_on LIMIT 5;
EXPLAIN QUERY PLAN SELECT * FROM submissions ORDER BY points LIMIT 5;
plan
-------------------------------------------------------------
SEARCH submissions USING INDEX idx_sub_student (student_id=?)
(1 row)
plan
----------------
SCAN submissions
(1 row)
plan
----------------
SCAN submissions
(1 row)
plan
-------------------------------------------------------------------------------
SEARCH submissions USING INDEX idx_sub_date (submitted_on>? AND submitted_on<?)
(1 row)
plan
-----------------------------------------
SCAN submissions USING INDEX idx_sub_date
(1 row)
plan
----------------------------
SCAN submissions
USE TEMP B-TREE FOR ORDER BY
(2 rows)
In order, the plans show: the bare column is searched through its index; the calculation on the column forces a scan; the LIKE with a prefix is scanned (the default LIKE ignores case, which stops a plain index being used); the range with >= and < is searched through the index; ORDER BY an indexed column reads the index in order; ORDER BY an unindexed column needs a temporary sort (USE TEMP B-TREE FOR ORDER BY).
4. Two special kinds of index
Expression index. If your query applies a function to a column, index the expression instead of the bare column. E-mail look-ups that ignore case are a classic case:
con.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT)")
con.executemany("INSERT INTO users (email) VALUES (?)", [("User%d@Example.com" % i,) for i in range(20000)])
q = "SELECT * FROM users WHERE lower(email) = 'user77@example.com'"
plan(con, q)
con.execute("CREATE INDEX idx_users_lower_email ON users (lower(email))")
plan(con, q)
print(con.execute(q).fetchall())
SCAN users
SEARCH users USING INDEX idx_users_lower_email (<expr>=?)
[(78, 'User77@Example.com')]
The query must use the same expression (lower(email)) as the index for the database to match them.
Partial index. An index can cover only the rows that matter. If your program often asks for the rare pending orders of one city, index just those rows. The index is small, and writes to shipped rows do not touch it:
con = build()
con.execute("CREATE INDEX idx_pending_city ON orders (city) WHERE status = 'pending'")
plan(con, "SELECT * FROM orders WHERE status = 'pending' AND city = 'Dhaka'")
plan(con, "SELECT * FROM orders WHERE status = 'shipped' AND city = 'Dhaka'")
SEARCH orders USING INDEX idx_pending_city (city=?)
SCAN orders
The first query matches the index's WHERE status = 'pending' condition and uses it; the second asks for different rows, so it cannot. Partial indexes exist in SQLite and PostgreSQL; check whether your database offers them before relying on the idea.
On the sample data.
An expression index for case-insensitive first-name look-ups, and a partial index for the pending orders of one city:
EXPLAIN QUERY PLAN SELECT * FROM customers WHERE lower(first_name) = 'vik';
CREATE INDEX idx_customers_lower_first ON customers (lower(first_name));
EXPLAIN QUERY PLAN SELECT * FROM customers WHERE lower(first_name) = 'vik';
CREATE INDEX idx_pending_city ON orders (ship_city) WHERE status = 'pending';
EXPLAIN QUERY PLAN SELECT * FROM orders WHERE status = 'pending' AND ship_city = 'Leeds';
EXPLAIN QUERY PLAN SELECT * FROM orders WHERE status = 'shipped' AND ship_city = 'Leeds';
plan
--------------
SCAN customers
(1 row)
plan
-----------------------------------------------------------------
SEARCH customers USING INDEX idx_customers_lower_first (<expr>=?)
(1 row)
plan
--------------------------------------------------------
SEARCH orders USING INDEX idx_pending_city (ship_city=?)
(1 row)
plan
-----------
SCAN orders
(1 row)
An expression index for case-insensitive name look-ups, and a partial index for the failed transfers of one account:
EXPLAIN QUERY PLAN SELECT * FROM customers WHERE lower(full_name) = 'chen park';
CREATE INDEX idx_customers_lower_name ON customers (lower(full_name));
EXPLAIN QUERY PLAN SELECT * FROM customers WHERE lower(full_name) = 'chen park';
CREATE INDEX idx_failed_from ON transfers (from_account) WHERE status = 'failed';
EXPLAIN QUERY PLAN SELECT * FROM transfers WHERE status = 'failed' AND from_account = 17;
EXPLAIN QUERY PLAN SELECT * FROM transfers WHERE status = 'done' AND from_account = 17;
plan
--------------
SCAN customers
(1 row)
plan
----------------------------------------------------------------
SEARCH customers USING INDEX idx_customers_lower_name (<expr>=?)
(1 row)
plan
-------------------------------------------------------------
SEARCH transfers USING INDEX idx_failed_from (from_account=?)
(1 row)
plan
--------------
SCAN transfers
(1 row)
An expression index for case-insensitive name look-ups, and a partial index for the absences on one day:
EXPLAIN QUERY PLAN SELECT * FROM students WHERE lower(last_name) = 'khan';
CREATE INDEX idx_students_lower_last ON students (lower(last_name));
EXPLAIN QUERY PLAN SELECT * FROM students WHERE lower(last_name) = 'khan';
CREATE INDEX idx_absent_date ON attendance (class_date) WHERE status = 'absent';
EXPLAIN QUERY PLAN SELECT * FROM attendance WHERE status = 'absent' AND class_date = '2026-02-02';
EXPLAIN QUERY PLAN SELECT * FROM attendance WHERE status = 'present' AND class_date = '2026-02-02';
plan
-------------
SCAN students
(1 row)
plan
--------------------------------------------------------------
SEARCH students USING INDEX idx_students_lower_last (<expr>=?)
(1 row)
plan
------------------------------------------------------------
SEARCH attendance USING INDEX idx_absent_date (class_date=?)
(1 row)
plan
---------------
SCAN attendance
(1 row)
The query must use the same expression (lower(...)) as the index, and a partial index is used only by queries that repeat its WHERE condition.
Worked example: choosing indexes for a small shop
The shop's three most common queries are:
SELECT * FROM orders WHERE customer_id = ?; -- a customer's history
SELECT * FROM orders WHERE status = 'pending'; -- work to do
SELECT * FROM orders ORDER BY placed DESC LIMIT 20; -- latest orders
customer_id: many different values, used inWHEREand joins: index it.status: two values, so an index on it alone is weak. Ifpendingis rare (10% here), it may still help that one query, but test it with the plan and a timing before keeping it.placed: used forORDER BY ... LIMIT, where the index avoids sorting everything: index it.
The shop and numbers are made up.
Common mistakes
- Indexing a column with two or three values and expecting speed.
- Wrapping the column in a function or calculation in
WHERE, which hides it from the index. - Starting a
LIKEpattern with%. - Guessing instead of checking. Always read the plan and measure on realistic amounts of data.
Key takeaways
- Index columns used to find rows:
WHERE,JOINandORDER BYcolumns. - Columns with many different values benefit most; two-value columns rarely do.
- A calculation on the column, or a leading
%, stops the index being used. - An index on the
ORDER BYcolumn avoids a separate sort. - Selectivity (how few rows a typical value matches) tells you whether an index will pay off.
- Expression and partial indexes cover special queries:
lower(email), or only thependingrows. - Confirm with the query plan and a timing.
Practice
1. Why did the status = 'shipped' query not get faster with an index?
Show answer
It returns 90% of the rows, so almost every row has to be fetched anyway; the index saves nothing.
2. What change would let an index on amount be used instead of WHERE amount + 0 = 500?
Show answer
Write WHERE amount = 500, with the column bare.
3. Why can't an index help LIKE '%-03-05'?
Show answer
The index is sorted by the start of the value, and the pattern does not fix the start.
4. What does USE TEMP B-TREE FOR ORDER BY mean?
Show answer
The database had to sort the rows in a temporary structure because no index gave them in that order.
5. Your login query is WHERE lower(email) = ? and its plan shows SCAN users, although email has an index. What would you do?
Show answer
The plain index on email is sorted by the original text, not by lower(email). Create an expression index: CREATE INDEX ... ON users (lower(email)), then check that the plan says SEARCH.
6. A column is_active holds only 1 or 0. Should you index it?
Show answer
Probably not on its own: with two values each lookup returns half the table. Test with the plan and timing if one value is very rare.