107

An index is a separate data structure (usually a B+ tree) that lets the database find rows without scanning the whole table, like the index at the back of a book. It speeds up SELECT/WHERE/JOIN/ORDER BY but slows down INSERT/UPDATE/DELETE and uses extra space.

  • Clustered index — the table rows are physically stored in index order; only one per table (the primary key in InnoDB).
  • Non-clustered index — separate structure pointing to rows; many per table.
  • Composite index on (a, b) helps queries on a, or a and b, but not on b alone (leftmost prefix rule).
SQL 3 lines
CREATE INDEX idx_students_name ON students(name);
CREATE INDEX idx_orders_user_date ON orders(user_id, created_at);
EXPLAIN SELECT * FROM students WHERE name = 'Rahim';   -- check if the index is used