âš¡

Database Indexing Strategies

Master indexing for optimal query performance.

Section 1 of 3: Index Types and Selection0%

Index Types and Selection

Study Material

Understanding Database Indexes:

An index is a data structure that improves query speed at the cost of additional storage and write overhead.

Analogy:

Index = Book's table of contents

Without index: Read entire book to find a topic

With index: Jump directly to the right page

Index Types:

1. B-Tree Index (Default, most common)

Best for:

  • Range queries: <, >, BETWEEN
  • Equality: =
  • Sorting: ORDER BY
  • Prefix matching: LIKE 'abc%'

Structure: Balanced tree, O(log n) lookups

Use cases:

  • Primary keys
  • Foreign keys
  • Date columns (range queries)
  • High-cardinality columns

2. Hash Index

Best for:

  • Exact match only: =
  • Faster than B-Tree for equality

Cannot support:

  • Range queries
  • Sorting
  • Partial matches

Use cases:

  • Lookup tables
  • Session IDs
  • Exact string matching

3. Bitmap Index

Best for:

  • Low-cardinality columns
  • AND/OR operations
  • Data warehouses

Structure: Bit vector per distinct value

Use cases:

  • Gender (M/F)
  • Status (Active/Inactive)
  • Boolean flags
  • Category columns

4. Composite Index (Multi-column)

Index on multiple columns: (customer_id, order_date)

Critical rule: Leftmost prefix matters!

Index on (A, B, C) supports:

WHERE A = ?
WHERE A = ? AND B = ?
WHERE A = ? AND B = ? AND C = ?
WHERE B = ? (doesn't use index efficiently)
WHERE C = ? (doesn't use index)

5. Covering Index

Index that contains ALL columns needed by a query.

Query answered entirely from index - no table access!

CREATE INDEX idx_covering

ON orders(customer_id, order_date)

INCLUDE (total_amount, status);

-- This query uses only the index:

SELECT total_amount, status

FROM orders

WHERE customer_id = 100;