01 / 20

SQL Index
Basics

Learn what a database index is, why it dramatically speeds up queries, and how to think about when to use one.

SQL

What Is a Database Index?

An index is a separate data structure that the database maintains alongside your table. It stores a sorted reference to the values in one or more columns, allowing the database engine to find rows much faster than scanning every single row.

The Textbook Analogy

Full Table (800 pages) Row 1: Alice, Sales, ... Row 2: Bob, Engineering, ... Row 3: Carol, Marketing, ... ... Row 799: Yara, Sales, ... Row 800: Zach, HR, ... Scan all 800 rows? vs. Index (sorted) Alice → Row 1 Bob → Row 2 Carol → Row 3 ... Zach → Row 800 ★ Jump straight to "Zach"

Why Does Speed Matter?

Without Index
The database reads every row in order: for a table with 1 million rows, that could mean 1 million comparisons for a single query.
With Index
The database uses a tree structure (like binary search) and finds the row in roughly \( \log_2(1{,}000{,}000) \approx 20 \) steps instead of 1 million.

How an Index Works: B-Tree

Most databases use a B-Tree (balanced tree) structure for indexes. Each node contains sorted keys and pointers, letting the engine navigate from root to leaf in \( O(\log n) \) time.

50 Root 20 | 35 70 | 85 5,10 25,30 40,45 55,65 75,80 90,95 Leaf nodes Finding "42" → 3 steps

Creating an Index in SQL

-- Basic index on a single column
CREATE INDEX idx_last_name
ON employees (last_name);
-- Composite index on multiple columns
CREATE INDEX idx_dept_salary
ON employees (department, salary);

Full Scan vs Index Scan

Full Table Scan Index Scan
How it works Reads every row sequentially Navigates B-Tree to target rows
Time complexity \( O(n) \) \( O(\log n) \)
1M rows lookup ~1,000,000 reads ~20 reads
Best for Small tables, full-table analytics Selective queries on large tables

When to Use an Index

1
Frequent WHERE clauses: if you often filter by a column (e.g., WHERE last_name = 'Smith'), index it.
2
JOIN columns: columns used in JOIN conditions benefit hugely from indexes.
3
ORDER BY / GROUP BY: an index on the sorted column avoids expensive sorting operations.
4
High-cardinality columns: columns with many unique values (like email) benefit more than low-cardinality ones (like gender).

The Trade-Off: Indexes Are Not Free

✓ Faster Reads
SELECT queries with WHERE, JOIN, and ORDER BY run dramatically faster.
✕ Slower Writes
Every INSERT, UPDATE, or DELETE must also update the index, adding overhead.
★ Extra Storage
Each index is a separate data structure that consumes additional disk space.

How to Decide If You Need an Index

1
Identify slow queries: look at queries that take a long time or run frequently.
2
Check the WHERE clause: which columns are used for filtering, joining, or sorting?
3
Evaluate cardinality: does the column have many unique values? High cardinality = good index candidate.
4
Consider write frequency: if the table is updated thousands of times per second, be selective about indexes.
5
Use EXPLAIN: run EXPLAIN SELECT ... to see if the optimizer is using a full scan or an index.

Example 1: Simple Lookup

-- Query: find a specific customer
SELECT * FROM customers
WHERE email = 'alice@example.com';
No Index bob@... ✕ carol@... ✕ dave@... ✕ eve@... ✕ alice@... ✓ (row 50K) With Index on email Root: M A-L node alice@ ✓ 3 steps!

Example 2: Composite Index

-- Query: find high earners in Engineering
SELECT name, salary
FROM employees
WHERE department = 'Engineering'
  AND salary > 100000
ORDER BY salary DESC;
-- Perfect composite index for this query
CREATE INDEX idx_dept_salary
ON employees (department, salary);

Example 3: Using EXPLAIN

-- Check if the database uses our index
EXPLAIN SELECT * FROM employees
WHERE last_name = 'Garcia';
type: ALL
Full table scan: no useful index found. Every row is examined.
type: ref
Index scan: the optimizer found and used an index. Only matching rows are read.

Types of Indexes

Single-Column
Index on one column. Ideal for simple WHERE filters on a single field.
Composite
Index on two or more columns. Column order matters: leftmost column is primary.
Unique
Enforces uniqueness on the column(s). Primary keys automatically create one.

Common Mistakes with Indexes

✕ Over-Indexing
Adding an index on every column wastes storage and slows down INSERT/UPDATE/DELETE operations significantly.
✕ Wrong Column Order
In a composite index (A, B), queries filtering only on B cannot use this index. The leftmost column must be in the WHERE clause.
✕ Indexing Low-Cardinality
Indexing a boolean column (true/false) provides almost no benefit: the index can only narrow results to ~50% of the table.

Index Summary

Concept Key Point
What it is A sorted data structure (B-Tree) for fast lookups
Time complexity \( O(\log n) \) vs \( O(n) \) without
Best for WHERE, JOIN, ORDER BY on high-cardinality columns
Trade-off Faster reads, slower writes, extra storage
Syntax CREATE INDEX name ON table (col1, col2)
Diagnostic Use EXPLAIN to verify index usage

Question 1 of 5

What is the primary purpose of a database index?

Question 2 of 5

A table has 1,000,000 rows. With a B-Tree index, approximately how many comparisons are needed to find a single row?

Question 3 of 5

Which of the following is a disadvantage of adding an index?

Question 4 of 5

You have a composite index on (department, salary). Which query can use this index effectively?

Question 5 of 5

A column called is_active stores only TRUE or FALSE for 10 million rows. Why is indexing this column generally a bad idea?