Labs ICT
โญ Pro Login

Indexes

Making queries faster with strategic indexing.

Speeding Up Queries

An index is a data structure that improves the speed of data retrieval operations. Without an index, the database must scan every row in a table (a full table scan) to find matching records. With an index, it can jump directly to the right rows โ€” like using the index at the back of a book instead of reading every page.

Creating Indexes


  -- Single column index
  CREATE INDEX idx_student_name ON Students(Name);

  -- Composite index
  CREATE INDEX idx_student_dept_age ON Students(DeptID, Age);

  -- Unique index (enforces uniqueness)
  CREATE UNIQUE INDEX idx_student_email ON Students(Email);

  -- Check existing indexes
  SHOW INDEX FROM Students;  -- MySQL
  \di                         -- PostgreSQL

When to Use Indexes

How Indexes Work (B-Tree)


  B-Tree Index Structure:

                   โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                   โ”‚  50     โ”‚
                   โ””โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”˜
                โ”Œโ”€โ”€โ”€โ”€โ”˜     โ””โ”€โ”€โ”€โ”€โ”
           โ”Œโ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”     โ”Œโ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”
           โ”‚  25     โ”‚     โ”‚  75     โ”‚
           โ””โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”˜     โ””โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”˜
          โ”Œโ”€โ”€โ”˜     โ””โ”€โ”€โ”   โ”Œโ”€โ”€โ”˜     โ””โ”€โ”€โ”
        โ”Œโ”€โ”ดโ”€โ”     โ”Œโ”€โ”€โ”€โ”ดโ” โ”Œโ”€โ”ดโ”€โ”     โ”Œโ”€โ”€โ”€โ”ดโ”
        โ”‚10 โ”‚     โ”‚30  โ”‚ โ”‚60 โ”‚     โ”‚90  โ”‚
        โ””โ”€โ”€โ”€โ”˜     โ””โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”˜     โ””โ”€โ”€โ”€โ”€โ”˜

  To find value 30:
  Start at root (50) โ†’ go left (< 50)
  โ†’ node (25) โ†’ go right (> 25)
  โ†’ found (30)!

  Only 3 steps instead of scanning all rows!

๐Ÿงช Quick Quiz

What does an index do?