Choosing the right indexes is a balance between faster reads and slower writes. This topic gives practical rules for that choice.

Guidelines for index selection

  1. Index columns that appear often in WHERE conditions with = or ranges.
  2. Index join columns, especially foreign keys.
  3. Index columns used in ORDER BY or GROUP BY when the result is large.
  4. Prefer columns with many different values (high selectivity). An index on a gender column helps little.
  5. Avoid indexing small tables, which the DBMS scans quickly.
  6. Avoid indexes on columns that change very often.

Composite indexes

An index on (dept_id, marks) helps queries on dept_id alone or on both columns, but not on marks alone. The leftmost column matters.

Basic examples

Example 1. Query: SELECT * FROM student WHERE roll_no = 120;. roll_no is already the primary key, which has an index. Nothing more is needed.

Example 2. Query: SELECT name FROM student WHERE dept_id = 3 AND marks > 70;. Create CREATE INDEX idx_dept_marks ON student(dept_id, marks);. Because name is not in the index, the DBMS also reads the row; adding name as a third column gives an index-only answer.

Example 3. A report that sorts millions of rows by join_date benefits from an index on join_date to avoid a big sort.

Tuning in practice

  • Look at the query plan (EXPLAIN) to see whether an index is used.
  • Rewrite queries to avoid functions on indexed columns: WHERE YEAR(join_date) = 2025 cannot use an index on join_date, but WHERE join_date >= '2025-01-01' AND join_date < '2026-01-01' can.
  • Remove unused indexes.
  • Keep transactions short to reduce lock waits.

Common mistakes

  • Creating a composite index in the wrong column order.
  • Never looking at the query plan and guessing instead.

Practice questions

  1. State four guidelines for choosing indexes.
  2. What is a composite index? Why does column order matter?
  3. Write an index to speed up WHERE dept_id = 3 AND marks > 70.
  4. Why can a function on an indexed column stop the index from being used?
  5. What does EXPLAIN show?

Answers to the practice questions

  1. Index WHERE columns, join columns, ORDER BY columns, and high-selectivity columns.
  2. An index on several columns; it serves queries that use its leftmost columns.
  3. CREATE INDEX idx ON student(dept_id, marks);
  4. The index is on the raw value, not on the function result, so the DBMS cannot search it directly.
  5. The plan the DBMS will use to run the query, including whether indexes are used.

Sources

  • Official BCA syllabus Database Management Systems, course code CC202, Unit III
  • Raghu Ramakrishnan and Johannes Gehrke, Database Management Systems, 3rd edition, McGraw-Hill