MySQL INDEXES

MySQL INDEXES

MySQL INDEXES: A Comprehensive Guide

What is an Index in MySQL?

An index in MySQL is a data structure that improves the speed of data retrieval operations on a database table. It allows MySQL to find and retrieve specific rows much faster than scanning the entire table.

Indexes work similarly to an index in a book—allowing you to quickly find relevant information without flipping through every page.

Why Use Indexes?

Indexes help to:

  1. Speed up queries – Queries that search for specific values, sort data, or filter results can execute much faster.
  2. Improve performance of JOIN operations – Indexes can enhance performance when tables are joined.
  3. Enable unique constraints – A UNIQUE index ensures that no duplicate values exist in the specified columns.
  4. Allow efficient sorting (ORDER BY) – Sorting large datasets is much faster when indexes are used.

However, indexes come with a trade-off:

  • They consume additional disk space.
  • Inserting, updating, and deleting records becomes slightly slower because MySQL must also maintain the index.

Types of Indexes in MySQL

MySQL supports several types of indexes:

  1. Primary Index (PRIMARY KEY)

    • Uniquely identifies each row in a table.
    • Automatically created when a PRIMARY KEY is defined.
    • A table can have only one primary index.
  2. Unique Index (UNIQUE)

    • Ensures that all values in a column (or set of columns) are unique.
    • Unlike a primary key, a table can have multiple unique indexes.
  3. Regular Index (INDEX)

    • Speeds up search operations but allows duplicate values.
    • Useful for optimizing queries that use WHERE, ORDER BY, or GROUP BY.
  4. Full-Text Index (FULLTEXT)

    • Used for full-text searches in CHAR, VARCHAR, and TEXT columns.
    • Enables fast searches for words or phrases.
  5. Spatial Index (SPATIAL)

    • Used for indexing geometric and spatial data types.
  6. Composite Index

    • An index on multiple columns, allows searches to be optimized for queries using any or all of the indexed columns.

Creating Indexes in MySQL

Indexes can be created in multiple ways:

1. Creating an Index When Creating a Table

Primary Key Index

CREATE TABLE employees ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100), department VARCHAR(50) );
  • The PRIMARY KEY automatically creates an index on the id column.

Unique Index

CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, email VARCHAR(255) UNIQUE );
  • The UNIQUE constraint ensures that email values are unique.

Regular Index

CREATE TABLE books ( id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(255), author VARCHAR(100), INDEX (author) -- Creates an index on the 'author' column );

2. Adding an Index to an Existing Table

You can add an index to an existing table using ALTER TABLE:

Adding a Simple Index

ALTER TABLE books ADD INDEX idx_author (author);
  • Creates an index named idx_author on the author column.

Adding a Unique Index

ALTER TABLE users ADD UNIQUE INDEX idx_email (email);
  • Ensures that the email column remains unique.

Adding a Composite Index

ALTER TABLE orders ADD INDEX idx_order (customer_id, order_date);
  • Optimizes queries filtering by customer_id and order_date.

Adding a Full-Text Index

ALTER TABLE articles ADD FULLTEXT INDEX idx_content (content);
  • Optimized for text searches using MATCH(...) AGAINST(...).

3. Creating an Index with CREATE INDEX

The CREATE INDEX statement can also be used:

Creating a Regular Index

CREATE INDEX idx_lastname ON employees (lastname);

Creating a Composite Index

CREATE INDEX idx_emp_dept ON employees (department, hire_date);
  • Helps optimize queries involving both department and hire_date.

Creating a Unique Index

CREATE UNIQUE INDEX idx_phone ON customers (phone_number);
  • Ensures phone_number remains unique.

Using Indexes in Queries

Indexes improve performance when used in WHERE, ORDER BY, and GROUP BY queries.

Example 1: Faster WHERE Queries

SELECT * FROM books WHERE author = 'J.K. Rowling';
  • If author is indexed, MySQL will use the index to quickly find the matching rows instead of scanning the whole table.

Example 2: Faster Sorting (ORDER BY)

SELECT * FROM books ORDER BY title;
  • If title is indexed, sorting is much faster.

Example 3: Optimized Joins

SELECT employees.name, departments.name FROM employees JOIN departments ON employees.department_id = departments.id;
  • Indexing department_id speeds up the JOIN.

Example 4: Full-Text Search

SELECT * FROM articles WHERE MATCH(content) AGAINST('database indexing');
  • If content is indexed with FULLTEXT, this search will be very fast.

Checking Existing Indexes

You can view the indexes on a table using:

SHOW INDEX FROM table_name;

Example:

SHOW INDEX FROM employees;

Dropping an Index

To remove an index from a table:

ALTER TABLE books DROP INDEX idx_author;

or

DROP INDEX idx_author ON books;
  • Note: You cannot drop a PRIMARY KEY index unless you remove the primary key constraint.

Best Practices for Using Indexes

Use indexes for columns frequently used in WHERE, JOIN, ORDER BY, or GROUP BY.
Use composite indexes for multi-column queries.
Index primary and foreign keys for fast lookups.
Use FULLTEXT indexes for searching large text fields.
Avoid over-indexing – too many indexes slow down inserts, updates, and deletes.
Monitor index usage – use EXPLAIN to check if MySQL is using the index.

Analyzing Query Performance Using Indexes

Use the EXPLAIN statement to see if MySQL is using indexes effectively:

EXPLAIN SELECT * FROM books WHERE author = 'George Orwell';
  • This will show whether MySQL is using an index for the query.

Conclusion

Indexes are a powerful way to optimize query performance in MySQL. By carefully choosing which columns to index and using the right type of index, you can drastically improve database performance. However, indexes should be used wisely to balance query speed with storage and write performance.

Would you like help analyzing query performance using indexes? 🚀

Souy Soeng

Souy Soeng

Our website teaches and reads PHP, Framework Laravel, and how to download Admin template sample source code free. Thank you for being so supportive!

Github

Post a Comment

CAN FEEDBACK
close