Skip to content
Home/Resources/Software Development/Indexing in databases
Concept ยท Software Development

Indexing in databases explained: what an index is, with a timed 200,000-row demo

Younus FardeenBy Younus FardeenUpdated 1 Dec 202614 min read
Short answer

A database index is a separate sorted structure, usually a B-tree, that lets the database find rows by a column's value without reading the whole table. It makes reads faster and writes slower, and it uses disk space. Create indexes for columns used in WHERE, JOIN and ORDER BY on large tables, not on every column.

On this pageWhat an index is, and the B-tree behind itBefore and after CREATE INDEX: the timed demoComposite indexes and the leftmost-prefix ruleCovering indexes and clustered vs non-clusteredWhen indexes hurt, and a checklistFrequently asked questions

Most explanations of indexing use a book analogy and stop. This page measures it: a 200,000-row table in SQLite, the query plan before and after CREATE INDEX, the time per lookup, the size the index adds, and the cases where an index does nothing or makes things worse. Every code block was executed through Python's built-in sqlite3 module on SQLite 3.54.0.

The plan text and the on-disk layout are SQLite's, so the page notes where MySQL (InnoDB) and PostgreSQL differ. Timings depend on your machine: the figures quoted come from one laptop run, and you should expect the same shape (a ratio in the thousands for a point lookup) rather than the same milliseconds. For slow-query habits to build around this, see SQL interview questions and SQL joins explained.

What an index is, and the B-tree behind it

An index is a second copy of one or more columns, kept sorted, with a pointer back to each row. Without one, a query like WHERE email = ? reads every row (a full table scan). With a B-tree index the database walks from the root of a tree to the matching entry in a handful of steps. A B-tree is a balanced tree where each node holds many keys, so it stays shallow: the arithmetic below is an estimate of how many levels it needs.

import math
rows = 200_000
for fanout in (100, 200, 500):
    print(f"fan-out {fanout:3}: {math.ceil(math.log(rows, fanout))} levels for {rows:,} rows")
fan-out 100: 3 levels for 200,000 rows
fan-out 200: 3 levels for 200,000 rows
fan-out 500: 2 levels for 200,000 rows

Depending on how many keys fit in a node (the fan-out), 200,000 rows need two or three levels. That is two or three page reads to find one row instead of reading about 2,000 pages. The tree is also sorted, so range queries (BETWEEN, >), and ORDER BY can use it, which a hash index cannot do.

QuestionWithout an indexWith a B-tree index
Find one row by valueRead every row, O(n)Walk the tree, O(log n)
Range or ORDER BY on the columnScan then sortRead in order from the index
INSERT, UPDATE, DELETEChange the table onlyChange the table and every index
Disk spaceTable onlyTable plus a sorted copy of the columns

Before and after CREATE INDEX: the timed demo

The script builds 200,000 users with random cities and plans (seeded, so it is repeatable), runs EXPLAIN QUERY PLAN for an email lookup, times 50 lookups, creates the index, then times 2,000 lookups. In SQLite the SCAN word means a full table scan, and SEARCH ... USING INDEX means a B-tree lookup.

import sqlite3, random, time
random.seed(7)
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT, city TEXT, plan TEXT, signup_year INTEGER)")
cities = ["Bengaluru", "Pune", "Delhi", "Mumbai", "Chennai", "Hyderabad", "Kolkata", "Jaipur"]
plans = ["free", "pro", "team"]
rows = [(i, f"user{i}@example.com", random.choice(cities), random.choice(plans), random.randint(2019, 2026))
        for i in range(1, 200_001)]
db.executemany("INSERT INTO users VALUES (?,?,?,?,?)", rows)
db.commit()
print("rows:", db.execute("SELECT COUNT(*) FROM users").fetchone()[0])

def plan(sql, args=()):
    return [r[3] for r in db.execute("EXPLAIN QUERY PLAN " + sql, args)]
def timeit(sql, make_args, n):
    t = time.perf_counter()
    for i in range(n): db.execute(sql, make_args(i)).fetchall()
    return (time.perf_counter() - t) / n * 1000

Q = "SELECT id, city FROM users WHERE email = ?"
probe = lambda i: (f"user{(i * 997) % 200_000 + 1}@example.com",)
print("before:", plan(Q, probe(0)))
before = timeit(Q, probe, 50)

db.execute("CREATE INDEX idx_users_email ON users(email)")
print("after: ", plan(Q, probe(0)))
after = timeit(Q, probe, 2000)
print(f"per lookup: {before:.2f} ms without index, {after:.4f} ms with index, about {before / after:,.0f}x faster")
rows: 200000
before: ['SCAN users']
after:  ['SEARCH users USING INDEX idx_users_email (email=?)']
per lookup: 6.89 ms without index, 0.0026 ms with index, about 2,610x faster

The plan flipped from SCAN users to SEARCH users USING INDEX idx_users_email (email=?). The measured gap was more than 2,000 times on this machine; across three runs the ratio ranged from about 2,300 to 2,600. The time without an index is the cost of reading 200,000 rows, so it grows with the table, while the indexed time barely moves as the table grows. Read the plan first: in MySQL and PostgreSQL the same check is EXPLAIN, and PostgreSQL's EXPLAIN ANALYZE also runs the query and reports actual timings.

Composite indexes and the leftmost-prefix rule

A composite index covers several columns in a fixed order, sorted by the first column, then the second within it, and so on. Think of a phone directory sorted by surname then first name: it finds "Rao, Asha" and all "Rao" quickly, but it cannot find everyone named Asha. The index below is (city, plan, signup_year).

import sqlite3, random, time
random.seed(7)
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT, city TEXT, plan TEXT, signup_year INTEGER)")
cities = ["Bengaluru", "Pune", "Delhi", "Mumbai", "Chennai", "Hyderabad", "Kolkata", "Jaipur"]
plans = ["free", "pro", "team"]
db.executemany("INSERT INTO users VALUES (?,?,?,?,?)",
    [(i, f"user{i}@example.com", random.choice(cities), random.choice(plans), random.randint(2019, 2026))
     for i in range(1, 200_001)])
def plan(sql, args=()):
    return [r[3] for r in db.execute("EXPLAIN QUERY PLAN " + sql, args)]
def ms(sql, args=(), n=20):
    t = time.perf_counter()
    for _ in range(n): db.execute(sql, args).fetchall()
    return (time.perf_counter() - t) / n * 1000

db.execute("CREATE INDEX idx_city_plan_year ON users(city, plan, signup_year)")
tests = {
 "city only":                 "SELECT * FROM users WHERE city = 'Pune'",
 "city + plan":               "SELECT * FROM users WHERE city = 'Pune' AND plan = 'pro'",
 "city + plan + year range":  "SELECT * FROM users WHERE city = 'Pune' AND plan = 'pro' AND signup_year >= 2025",
 "plan only (skips city)":    "SELECT * FROM users WHERE plan = 'pro'",
 "city + year (skips plan)":  "SELECT * FROM users WHERE city = 'Pune' AND signup_year = 2025",
 "city, ORDER BY plan":       "SELECT * FROM users WHERE city = 'Pune' ORDER BY plan",
}
for name, q in tests.items():
    print(f"{name:26} -> {'; '.join(plan(q))}")
city only                  -> SEARCH users USING INDEX idx_city_plan_year (city=?)
city + plan                -> SEARCH users USING INDEX idx_city_plan_year (city=? AND plan=?)
city + plan + year range   -> SEARCH users USING INDEX idx_city_plan_year (city=? AND plan=? AND signup_year>?)
plan only (skips city)     -> SCAN users
city + year (skips plan)   -> SEARCH users USING INDEX idx_city_plan_year (city=?)
city, ORDER BY plan        -> SEARCH users USING INDEX idx_city_plan_year (city=?)
Query filters onIndex used?Why
cityYesLeading column
city and planYes, both columnsEquality on a leading prefix
city, plan, and a range on signup_yearYes, all threeEquality columns first, one range last
plan onlyNo, full scanLeading column missing
city and signup_yearOnly city narrows the searchplan is skipped, so signup_year cannot be used to seek
city with ORDER BY planYes, and no separate sort stepIndex order already matches

That is the rule behind the interview question "does column order matter in a composite index?". Yes. Put equality columns first, then the one range column, and order the equality columns so that the queries you run most can use a prefix. PostgreSQL's documentation states the same rule: equality constraints on leading columns, plus an inequality on the first column without an equality, limit the scanned portion (PostgreSQL multicolumn indexes). A caveat: PostgreSQL and some optimisers can sometimes use a non-leading column, only less efficiently, so test with EXPLAIN rather than assuming.

Covering indexes and clustered vs non-clustered

Normally the database finds the index entry, then jumps to the table to fetch the other columns. A covering index contains every column the query needs, so the table is never touched. SQLite prints USING COVERING INDEX. The cost is a bigger index.

import sqlite3, random, time
random.seed(7)
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT, city TEXT, plan TEXT, signup_year INTEGER)")
cities = ["Bengaluru", "Pune", "Delhi", "Mumbai", "Chennai", "Hyderabad", "Kolkata", "Jaipur"]
plans = ["free", "pro", "team"]
db.executemany("INSERT INTO users VALUES (?,?,?,?,?)",
    [(i, f"user{i}@example.com", random.choice(cities), random.choice(plans), random.randint(2019, 2026))
     for i in range(1, 200_001)])
def plan(sql, args=()):
    return [r[3] for r in db.execute("EXPLAIN QUERY PLAN " + sql, args)]
def ms(sql, args=(), n=20):
    t = time.perf_counter()
    for _ in range(n): db.execute(sql, args).fetchall()
    return (time.perf_counter() - t) / n * 1000

Q_ALL = "SELECT * FROM users WHERE city = 'Pune' AND plan = 'pro' AND signup_year = 2025"
Q_COV = "SELECT plan, signup_year FROM users WHERE city = 'Pune' AND plan = 'pro' AND signup_year = 2025"
def pages(): return db.execute("PRAGMA page_count").fetchone()[0]
p0 = pages()
db.execute("CREATE INDEX idx_city_plan_year ON users(city, plan, signup_year)")
print("table pages:", p0, "| index adds:", pages() - p0, "pages (4096 bytes each)" if db.execute("PRAGMA page_size").fetchone()[0] == 4096 else "")
print("SELECT *       ->", plan(Q_ALL)[0])
print("covered columns->", plan(Q_COV)[0])
table pages: 2253 | index adds: 1138 pages (4096 bytes each)
SELECT *       -> SEARCH users USING INDEX idx_city_plan_year (city=? AND plan=? AND signup_year=?)
covered columns-> SEARCH users USING COVERING INDEX idx_city_plan_year (city=? AND plan=? AND signup_year=?)

SELECT * needs columns the index lacks, so it uses the index and then the table. Selecting only plan and signup_year, which sit in the index, is covered. Note the size line: the composite index added 1,138 pages beside a table of 2,253 pages. An index is not free storage. In SQLite the rowid and the rowid-based primary key do not need to be listed, since every index entry already stores the rowid.

Clustered vs non-clustered

A clustered index decides the physical order of the table rows, so the table itself is the B-tree and there can be only one. A non-clustered (secondary) index is a separate structure that points back to the row. The word means different things by engine, so answer by naming one:

  • MySQL InnoDB: every table has a clustered index that stores the row data, typically the primary key (MySQL 8.4 manual). Other indexes are secondary and carry the primary key as their pointer, so a wide primary key makes every index bigger.
  • SQLite: an ordinary table is stored in rowid order, and INTEGER PRIMARY KEY is that rowid. WITHOUT ROWID tables are stored in primary key order instead (SQLite documentation).
  • PostgreSQL: tables are heaps and every index is secondary. The CLUSTER command reorders the table once by an index, but the order is not maintained for later inserts, so it is re-run periodically (PostgreSQL CLUSTER).
import sqlite3
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE a (id INTEGER PRIMARY KEY, email TEXT, city TEXT);          -- ordinary rowid table
CREATE TABLE b (email TEXT PRIMARY KEY, city TEXT) WITHOUT ROWID;       -- table stored in primary key order
CREATE INDEX a_city ON a(city);
""")
def plan(sql): return "; ".join(r[3] for r in db.execute("EXPLAIN QUERY PLAN " + sql))
print("a by id (the table is the B-tree):", plan("SELECT * FROM a WHERE id = 5"))
print("a by city (separate index):       ", plan("SELECT * FROM a WHERE city = 'Pune'"))
print("a by city, only id needed:        ", plan("SELECT id FROM a WHERE city = 'Pune'"))
print("b by email (primary key order):   ", plan("SELECT * FROM b WHERE email = 'x'"))
a by id (the table is the B-tree): SEARCH a USING INTEGER PRIMARY KEY (rowid=?)
a by city (separate index):        SEARCH a USING INDEX a_city (city=?)
a by city, only id needed:         SEARCH a USING COVERING INDEX a_city (city=?)
b by email (primary key order):    SEARCH b USING PRIMARY KEY (email=?)

The first line shows a lookup by id going straight into the table with no index at all, because the table is the clustered structure. The city lookup uses the secondary index a_city; when only id is requested it becomes a covering lookup.

When indexes hurt, and a checklist

More indexes are not better. The script below measures three common ways an index fails to help or slows the system down.

import sqlite3, random, time
random.seed(7)
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT, city TEXT, plan TEXT, signup_year INTEGER)")
cities = ["Bengaluru", "Pune", "Delhi", "Mumbai", "Chennai", "Hyderabad", "Kolkata", "Jaipur"]
plans = ["free", "pro", "team"]
db.executemany("INSERT INTO users VALUES (?,?,?,?,?)",
    [(i, f"user{i}@example.com", random.choice(cities), random.choice(plans), random.randint(2019, 2026))
     for i in range(1, 200_001)])
def plan(sql, args=()):
    return [r[3] for r in db.execute("EXPLAIN QUERY PLAN " + sql, args)]
def ms(sql, args=(), n=20):
    t = time.perf_counter()
    for _ in range(n): db.execute(sql, args).fetchall()
    return (time.perf_counter() - t) / n * 1000

# 1. Writes get slower with every index
def insert_ms(n_idx):
    d = sqlite3.connect(":memory:")
    d.execute("CREATE TABLE t (id INTEGER PRIMARY KEY, email TEXT, city TEXT, plan TEXT, signup_year INTEGER)")
    if n_idx >= 1: d.execute("CREATE INDEX i1 ON t(email)")
    if n_idx >= 2: d.execute("CREATE INDEX i2 ON t(city, plan)")
    if n_idx >= 3: d.execute("CREATE INDEX i3 ON t(signup_year, city)")
    rows = db.execute("SELECT * FROM users LIMIT 100000").fetchall()
    t0 = time.perf_counter(); d.executemany("INSERT INTO t VALUES (?,?,?,?,?)", rows)
    return (time.perf_counter() - t0) * 1000
for k in (0, 1, 2, 3):
    print(f"insert 100k rows with {k} secondary indexes: {insert_ms(k):6.0f} ms")

# 2. A low-selectivity index can lose to a plain scan
db.execute("CREATE INDEX idx_plan ON users(plan)")
q = "SELECT COUNT(*), AVG(signup_year) FROM users WHERE plan = 'pro'"
print("plan:", plan(q)[0])
print(f"  with idx_plan:   {ms(q):6.1f} ms")
print(f"  NOT INDEXED:     {ms(q.replace('users', 'users NOT INDEXED')):6.1f} ms  (rows matching: {db.execute(q).fetchone()[0]:,} of 200,000)")

# 3. Wrapping the column in a function hides the index
db.execute("CREATE INDEX idx_email ON users(email)")
print("email = ?          ->", plan("SELECT * FROM users WHERE email = 'user5@example.com'")[0])
print("lower(email) = ?   ->", plan("SELECT * FROM users WHERE lower(email) = 'user5@example.com'")[0])
db.execute("CREATE INDEX idx_email_lower ON users(lower(email))")
print("after expression index ->", plan("SELECT * FROM users WHERE lower(email) = 'user5@example.com'")[0])
print("LIKE '%5@example.com'  ->", plan("SELECT * FROM users WHERE email LIKE '%5@example.com'")[0])
insert 100k rows with 0 secondary indexes:     65 ms
insert 100k rows with 1 secondary indexes:    111 ms
insert 100k rows with 2 secondary indexes:    168 ms
insert 100k rows with 3 secondary indexes:    228 ms
plan: SEARCH users USING INDEX idx_plan (plan=?)
  with idx_plan:     10.4 ms
  NOT INDEXED:       10.1 ms  (rows matching: 66,500 of 200,000)
email = ?          -> SEARCH users USING INDEX idx_email (email=?)
lower(email) = ?   -> SCAN users
after expression index -> SEARCH users USING INDEX idx_email_lower (<expr>=?)
LIKE '%5@example.com'  -> SCAN users
  • Writes slow down. Loading 100,000 rows took roughly 65 ms with no secondary index, 100 ms with one, 160 ms with two and 210 ms with three, in the run shown. Every INSERT, and every UPDATE of an indexed column, also edits each index.
  • Low selectivity. An index on plan, which has three values, matches a third of the table. The indexed query and the NOT INDEXED scan took about 10 ms each. When a query returns a large share of the table, scanning is as fast or faster.
  • The index is hidden. lower(email) = ? scanned the table even though email is indexed, because the function changes the value being compared. An expression index on lower(email) fixed it. A leading wildcard (LIKE '%x') also cannot use a normal index, because the sorted order starts at the left.
  1. Write the slow query, then run EXPLAIN and look for a scan on a large table.
  2. Index the columns in WHERE and JOIN ... ON, equality columns first, one range column last.
  3. Check that you are not wrapping the column in a function or comparing mismatched types.
  4. Consider a covering index only for hot, read-heavy queries.
  5. Re-run EXPLAIN and time it. Drop indexes that no query uses.
  6. Avoid indexing tiny tables, low-selectivity columns and tables with heavy bulk loading unless measured.

Foreign key columns are the usual missing index behind slow joins; see SQL joins explained. For a theory-side view of why constraints and keys matter, read normalization in DBMS, and for building a project that needs a real schema and queries, try software development projects.

Frequently asked questions

What is an index in SQL?

An index is a database structure, most often a B-tree, that stores the values of one or more columns in sorted order with pointers to the table rows. It lets the database find rows by those columns without scanning the whole table. You create one with CREATE INDEX name ON table(column). It speeds reads and slows writes.

What is the difference between clustered and non-clustered index?

A clustered index defines the physical order of the table rows, so the table is stored as that index and there can be only one. A non-clustered index is a separate sorted structure with pointers to the rows, and a table can have many. In MySQL InnoDB the primary key is the clustered index; PostgreSQL has only non-clustered indexes.

Why do indexes use B-trees?

A B-tree is sorted and balanced, and each node holds many keys, so it stays two or three levels deep even for hundreds of thousands of rows. That means few disk reads for a lookup. Sorted leaves also support range queries and ORDER BY, which a hash index cannot do.

Does the order of columns in a composite index matter?

Yes. The index is sorted by the first column, then the second within it. Queries can use a leading prefix of the columns but not a later column alone. Put equality columns first and a range column last, and test with EXPLAIN, as the demo above shows for city, plan and signup_year.

What is a covering index?

A covering index includes every column a query reads, so the database answers from the index without visiting the table. It can be much faster for hot queries, and EXPLAIN shows it, for example SQLite's USING COVERING INDEX. The trade is a larger index, and extra write cost when those columns change.

When should you not create an index?

Avoid indexes on very small tables, on columns with few distinct values such as a three-value status, on columns that are rarely filtered or joined, and on tables with heavy bulk writes unless a query clearly needs one. Each index costs disk space and slows inserts and updates. Measure with EXPLAIN first.

How do I see whether a query uses an index?

Run EXPLAIN before the query. SQLite uses EXPLAIN QUERY PLAN and prints SCAN for a full table scan and SEARCH ... USING INDEX for an index lookup. PostgreSQL and MySQL use EXPLAIN, and PostgreSQL's EXPLAIN ANALYZE also runs the query and shows real timings.

Learn this with mentors

Programmes for builders and engineers with admissions open: live classes, mentors and project work.

Continue learning

Interview prep

SQL interview questions

40 questions, one practice schema, every result run on SQLite

11 min read
Concept

SQL joins explained

Every join type on two small tables, with real output and common mistakes

7 min read
Concept

ACID properties in DBMS

ACID and isolation levels shown with real rollback, crash and lock output

8 min read