New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming› SQL› Indexes and Query Performance

Indexes and Query Performance

💻 SQL

Understand why some queries are slow and how an index fixes them.

Lesson 8 of 9 Tutorial
0 of 9 completed

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.

By the end of this lesson you can:
  • 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.

Warning Wrapping an indexed column in a function, such as WHERE LOWER(email) = ?, can stop the index from being used. Store normalised values instead.

Practice

  1. Add an index to the score column of students.
  2. Run EXPLAIN on a query that filters by level.
  3. 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

Exercise 1. Speed up a filter Medium
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.
SQL exercise-1.sql
Expected Output
The plan should use the new index instead of scanning every row.

Lesson Nav

Lesson sections