SQL Index

A database index is a separate, sorted structure (usually a B-tree) that lets a query jump to the rows it needs instead of scanning the whole table.

No index on email

SELECT * FROM users WHERE email = 'priya@mail.com';

Table users (stored in insertion order)

1. kiranDelhi
2. ashaMumbai
3. raviPune
4. nehaMumbai
5. farhanChennai
6. vikramChennai
7. aaravPune
8. omarDelhi
9. gitaPune
10. sanaMumbai
11. leelaChennai
12. deepaDelhi
13. taraDelhi
14. meeraPune
15. priyaChennai
16. ishaanMumbai

The rows are stored in the order they were added. With no index, the only way is to check them one by one.

Step 1 / 18
Rows read
0
Index pages read
0

What's happening?

  1. Without an index, `WHERE email = …` has to read every row — a full table scan.
  2. With an index on email, the database reads the B-tree's root, follows one branch to a leaf, and finds a pointer to the row.
  3. A B-tree is very wide and shallow, so even a million rows need only three or four page reads.

Complexity

Time
O(log n) lookup with an index · O(n) full scan without
Space
Extra storage for every index, updated on every write

Where you'll meet it

Every login (WHERE email = ?), every "my orders" page (WHERE user_id = ?), and every slow-query fix starts with checking which index the query uses (EXPLAIN).

Common mistake

Indexing every column. Each index speeds up some reads but slows every INSERT and UPDATE, because the index has to be updated too.

FAQ

Why didn't the full scan stop at the first match?

Without a UNIQUE index the database can't know there is only one match, so it keeps reading.

What does EXPLAIN show?

Whether a query uses an index ("Index Scan") or reads the whole table ("Seq Scan"), and roughly how many rows it expects to read.

When does an index not help?

When the query reads most of the table anyway, wraps the column in a function (WHERE lower(email) = …), or filters on a column the index doesn't lead with.