Lab 12: Indexes Basics

Time: 30 minutes | Level: Foundations | DB: MySQL 8 / PostgreSQL 15

Overview

Understand why indexes matter, how B-tree indexes work, create regular and unique indexes, inspect with SHOW INDEX and \d+, and read basic EXPLAIN output.


Step 1: Why Indexes?

Without an index, the database performs a full table scan — reading every row to find matches. With an index, it navigates a B-tree structure to find matching rows in O(log n) time.

Full table scan:   Read 1,000,000 rows → find 5 matches
B-tree index:      Navigate ~20 comparisons → find 5 matches

B-tree index structure:

                    [50]
                   /    \
              [25]         [75]
             /    \       /    \
          [10]   [35] [60]    [90]
         / \    / \   / \    / \
        ...leaves with row pointers...

Each leaf points to actual table rows. Searching is fast, but maintaining the index has a write cost.


Step 2: Setup — Generate Test Data

📸 Verified Output:


Step 3: EXPLAIN Without Index

📸 Verified Output (no index):

  • type: ALL = full table scan

  • rows: 9984 = MySQL estimates it will read nearly ALL rows

  • key: NULL = no index used


Step 4: CREATE INDEX

📸 Verified Output (with index):

  • type: ref = index lookup (much better than ALL)

  • rows: 10 = MySQL only reads ~10 rows

  • key: idx_customer_id = index is being used!


Step 5: CREATE UNIQUE INDEX

📸 Verified Output:


Step 6: SHOW INDEX (MySQL) and \d+ (PostgreSQL)

MySQL:

📸 Verified Output:

PostgreSQL:

📸 Verified Output (PostgreSQL \d+):


Step 7: EXPLAIN with Range Queries and Composite Indexes

📸 Verified Output:

💡 Composite index rule (Leftmost Prefix): A composite index on (A, B, C) can be used for queries on A, A+B, or A+B+C — but NOT for queries on just B or C alone.


Step 8: Capstone — Index Strategy

📸 Verified Output (before creating region index):

Cleanup:


Summary

Concept
MySQL
PostgreSQL

Create index

CREATE INDEX idx ON t (col)

Same

Create unique index

CREATE UNIQUE INDEX uq ON t (col)

Same

Composite index

CREATE INDEX idx ON t (col1, col2)

Same

List indexes

SHOW INDEX FROM t

\d+ t

Inspect query plan

EXPLAIN SELECT ...

EXPLAIN SELECT ...

Drop index

DROP INDEX idx ON t

DROP INDEX idx

EXPLAIN type

Meaning

Performance

ALL

Full table scan

Worst

index

Full index scan

Poor

range

Index range scan

Good

ref

Index lookup (non-unique)

Good

eq_ref

Index lookup (unique)

Best

const

Single row lookup

Best

Next: Lab 13 — UPDATE and DELETE

Last updated