MySQL
database indexing
SQL optimization
database performance
index creation

How do I add indexes to MySQL tables?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Adding indexes to MySQL tables is an essential task for optimizing query performance and speeding up data retrieval. Indexes, akin to a book's index, allow MySQL to find records far more quickly than scanning an entire table. Let's delve into how to add indexes to MySQL tables, explore the types of indexes, and examine best practices for their use.

Types of Indexes

Before adding indexes, it's important to understand the types of indexes available in MySQL:

  1. Primary Key Index: Automatically created when you define a primary key.
  2. Unique Index: Ensures all values in a column are distinct.
  3. Fulltext Index: Used for full-text searches, predominantly in text fields.
  4. Spatial Index: Designed for indexing spatial data types.
  5. Composite Index: Index based on multiple columns, enhancing complex query performance.
  6. B-tree Index: Default index type in MySQL, applies to most index creations.
  7. Hash Index: Employed in MEMORY tables, best for exact match lookups.

Adding Indexes to MySQL Tables

Adding a Primary Key Index

A primary key automatically indexes a column. For example:

sql
1CREATE TABLE Employees (
2  EmployeeID INT NOT NULL,
3  Name VARCHAR(100),
4  Position VARCHAR(100),
5  PRIMARY KEY (EmployeeID)
6);

Adding a Unique Index

Unique indexes ensure column values remain unique:

sql
CREATE UNIQUE INDEX idx_email
ON Employees (Email);

Here, each email must be unique across the Employees table.

Adding a Fulltext Index

Useful for text searching capabilities:

sql
1CREATE TABLE Articles (
2  ID INT AUTO_INCREMENT,
3  Title VARCHAR(255),
4  Content TEXT,
5  FULLTEXT (Title, Content)
6);

Adding an Index to Existing Tables

To add an index to a table that already exists:

sql
ALTER TABLE Employees ADD INDEX idx_position (Position);

Composite Indexes

Indexes spanning multiple columns can significantly enhance performance for specific queries:

sql
ALTER TABLE Orders ADD INDEX idx_customer_order (CustomerID, OrderDate);

This composite index aids in query operations involving both CustomerID and OrderDate.

Best Practices

  1. Index Only What You Query: Indexing every column can degrade performance due to increased overhead.
  2. Consider Column Selectivity: Indices are more beneficial on columns with high selectivity — many distinct values.
  3. Monitor for Redundancy: Avoid overlapping indices like one on (Column A) and another on (Column A, Column B).

Potential Drawbacks

While indexes improve query speed, they also have downsides:

  • Indexes occupy disk space.
  • They can slow down insert and update operations due to the need for index maintenance.

Summary Table

Index TypeSuitable ForRemarks
Primary KeyUnique row identifierAutomatically created with primary key
UniqueEnforcing uniquenessUseful for fields like Email or Username
FulltextText searchingUsed with MATCH() and AGAINST()
SpatialSpatial data typesRequires MyISAM storage engine (for older versions)
CompositeMulti-column queriesImproves performance for specific queries
B-treeGeneral indexingDefault index type in MySQL
HashExact match lookupsUsed in MEMORY tables

Adding the right indexes in MySQL requires careful planning and an understanding of the database's query requirements. Employ the types of indexes judiciously to improve performance, reduce query time, and maintain the efficiency of the database system.


Course illustration
Course illustration

All Rights Reserved.