Ask a database for every student in Dhaka and, by default, it checks the rows one by one until it reaches the end of the table, which is called a full table scan. An index keeps the values of a column in order, each with a pointer to its row, so the database can jump straight to the rows it needs. Think of a phone book: because names are sorted, you open it near the right letter instead of reading from page one. Indexes can make queries hundreds of times faster, but they take space and add a little work to every write.
In this lesson you will learn
- How to create and drop an index
- How to check whether a query uses an index
- Unique and multi-column (composite) indexes
- Which columns are worth indexing
- The trade-offs of adding indexes
Creating an Index and Checking the Plan
CREATE INDEX idx_students_city ON students(city);
-- SQLite shows how it will run the query
EXPLAIN QUERY PLAN SELECT name FROM students WHERE city = 'Dhaka';
EXPLAIN QUERY PLAN SELECT name FROM students WHERE cgpa > 3.5;
SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = 'students';
Output
+--------------------------------------------------------+
| detail |
+--------------------------------------------------------+
| SEARCH students USING INDEX idx_students_city (city=?) |
+--------------------------------------------------------+
(1 row)
+---------------+
| detail |
+---------------+
| SCAN students |
+---------------+
(1 row)
+-------------------+
| name |
+-------------------+
| idx_students_city |
+-------------------+
(1 row)
CREATE INDEX name ON table(column)builds the index.EXPLAIN QUERY PLAN(SQLite) shows the strategy without running the query. SEARCH … USING INDEX means the index is used; SCAN means every row is read.- The
cgpaquery still scans, because there is no index oncgpa. - On a table of 8 rows the difference is invisible. On a few million rows it is the difference between milliseconds and seconds.
Unique and Composite Indexes
CREATE UNIQUE INDEX idx_students_name ON students(name);
CREATE INDEX idx_enroll_student_course ON enrollments(student_id, course_id);
EXPLAIN QUERY PLAN
SELECT marks FROM enrollments WHERE student_id = 3 AND course_id = 101;
DROP INDEX idx_students_name;
SELECT name FROM sqlite_master
WHERE type = 'index' AND name NOT LIKE 'sqlite_%'
ORDER BY name;
Output
+-----------------------------------------------------------------------------------------+
| detail |
+-----------------------------------------------------------------------------------------+
| SEARCH enrollments USING INDEX idx_enroll_student_course (student_id=? AND course_id=?) |
+-----------------------------------------------------------------------------------------+
(1 row)
+---------------------------+
| name |
+---------------------------+
| idx_enroll_student_course |
+---------------------------+
(1 row)
- A unique index also acts as a constraint: it rejects duplicate values.
- A composite index on
(student_id, course_id)serves queries that filter on both columns, and also those that filter onstudent_idalone, but not those that filter only oncourse_id. Order matters: the index works from the leftmost column. DROP INDEXremoves an index; the table data is not affected.
When to Add an Index
| Good candidates | Usually not worth it |
|---|---|
Columns used often in WHERE | Small tables |
Columns used in JOIN ... ON (foreign keys) | Columns with only a few distinct values, such as yes/no |
Columns used in ORDER BY on large results | Tables that are written far more often than read |
Primary key and UNIQUE columns are indexed automatically.
The Cost of Indexes
- Each index takes disk space.
- Every
INSERT,UPDATEandDELETEmust also update the indexes, so too many indexes slow writes. - Functions on the column, such as
WHERE LOWER(name) = 'tania', usually prevent a normal index from being used.
Common Mistakes
- Indexing every column “just in case”.
- Wrong column order in a composite index.
- Using
LIKE '%text'with a leading wildcard, which cannot use a normal index. - Not checking the query plan before and after adding an index.
Practice Exercises
Exercise 1. Create an index that speeds up finding enrollments by course.
Show answer
CREATE INDEX idx_enroll_course ON enrollments(course_id);
Exercise 2. Will an index on (dept, cgpa) help WHERE cgpa > 3.5?
Show answer
Not as a normal search, because cgpa is not the leftmost column. It helps WHERE dept = 'CSE' AND cgpa > 3.5.
Frequently Asked Questions
How do I see the query plan in MySQL or PostgreSQL?
Put EXPLAIN before the query in both. PostgreSQL’s EXPLAIN ANALYZE also runs the query and shows real timings.
What data structure do indexes use?
Most databases use a B-tree, which keeps keys sorted and finds any value in a few steps even with millions of rows. Some also offer hash, full-text and spatial indexes.
Summary
- An index lets the database find rows without scanning the whole table.
- Check with
EXPLAIN QUERY PLAN(SQLite) orEXPLAIN. - Composite indexes work from the leftmost column.
- Indexes speed up reads but cost space and slow writes.
Next: SQL Views.
