MySQL: MySQL Index Basics: Creation and Management

Last updated: 2026-08-26

Indexes are key to optimizing database performance—a query without an index is like looking up a word in a dictionary without consulting the table of contents.

This lesson explains the principles behind indexes, as well as how to create and manage them.

1. What You'll Learn



2. Real-Life Scenarios

(1) Pain Point: Queries are too slow

1 million user records, search by email address:

SQL
SELECT * FROM users WHERE email = 'alice@email.com';
-- Execution time: 2.5 seconds (Full Table Scan)

(2) Solutions for Indexes

SQL
CREATE INDEX idx_email ON users(email);
-- Search again: 0.003 seconds (Index Lookup)
Dimension Unindexed Indexed
Query Method Full Table Scan B+Tree Lookup
1 million-row query 2–5 seconds < 0.01 seconds
Write Performance No additional overhead Slightly slower (index maintenance required)


3. How Indexes Work

(1) B+Tree Structure

100%
graph TB
    R[Root Node<br/>10 | 30 | 50] --> L1[1-10]
    R --> L2[11-30]
    R --> L3[31-50]
    R --> L4[51+]
    L1 --> D1[Data: 1,3,5,7,9]
    L1 --> D2[Data: 2,4,6,8,10]
    L2 --> D3[Data: 11,15,20]
    L2 --> D4[Data: 25,28,30]
    L3 --> D5[Data: 31,35,40]
    L3 --> D6[Data: 45,48,50]

(2) Index Types

Type Description Use Cases
B+Tree Index Default Index Type Equal/Range/Sorted
Hash Index Hash Table Equality Query (Memory Engine)
Full-Text Index Text Search Article Content Search
Spatial Index GIS Data Geolocation Query


4. Creating Indexes

▶ Example: Creating an Index

Output:

TEXT 📖 Display only
Query OK, 0 rows affected
Records: 0  Duplicates: 0  Warnings: 0

Query OK, 0 rows affected
Records: 0  Duplicates: 0  Warnings: 0

Query OK, 0 rows affected
Records: 0  Duplicates: 0  Warnings: 0

Query OK, 0 rows affected
Records: 0  Duplicates: 0  Warnings: 0

Query OK, 0 rows affected
Records: 0  Duplicates: 0  Warnings: 0
SQL
-- Methods1:CREATE INDEX
CREATE INDEX idx_email ON users(email);

-- Unique Index
CREATE UNIQUE INDEX idx_email ON users(email);

-- Methods2:ALTER TABLE
ALTER TABLE users ADD INDEX idx_username (username);

-- Composite Index(Composite Index)
CREATE INDEX idx_name_email ON users(username, email);

-- Prefix Index
CREATE INDEX idx_email_prefix ON users(email(10));

Output:

TEXT 📖 Display only
Output displayed


5. View the Index

▶ Example: Viewing Index Information

SQL
-- View all indexes on the table
SHOW INDEX FROM users;

-- View Index Information
SHOW INDEX FROM users\G
▶ Try it Yourself
💡 \G is a MySQL command-line client directive that displays query results vertically. It only works in the mysql CLI, not in application code or GUI tools.

Output:

TEXT 📖 Display only
+-------+------------+----------+--------------+-------------+
| Table | Key_name   | Seq_in_index | Column_name | Index_type |
+-------+------------+--------------+-------------+------------+
| users | PRIMARY    |            1 | id          | BTREE      |
| users | idx_email  |            1 | email       | BTREE      |
+-------+------------+--------------+-------------+------------+


6. Deleting an Index

▶ Example: Deleting an Index

SQL
-- Methods1:DROP INDEX
DROP INDEX idx_email ON users;

-- Methods2:ALTER TABLE
ALTER TABLE users DROP INDEX idx_email;

-- Delete Primary Key
ALTER TABLE users DROP PRIMARY KEY;
▶ Try it Yourself

Output:

TEXT 📖 Display only
Output displayed


7. Use Cases for Indexes

Scenario Should an index be created? Reason
WHERE Condition Field ✅ Speed Up Query
JOIN Field ✅ Accelerated Join
ORDER BY field ✅ Avoid sorting
GROUP BY Field ✅ Accelerated Grouping
Highly Selective Field ✅ High Discrimination
Frequent field updates ❌ High maintenance costs
Low-selectivity fields ❌ Such as gender (M/F)
Tables with small amounts of data ❌ Full table scan is faster

❓ FAQ

Q Is it better to have more indexes?
A No. Indexes take up space and reduce write performance. Create indexes only on fields that are frequently queried.
Q Are primary keys automatically indexed?
A Yes. A PRIMARY KEY automatically creates a clustered index, and a UNIQUE key automatically creates a unique index.
Q How do I determine whether an index is needed?
A Use EXPLAIN to analyze the query plan and see if an index is being used.
Q Is it better to have more indexes?
A No. Indexes slow down write performance, so it’s recommended that a single table have no more than 5–6 indexes.
Q Is a primary key always a clustered index?
A In InnoDB, yes—the primary key is a clustered index. In MyISAM, the primary key is a non-clustered index.

📖 Summary


📝 Exercises

  1. Basic Question (Difficulty ⭐): Create a unique index on the email field of the users table.

  2. Advanced Problem (Difficulty ⭐⭐): Create a composite index (department, salary) and verify the leftmost prefix principle.

  3. Challenge Question (Difficulty: ⭐⭐⭐): Use EXPLAIN to compare the performance differences between queries with and without indexes.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏