Skip to main content
Albero Academy

Indexes & Query Performance

Make queries fast — how indexes work, which columns to index, reading the query plan with EXPLAIN, and common performance pitfalls.

Chapter 15SQL15 min readBeginner friendly
  • #SQL
  • #Indexes
  • #Performance

Everything works on a thousand rows. On ten million, a missing index turns a millisecond query into a multi-second table scan. Understanding indexes and how to read the query plan is what separates queries that scale from ones that fall over in production.

Why queries get slow

Without an index, the database must scan every row to find matches — a "full table scan". As the table grows, so does the time. An index gives it a shortcut.

Indexes

An index is a sorted lookup structure (like a book's index) that lets the database jump straight to matching rows instead of scanning:

creating indexes
CREATE INDEX idx_students_email ON students(email);
CREATE INDEX idx_students_programme ON students(programme_id);
-- Composite index: helps queries filtering by both, left-to-right
CREATE INDEX idx_prog_pkg ON students(programme_id, package);

What to index

  • Columns you WHERE on frequently.
  • Columns you JOIN on (foreign keys — often not indexed automatically).
  • Columns you ORDER BY on.

EXPLAIN

Prefix a query with EXPLAIN (or EXPLAIN ANALYZE) to see the plan the database will use. Hunt for a sequential scan where you expected an index:

reading the plan
EXPLAIN ANALYZE
SELECT * FROM students WHERE email = 'aanya@example.com';
-- Look for:
-- "Index Scan using idx_students_email" → good
-- "Seq Scan on students" → full scan (add an index)

Pitfalls

  • A function on an indexed column defeats the index: WHERE LOWER(email) = … can't use an index on email (use a functional index, or store normalised).
  • Leading wildcards (LIKE '%term') can't use a normal index.
  • SELECT * fetches every column — select only what you need.

Practice

Add indexes to the columns you filter and join on. Run EXPLAIN ANALYZE on a query before and after adding an index and compare the plan (Seq Scan → Index Scan). Then find a query where a function on a column defeats the index and rewrite it.

Key takeaways

  1. 01Without an index the database scans every row; an index is a sorted shortcut to matches.
  2. 02Index columns you filter (WHERE), join (foreign keys) and sort (ORDER BY) on.
  3. 03Indexes cost space and slow writes — index deliberately, not everything.
  4. 04EXPLAIN/EXPLAIN ANALYZE shows the plan; a Seq Scan where you expected an index means add one.
  5. 05Functions on indexed columns and leading-wildcard LIKE defeat indexes; avoid SELECT *.