Learn SQL
-- performance.indexes_btree

Indexes (B-tree) in SQL

Sorted side-structures that turn scans into lookups

--concept

An index is a sorted auxiliary structure — usually a B-tree — pointing into the table. Without one, WHERE salary > 80000 must read every row (a sequential scan). With one, the engine descends the tree in a few steps straight to the first matching row. Indexes make reads fast and writes slightly slower, because every INSERT/UPDATE must maintain them: that trade is the central decision of database performance.

--how it works
1

Build the side structure

CREATE INDEX idx_emp_salary ON employees(salary) — a B-tree keyed by salary, each leaf pointing at the matching table rows.

2

Search becomes descent

WHERE salary > 80000 walks root → branch → leaf — a handful of page reads instead of touching every row.

3

Ranges ride the leaf chain

Leaves are linked in key order: find the first match, then follow the chain — perfect for BETWEEN and ORDER BY.

4

Fetch or cover

The engine pulls each matching row from the table — unless the index contains every needed column, in which case it answers from the index alone.

5

Writes maintain it all

Every INSERT/UPDATE updates every index on the table — the read speed is paid for on every write, forever.

--visualization
WHERE salary > 80000
employees — sequential scanDavid47kBob52kElena58kFarid73kAlice85kCynthia91kall 6 rows read — 4 rejectedidx_emp_salary · (not built yet)an index turns “read everything” into “descend + read 2 leaves”choose a mode and press Run
qualifying row read but rejected (seq) untouched (indexed)
Stage 1 / 4
No index yet. WHERE salary > 80,000 forces a sequential scan — every row must be read.
--example
query.sql
1CREATE INDEX idx_emp_salary ON employees(salary);
2EXPLAIN SELECT name FROM employees WHERE salary > 80000;
Result
plan
QUERY PLAN
Index Scan using idx_emp_salary on employees
Index Cond: (salary > 80000)

Before the index this query was a sequential scan reading all six rows; after it, the plan is an index scan that reads only the two rows above 80,000. On six rows the win is tiny — on sixty million it is the difference between seconds and milliseconds.

--variants

Scan vs index — the same query

The plan is the proof.

query.sql
1CREATE INDEX idx_emp_salary ON employees(salary);
2EXPLAIN SELECT name FROM employees WHERE salary > 80000;
Result
plan
QUERY PLAN
Index Scan using idx_emp_salary on employees
Index Cond: (salary > 80000)
1Before the index: Seq Scan — every row read, three kept.
2After: Index Scan — descend the tree, read only the three qualifying rows.
3At six rows this is noise; at sixty million it is seconds versus milliseconds.

When the index is ignored

Selectivity decides — and functions on the column.

query.sql
1EXPLAIN SELECT * FROM employees WHERE UPPER(name) = 'ALICE';
2-- Seq Scan: the UPPER(name) expression hides the column from the index
3CREATE INDEX idx_emp_name_upper ON employees(UPPER(name));
4-- now: Bitmap Index Scan on idx_emp_name_upper
Result
plan
Seq Scan on employees (cost=0.00..12.00 rows=1)
Filter: (UPPER(name) = 'ALICE'::text)
-- after functional index:
Bitmap Index Scan on idx_emp_name_upper
1A function wrapped around the column makes the stored key order useless — plain indexes cannot see through it.
2A functional index on UPPER(name) precomputes the expression and restores index access.
3Same story with leading wildcards: LIKE '%son' cannot use a name index; LIKE 'A%' can.

Composite index and the leading edge

Column order in the index decides which queries it serves.

query.sql
1CREATE INDEX idx_dept_sal ON employees(department, salary);
2-- serves: WHERE department = ? · WHERE department = ? AND salary > ?
3-- ignored for: WHERE salary > ? (salary is not the leading column)
Result
query shapeplan
department + salary filterIndex Scan on idx_dept_sal
salary-only filterSeq Scan — index not usable
1The B-tree sorts by department, then salary inside each department — like a phone book sorted by surname then first name.
2Filtering on the second key alone skips the sort order — the engine cannot seek into the middle.
3Design rule: equality columns first, range column last; a covering fourth column lets the index answer without the table.

The write-side bill

Every index taxes every write.

query.sql
1-- one INSERT with 5 indexes:
2-- 1 table row write + 5 index maintenance writes
3INSERT INTO employees (id, name, department, salary, age)
4VALUES (8, 'Hana', 'Sales', 54000, 28);
5-- bulk loads often DROP the indexes, load, then REBUILD
Result
result
1 row inserted · 6 total writes (row + 5 index entries)
1Each index entry is a sorted insert of its own — random I/O against the tree.
2Tables with dozens of indexes turn fast bulk loads into hours; drop → load → rebuild is the standard rescue.
3Index for the queries you actually run — the WHERE/JOIN/ORDER BY columns — not speculatively.
--key facts
Not freeindexes speed reads, slow writes, and use disk — index the columns you query, not all of them
Leading edgea composite index (a, b) serves filters on a and a+b, but not on b alone
Other kindsHASH for equality, GiST/GIN for text and geometry — B-tree is the default workhorse
--use cases
Primary keys and FK lookup columns — the two indexes almost every table deserves
Hot predicates: status filters, tenant ids, date ranges on event tables
Sort acceleration: an index on (department, salary DESC) pre-sorts top-N queries
Uniqueness: UNIQUE constraints are indexes wearing a contract
--under the hood
Postgres keeps indexes separate from the heap (secondary); MySQL InnoDB clusters row data in the primary key itself — a second key lookup per non-covering query.
Monitor pg_stat_user_indexes / sys.schema_unused_indexes: never-read indexes are pure write tax and safe to drop.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Take the queries you just visualized and see the data structures that power real databases.