🔍

How MySQL Indexes Work

Jul 15, 2024

How MySQL Indexes Work

Introduction

  • Discussion about MySQL indexes
  • Highlighted effectiveness of MySQL indexes (reducing query time)
  • Reference to a previous video demonstrating speed improvements

Example Scenario

  • Using the authors table with 3 million records
  • Query to find instances where the first name is "Jonas"
    • Initial query result: ~103 milliseconds
  • Adding an index to the first name column
    • How to add an index: ALTER TABLE authors ADD INDEX author_index (first_name);
    • Indexed query result: ~2.7 milliseconds

Understanding MySQL Indexes

  • Without Indexes: MySQL scans each row until it finds the matching value
    • Time-consuming process as it checks each row one by one
  • With Indexes: MySQL uses a separate storage and ordered list for indexed column values
    • Efficient searching mechanism

How Indexing Works

  • Compares database indexing to a book index
  • Indexing process:
    1. Create separate storage for the indexed column, ordered list
    2. MySQL stores pointer locations (e.g., p10) linking back to the original table

Binary Search (B-Tree Indexing)

  • MySQL uses a binary search-like method, called B-Tree
    • Start at the middle of the ordered index list
    • Eliminate half the search space based on comparison
    • Continue narrowing down the search area until the value is found
    • Retrieve matching records using pointer locations to the main table

Advantages of Indexes

  • Significant reduction in query time
  • Efficient data retrieval without scanning all rows

Types of Indexes

  • Primary Key
  • Unique
  • Regular Index (demonstrated in example)
  • Full Text Index
  • All use the B-Tree structure for indexing

Conclusion

  • Understanding of MySQL indexes and how they improve query performance
  • Mention of future content on different types of indexes
  • Call to action to like and subscribe the channel