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
- Index columns that appear often in WHERE conditions with
=or ranges. - Index join columns, especially foreign keys.
- Index columns used in ORDER BY or GROUP BY when the result is large.
- Prefer columns with many different values (high selectivity). An index on a gender column helps little.
- Avoid indexing small tables, which the DBMS scans quickly.
- 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) = 2025cannot use an index onjoin_date, butWHERE 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
- State four guidelines for choosing indexes.
- What is a composite index? Why does column order matter?
- Write an index to speed up
WHERE dept_id = 3 AND marks > 70. - Why can a function on an indexed column stop the index from being used?
- What does EXPLAIN show?
Answers to the practice questions
- Index WHERE columns, join columns, ORDER BY columns, and high-selectivity columns.
- An index on several columns; it serves queries that use its leftmost columns.
CREATE INDEX idx ON student(dept_id, marks);- The index is on the raw value, not on the function result, so the DBMS cannot search it directly.
- 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
