How to Add an Index in MySQL

Indexes are essential for optimizing the performance of your MySQL database. They help speed up queries, especially on large datasets, by allowing the database engine to locate rows more efficiently.

What is an Index?

An index in MySQL is a data structure that improves the speed of data retrieval operations on a table at the cost of additional space and maintenance overhead when inserting, updating, or deleting rows.

Why Use Indexes?

  • Speed up SELECT queries
  • Improve JOIN performance
  • Enforce uniqueness with UNIQUE indexes
  • Optimize sorting and grouping operations

How to Add an Index

You can add an index to a MySQL table using the CREATE INDEX statement or by altering the table. Here’s how:

1. Using CREATE INDEX

CREATE INDEX index_name ON table_name (column_name);

Example:

CREATE INDEX idx_email ON users (email);

2. Using ALTER TABLE

ALTER TABLE table_name ADD INDEX index_name (column_name);

Example:

ALTER TABLE users ADD INDEX idx_email (email);

Types of Indexes

  • PRIMARY KEY — A unique index that uniquely identifies each row
  • UNIQUE — Ensures all values in the index are distinct
  • FULLTEXT — Used for full-text searches
  • SPATIAL — For spatial (GIS) data types

Best Practices

  • Index columns that appear in WHERE, JOIN, ORDER BY, or GROUP BY clauses
  • Avoid over-indexing; too many indexes can slow down write operations
  • Use composite indexes when querying multiple columns together
  • Regularly monitor and analyze query performance

Verifying Indexes

Check existing indexes on a table with:

SHOW INDEXES FROM table_name;

Conclusion

Adding indexes is one of the most effective ways to improve the performance of your MySQL queries. Be sure to test and monitor their impact, as the right balance between read and write performance is key to a well-optimized database.