Skip to content

Indexes: How They Work and When to Use Them

Beginning of the lesson

Indexes: How They Work and When to Use Them

Speed up reads by letting the database jump straight to the rows it needs

Big Idea: An index is a separate, sorted data structure the database keeps alongside a table so it can find rows without scanning every one. It is the classic space-and-write-time-for-read-time trade: queries that filter, join or sort on the indexed column get dramatically faster, while every INSERT, UPDATE and DELETE has a little more work to do and the index takes disk space. Knowing when that trade pays off is the whole skill.
By the end of this topic you will be able to:
  • explain why a query without an index does a full table scan,
  • describe how a B-tree index narrows a search to a handful of reads,
  • name what an index speeds up (equality, ranges, ORDER BY, joins) and what it costs,
  • choose good columns using selectivity and the leftmost-prefix rule for composite indexes,
  • verify that an index is actually used with EXPLAIN,
  • recognise the cases where you should not add an index.

1. The problem: a full table scan

Every example on this page uses one small table from an online shop. Create it once and load a few rows:

CREATE TABLE customers (
    customer_id INT PRIMARY KEY,
    email       VARCHAR(120),
    city        VARCHAR(50),
    created_at  DATE
);

INSERT INTO customers (customer_id, email, city, created_at) VALUES
    (1, 'ana@shop.io',   'Bishkek', '2025-01-04'),
    (2, 'omar@shop.io',  'Osh',     '2025-01-09'),
    (3, 'lena@shop.io',  'Bishkek', '2025-02-14'),
    (4, 'raj@shop.io',   'Naryn',   '2025-02-20'),
    (5, 'mira@shop.io',  'Osh',     '2025-03-02');

Now imagine this table holds a million rows and you run a very ordinary lookup:

SELECT * FROM customers WHERE email = 'raj@shop.io';

With no index on email, the database has no idea where that row lives. It must read every single row and compare its email one at a time. That is a full table scan: on a million rows it does roughly a million comparisons to return one result.

Analogy. Think of a 900-page textbook with no index at the back. To find every page that mentions "photosynthesis" you would flip through all 900 pages. The alphabetical index at the back changes that: you jump to the letter P, read one line, and it tells you the exact pages. A database index is that back-of-the-book index for your rows.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers