0
0
MySQLquery~5 mins

Index maintenance in MySQL

Choose your learning style9 modes available
Introduction
Indexes help databases find data faster. Index maintenance keeps these indexes working well and up to date.
When your database queries are slow and you want to speed them up.
After adding or deleting a lot of data to keep indexes efficient.
When you want to check if indexes are still useful or need changes.
Before backing up your database to ensure indexes are optimized.
Syntax
MySQL
ALTER TABLE table_name DROP INDEX index_name;
ALTER TABLE table_name ADD INDEX index_name (column_name);
OPTIMIZE TABLE table_name;
Use DROP INDEX to remove an index that is no longer needed.
Use ADD INDEX to create a new index on one or more columns.
OPTIMIZE TABLE helps reorganize the table and its indexes for better performance.
Examples
This removes the index named 'idx_lastname' from the 'employees' table.
MySQL
ALTER TABLE employees DROP INDEX idx_lastname;
This adds a new index on the 'last_name' column in the 'employees' table.
MySQL
ALTER TABLE employees ADD INDEX idx_lastname (last_name);
This command reorganizes the 'employees' table and its indexes to improve performance.
MySQL
OPTIMIZE TABLE employees;
Sample Program
This example creates a table with an index, then drops and recreates the index, and finally optimizes the table to keep the index efficient.
MySQL
CREATE TABLE employees (
  id INT PRIMARY KEY,
  first_name VARCHAR(50),
  last_name VARCHAR(50),
  INDEX idx_lastname (last_name)
);

-- Drop the existing index
ALTER TABLE employees DROP INDEX idx_lastname;

-- Add the index again
ALTER TABLE employees ADD INDEX idx_lastname (last_name);

-- Optimize the table
OPTIMIZE TABLE employees;
OutputSuccess
Important Notes
Regularly maintaining indexes helps keep your database fast and responsive.
Dropping and recreating indexes can be useful after large data changes.
OPTIMIZE TABLE may lock the table temporarily, so use it during low-traffic times.
Summary
Indexes speed up data searches in a database.
You can drop, add, and optimize indexes to keep them efficient.
Regular index maintenance improves overall database performance.