search
HomeDatabaseMysql TutorialWhat are the types of indexes in mysql database? Establishment Methods and Advantages and Disadvantages

This article will focus on describing the four types of masql database indexes. How to create a database index? Columns appearing in WHERE and JOIN need to be indexed, but not entirely so, because MySQL only does , >=, BETWEEN, IN, and sometimes LIKE. Use indexes. I hope this article can help everyone. First, let’s understand what an index is. To sum it up in one sentence: Index is the key to fast search.

The establishment of MySQL index is very important for the efficient operation of MySQL. The following introduces several common MySQL index types

In database tables, indexing fields can greatly improve query speed. Suppose we create a mytable table:

The code is as follows:

CREATE TABLE mytable( ID INT NOT NULL, username VARCHAR(16) NOT NULL );

We randomly There are 10,000 records inserted, including one: 5555, admin.

When searching for the record of username="admin" SELECT * FROM mytable WHERE username='admin';, if an index has been established on username, MySQL can accurately find the record without any scanning. On the contrary, MySQL will scan all records, that is, 10,000 records will be queried.

Indexes are divided into single column indexes and combined indexes. A single-column index means that an index only contains a single column. A table can have multiple single-column indexes, but this is not a combined index. Combined index, that is, one index contains multiple columns.

MySQL index types include:

1. Ordinary index

This is the most basic index, it has no restrictions. It has the following creation methods:

1. Create an index

The code is as follows:

CREATE INDEX indexName ON mytable(username(length));

If it is CHAR, VARCHAR type, length can be less than the actual length of the field; if it is BLOB and TEXT type, length must be specified, the same below.

2. Modify the table structure

The code is as follows:
ALTER mytable ADD INDEX [indexName] ON (username(length)) -- Specify it directly when creating the table

CREATE TABLE mytable( ID INT NOT NULL, username VARCHAR(16) NOT NULL, INDEX [indexName] (username(length)) );

-- Syntax to delete index:

DROP INDEX [indexName] ON mytable;

2. Unique index

It is similar to the previous ordinary index, except that the value of the index column must be unique, but it is allowed There is a null value. In the case of a composite index, the combination of column values ​​must be unique. It has the following creation methods:

The code is as follows:

CREATE UNIQUE INDEX indexName ON mytable(username(length))
-- Modify the table structure
ALTER mytable ADD UNIQUE [indexName] ON (username(length))
-- Directly specify
CREATE TABLE mytable when creating the table( ID INT NOT NULL, username VARCHAR(16) NOT NULL, UNIQUE [indexName] (username(length) ) );

3. Primary key index

It is a special unique index that does not allow null values. Generally, the primary key index is created at the same time when creating the table:

The code is as follows:

CREATE TABLE mytable( ID INT NOT NULL, username VARCHAR(16) NOT NULL, PRIMARY KEY(ID) ) ;

Of course you can also use the ALTER command. Remember: a table can only have one primary key.

4. Combined index

In order to vividly compare single column index and combined index, add multiple fields to the table:

The code is as follows:

CREATE TABLE mytable( ID INT NOT NULL, username VARCHAR(16) NOT NULL, city VARCHAR(50) NOT NULL, age INT NOT NULL );

In order to further extract the efficiency of MySQL, it is necessary to Consider building a composite index. Just build name, city, age into an index:

The code is as follows:

ALTER TABLE mytable ADD INDEX name_city_age (name(10),city,age);[code]
When creating the table, the usernname length is 16, and 10 is used here. This is because generally the name length will not exceed 10, which will speed up the index query, reduce the size of the index file, and improve the update speed of INSERT.

If you create single-column indexes on usernname, city, and age respectively, so that the table has three single-column indexes, the query efficiency will be very different from the above combined index, which is far lower than our combined index. . Although there are three indexes at this time, MySQL can only use the single-column index that it thinks seems to be the most efficient.

Establishing such a combined index is actually equivalent to establishing the following three sets of combined indexes:

usernname,city,age usernname,city usernname Why is there no combined index like city and age? This is a result of the "leftmost prefix" of the MySQL composite index. The simple understanding is to only start the combination from the leftmost one. Not only queries containing these three columns will use this combined index, the following SQL will use this combined index:
[code]
SELECT * FROM mytable WHREE username="admin" AND city ="Zhengzhou" SELECT * FROM mytable WHREE username="admin"

The following ones will not be used:

The code is as follows:
SELECT * FROM mytable WHREE age=20 AND city="Zhengzhou" SELECT * FROM mytable WHREE city="Zhengzhou"

5. How to create an index

So far we have learned how to create an index, then we Under what circumstances do you need to create an index? Generally speaking, columns appearing in WHERE and JOIN need to be indexed, but this is not entirely true because MySQL only indexes , >=, BETWEEN, IN, and sometimes LIKE will use the index. For example:

The code is as follows:

SELECT t.Name FROM mytable t LEFT JOIN mytable m ON t.Name=m.username WHERE m.age=20 AND m.city='Zhengzhou'

At this point, it is necessary to index city and age. Since the userame of the mytable table also appears in the JOIN clause, it is also necessary to index it.

I just mentioned that only LIKE needs to be indexed at certain times. Because MySQL will not use the index when making queries starting with wildcard characters % and _. For example, the following sentence will use the index:

The code is as follows:
SELECT * FROM mytable WHERE username like'admin%'
The next sentence will not use the index:

The code is as follows:

SELECT * FROM mytable WHEREt Name like'�min'

Therefore, you should pay attention to the above differences when using LIKE.

6. Index Disadvantages

The above all talk about the benefits of using indexes, but excessive use of indexes will cause abuse. Therefore, the index will also have its shortcomings:

1. Although the index greatly improves the query speed, it will also reduce the speed of updating the table, such as INSERT, UPDATE and DELETE on the table. Because when updating the table, MySQL not only needs to save the data, but also save the index file.

2. Creating an index file will occupy disk space. Generally, this problem is not serious, but if you create multiple combined indexes on a large table, the index file will expand quickly.

Indexes are only one factor in improving efficiency. If your MySQL has a large amount of data tables, you need to spend time researching and building the best indexes or optimizing query statements.

7. Things to note when using indexes:

When using indexes, there are some tips and precautions:

1. The index will not contain Columns with NULL values

As long as the column contains NULL values, they will not be included in the index. As long as one column in the composite index contains a NULL value, then this column will be invalid for the composite index. Therefore, when designing the database, we should not let the default value of the field be NULL.

2. Use short index

to index the string. If possible, you should specify a prefix length. For example, if you have a CHAR(255) column, if most values ​​are unique within the first 10 or 20 characters, then do not index the entire column. Short indexes not only improve query speed but also save disk space and I/O operations.

3. Index column sorting

MySQL query only uses one index, so if the index has been used in the where clause, the columns in order by will not use the index. Therefore, do not use sorting operations when the default sorting of the database can meet the requirements; try not to include sorting of multiple columns. If necessary, it is best to create composite indexes for these columns.

4.Like statement operation

Generally, the use of like operation is not encouraged. If it must be used, how to use it is also a problem. Like “�a%” will not use the index but like “aaa%” will.

5. Do not perform operations on columns

The code is as follows:
select * from users where YEAR(adddate)

will be in each row This will cause the index to fail and perform a full table scan, so we can change it to:

The code is as follows:

select * from users where adddate

6. Do not use NOT IN and operations

Above, the MySQL index types are introduced. I hope to be helpful.

Two methods of indexing:

B-tree index

Note: It is called btree index, the big aspect Look, they all use balanced trees, but in terms of specific implementation, each storage engine is slightly different. For example, strictly speaking, the NDB engine uses T-tree
Myisam, in innodb, uses B-tree index by default , the theoretical query time complexity of B-tree is O(log2 (N-1)), N is the number of rows in the data table

hash index
In tables using memory storage engine, the default is hash The theoretical query time complexity of index and hash is O(1)

Related recommendations:

Detailed explanation of how to use mysql to create indexes and analysis of advantages and disadvantages

Advantages and Disadvantages of Indexing Page 1/2

The above is the detailed content of What are the types of indexes in mysql database? Establishment Methods and Advantages and Disadvantages. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
MySQL: An Introduction to the World's Most Popular DatabaseMySQL: An Introduction to the World's Most Popular DatabaseApr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

The Importance of MySQL: Data Storage and ManagementThe Importance of MySQL: Data Storage and ManagementApr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system suitable for data storage, management, query and security. 1. It supports a variety of operating systems and is widely used in Web applications and other fields. 2. Through the client-server architecture and different storage engines, MySQL processes data efficiently. 3. Basic usage includes creating databases and tables, inserting, querying and updating data. 4. Advanced usage involves complex queries and stored procedures. 5. Common errors can be debugged through the EXPLAIN statement. 6. Performance optimization includes the rational use of indexes and optimized query statements.

Why Use MySQL? Benefits and AdvantagesWhy Use MySQL? Benefits and AdvantagesApr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

Describe InnoDB locking mechanisms (shared locks, exclusive locks, intention locks, record locks, gap locks, next-key locks).Describe InnoDB locking mechanisms (shared locks, exclusive locks, intention locks, record locks, gap locks, next-key locks).Apr 12, 2025 am 12:16 AM

InnoDB's lock mechanisms include shared locks, exclusive locks, intention locks, record locks, gap locks and next key locks. 1. Shared lock allows transactions to read data without preventing other transactions from reading. 2. Exclusive lock prevents other transactions from reading and modifying data. 3. Intention lock optimizes lock efficiency. 4. Record lock lock index record. 5. Gap lock locks index recording gap. 6. The next key lock is a combination of record lock and gap lock to ensure data consistency.

What are common causes of poor MySQL query performance?What are common causes of poor MySQL query performance?Apr 12, 2025 am 12:11 AM

The main reasons for poor MySQL query performance include not using indexes, wrong execution plan selection by the query optimizer, unreasonable table design, excessive data volume and lock competition. 1. No index causes slow querying, and adding indexes can significantly improve performance. 2. Use the EXPLAIN command to analyze the query plan and find out the optimizer error. 3. Reconstructing the table structure and optimizing JOIN conditions can improve table design problems. 4. When the data volume is large, partitioning and table division strategies are adopted. 5. In a high concurrency environment, optimizing transactions and locking strategies can reduce lock competition.

When should you use a composite index versus multiple single-column indexes?When should you use a composite index versus multiple single-column indexes?Apr 11, 2025 am 12:06 AM

In database optimization, indexing strategies should be selected according to query requirements: 1. When the query involves multiple columns and the order of conditions is fixed, use composite indexes; 2. When the query involves multiple columns but the order of conditions is not fixed, use multiple single-column indexes. Composite indexes are suitable for optimizing multi-column queries, while single-column indexes are suitable for single-column queries.

How to identify and optimize slow queries in MySQL? (slow query log, performance_schema)How to identify and optimize slow queries in MySQL? (slow query log, performance_schema)Apr 10, 2025 am 09:36 AM

To optimize MySQL slow query, slowquerylog and performance_schema need to be used: 1. Enable slowquerylog and set thresholds to record slow query; 2. Use performance_schema to analyze query execution details, find out performance bottlenecks and optimize.

MySQL and SQL: Essential Skills for DevelopersMySQL and SQL: Essential Skills for DevelopersApr 10, 2025 am 09:30 AM

MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function