Indexes and Query Performance
💻 SQLUnderstand why some queries are slow and how an index fixes them.
An index is a lookup structure that lets the database find rows without scanning the whole table. It speeds up reads and slightly slows writes.
- Explain what an index does.
- Create an index for a common filter.
- Read a basic query plan.
Why Indexes Help
Without an index, a filter on email reads every row. With an index, the database jumps close to the matching row and reads only what it needs.
Creating an Index
Index columns you filter, join or sort by often. A composite index can serve several queries if the most selective column comes first.
CREATE INDEX idx_students_email ON students (email);
CREATE INDEX idx_sales_product_date ON sales (product, sold_at);Reading a Query Plan
Put EXPLAIN before a query to see how the database will run it. Look for full table scans on large tables and missing index notices.
EXPLAIN
SELECT name
FROM students
WHERE email = 'amina@example.com';Costs
Every index uses disk space and adds work to INSERT and UPDATE. Remove indexes nothing uses. Never index every column by default.
Practice
- Add an index to the score column of students.
- Run EXPLAIN on a query that filters by level.
- List two queries in a school system that would benefit from an index.
Hands-on exercise
A users table is slow to search by email.
1. Write the CREATE INDEX statement.
2. Write an EXPLAIN query that filters by email.
3. In one sentence, explain what changed.
Recap
Indexes make reads fast by avoiding full scans. Index common filters and joins, check with EXPLAIN and remove unused indexes.
Example
CREATE INDEX idx_students_email ON students (email);
CREATE INDEX idx_sales_product_date ON sales (product, sold_at);
Exercises
1. Write the CREATE INDEX statement.
2. Write an EXPLAIN query that filters by email.
3. In one sentence, explain what changed.
Expected Output
The plan should use the new index instead of scanning every row.
Lesson Nav
SQL Course
0/9 lessons completed
- 1 What a Database Is Tutorial
- 2 Filtering and Sorting Tutorial
- 3 Aggregates and Grouping Tutorial
- 4 Joining Tables Tutorial
- 5 Subqueries and Common Table Expressions Tutorial
- 6 Inserting, Updating and Deleting Tutorial
- 7 Schemas, Keys and Normalisation Tutorial
- 8 Indexes and Query Performance Tutorial
- 9 Project: A Reporting Query Project