SQL Index
Basics
Learn what a database index is, why it dramatically speeds up queries, and how to think about when to use one.
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
Why Does Speed Matter?
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.
Creating an Index in SQL
CREATE INDEX idx_last_name
ON employees (last_name);
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
WHERE last_name = 'Smith'), index it.The Trade-Off: Indexes Are Not Free
How to Decide If You Need an Index
EXPLAIN SELECT ... to see if the optimizer is using a full scan or an index.Example 1: Simple Lookup
SELECT * FROM customers
WHERE email = 'alice@example.com';
Example 2: Composite Index
SELECT name, salary
FROM employees
WHERE department = 'Engineering'
AND salary > 100000
ORDER BY salary DESC;
CREATE INDEX idx_dept_salary
ON employees (department, salary);
Example 3: Using EXPLAIN
EXPLAIN SELECT * FROM employees
WHERE last_name = 'Garcia';
Types of Indexes
Common Mistakes with Indexes
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?