MySQL Index: Create, Add & Drop Tutorial

โšก Smart Summary

MySQL Index Tutorial covers how indexes sort and locate data quickly. An index is a sorted lookup structure created on one or more columns; CREATE INDEX adds it, SHOW INDEXES inspects it, and DROP INDEX removes it when write-heavy tables outweigh read benefits.

  • ๐Ÿ“š Treat indexes like a dictionary: They sort column values so the engine can locate rows without scanning the whole table.
  • ๐Ÿ› ๏ธ Create at table or after: Define an index inline in CREATE TABLE or add it later with CREATE INDEX on a live table.
  • ๐Ÿ” Inspect with SHOW INDEXES: Use SHOW INDEXES FROM table_name to list every index, key part, cardinality, and uniqueness flag.
  • ๐Ÿงน Drop when write cost is too high: Indexes slow INSERT and UPDATE โ€” drop unused ones with DROP INDEX to recover write throughput.
  • ๐Ÿค– Use AI for index design: AI assistants read slow-query logs, suggest column orders for composite indexes, and explain EXPLAIN plans line by line.

MySQL Index concept

What is a MySQL Index?

An index in MySQL is a data structure that stores column values in an ordered way so the engine can look rows up quickly. Indexes are created on the column or columns most often used to filter data. Think of an index like an alphabetically sorted list: it is far faster to find a name in a sorted list than in an unsorted pile.

Indexes carry a trade-off โ€” every INSERT or UPDATE has to maintain the index, so adding too many indexes on a write-heavy table can hurt overall performance. As a rule of thumb, index columns that appear in WHERE, JOIN, and ORDER BY clauses on tables that are read more often than they are written.

Why Use an Index?

Nobody likes slow systems. High performance is a top concern for almost every database-backed application. Businesses spend heavily on hardware to keep queries fast, but there is a ceiling to what hardware alone can deliver. Optimising indexes is a cheaper and more effective lever.

MySQL Index concept

Slow response times usually come from rows being stored in physical order on disk. Without an index, MySQL must scan every row to find the ones that match a predicate โ€” a “full table scan”. Indexes let MySQL jump straight to the matching rows, which transforms the query plan from O(n) to roughly O(log n) for B-tree lookups.

Syntax: Create Index

An index can be defined in two places:

  1. At the time of table creation.
  2. After the table already exists.

Example: Create an index inline with CREATE TABLE

For the myflixdb database, we expect a lot of searches on the full-name column. The script below creates a new members_indexed table with an index on the full_names column.

CREATE TABLE `members_indexed` (
    `membership_number` INT(11) NOT NULL AUTO_INCREMENT,
    `full_names`        VARCHAR(150) DEFAULT NULL,
    `gender`            VARCHAR(6)   DEFAULT NULL,
    `date_of_birth`     DATE         DEFAULT NULL,
    `physical_address`  VARCHAR(255) DEFAULT NULL,
    `postal_address`    VARCHAR(255) DEFAULT NULL,
    `contact_number`    VARCHAR(75)  DEFAULT NULL,
    `email`             VARCHAR(255) DEFAULT NULL,
    PRIMARY KEY (`membership_number`),
    INDEX (`full_names`)
) ENGINE = InnoDB;

Execute the script in MySQL Workbench against the myflixdb database.

members_indexed table in MySQL Workbench

Refresh myflixdb to see the new members_indexed table. The full_names column now appears under the Indexes node.

As membership grows, search queries on members_indexed that use WHERE and ORDER BY against full_names are much faster than the same queries on the original members table without the index.

Add an index after the table already exists

You will often discover that an existing table needs an index โ€” search queries are slow and an EXPLAIN plan shows a full table scan on a column that appears in WHERE. The CREATE INDEX statement adds an index without recreating the table.

CREATE INDEX `id_index` ON `table_name` (`column_name`);

Concrete example โ€” speed up searches on the title column of the movies table:

CREATE INDEX `title_index` ON `movies` (`title`);

Every query that filters on movies.title is now backed by the new index. Queries that filter on other columns still scan the table unless they have their own index.

Note: You can create a composite index across multiple columns when your queries always filter or sort on the same combination. Order matters โ€” the leading column drives whether the index can be used.

List indexes on a table

Use SHOW INDEXES to see every index defined on a table.

SHOW INDEXES FROM `table_name`;

Example โ€” list indexes on the movies table:

SHOW INDEXES FROM `movies`;

Run the statement in MySQL Workbench against myflixdb to see the existing indexes and the columns they cover.

Note: Primary and foreign keys are indexed automatically by MySQL. Each index has a unique name and lists the column(s) it covers.

Syntax: Drop Index

Use DROP INDEX to remove an existing index from a table. This is useful when a write-heavy table is being slowed by an index that is no longer earning its keep on the read side.

DROP INDEX `index_id` ON `table_name`;

Concrete example โ€” drop the full_names index from members_indexed:

DROP INDEX `full_names` ON `members_indexed`;

Types of MySQL Indexes

MySQL supports several index types, each suited to a different workload.

Type Purpose
PRIMARY KEY Unique row identifier; clustered with the table data in InnoDB.
UNIQUE Enforces uniqueness while serving as an index.
INDEX (B-tree) Default secondary index used for range queries and equality lookups.
FULLTEXT Optimised for natural-language text search with MATCH โ€ฆ AGAINST.
SPATIAL R-tree index for GIS data types such as POINT and POLYGON.
HASH Constant-time equality lookups; used by the MEMORY storage engine.
Composite (multi-column) Combines several columns into one index; honours the leftmost-prefix rule.

Best Practices for MySQL Indexes

The habits below keep indexes useful and stop them from becoming dead weight.

  • Index for the query pattern, not the column name: add indexes that match real WHERE, JOIN, and ORDER BY clauses, not “every column that sounds important”.
  • Watch composite-index order: the leading column must appear in the query for the index to be used.
  • Avoid duplicate indexes: a leading prefix of a composite index already covers single-column lookups on that prefix.
  • Inspect with EXPLAIN: confirm the planner is actually picking the new index.
  • Drop unused indexes: use sys.schema_unused_indexes in MySQL 5.7+ to find indexes that nothing reads.
  • Match data types: if a WHERE clause compares a VARCHAR column to a number, the index cannot be used because of an implicit cast.

FAQs

A primary key uniquely identifies each row and is always indexed. A general INDEX speeds up lookups but allows duplicate values. Every primary key is an index, but not every index is a primary key.

Avoid indexes on very small tables, on columns with very few distinct values (low cardinality), and on tables that are written far more often than they are read. Each extra index slows every INSERT, UPDATE, and DELETE.

A composite (multi-column) index covers more than one column in a single index. It honours the leftmost-prefix rule, so it can serve queries that filter on the first column, the first two columns, and so on, but not the second column alone.

Run EXPLAIN in front of the SELECT statement. The key column shows which index the optimiser picked, while type and rows tell you whether the access path is efficient.

A covering index contains every column the query needs, so the engine answers the query from the index alone without reading the table. EXPLAIN reports “Using index” when this happens.

Common reasons include wrapping the column in a function (WHERE YEAR(col) = โ€ฆ), implicit type casts, very low cardinality, and stale statistics. Run ANALYZE TABLE to refresh stats and inspect EXPLAIN for the actual reason.

AI assistants ingest slow-query logs, classify the most expensive patterns, suggest single-column or composite indexes, and explain EXPLAIN plans in plain English. They cut tuning time from hours to minutes for routine workloads.

Yes. AI tools turn a request such as “speed up customer searches by email and signup date” into a working CREATE INDEX statement, recommend column order, and explain the expected impact on read and write throughput.

Summarize this post with: