search
HomeDatabaseMysql TutorialMysql creates index to improve system running speed

Suppose we create a mytable table:
CREATE TABLE mytable( ID INT NOT NULL, username VARCHAR(16) NOT NULL ); We randomly insert 10,000 records into it, 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:
(7) Precautions for using indexes
When using indexes, there are some tips and precautions as follows:
◆The index will not contain columns with NULL values ​​
As long as the column contains NULL values, it will not Will 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 this composite index. Therefore, when designing the database, we should not let the default value of the field be NULL.
◆Use short indexes
to index the string, specifying a prefix length if possible. 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.
◆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.
◆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 “%aaa%” will not use the index but like “aaa%” will use the index.
◆Don’t operate on columns
select * from users where YEAR(adddate)select * from users where adddate◆Do not use NOT IN and operations
The above has introduced the MySQL index types.
(6) Disadvantages of indexes
The benefits of using indexes are mentioned above, but excessive use of indexes will cause abuse. Therefore, the index will also have its shortcomings:
◆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.
◆Creating index files 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 to improve efficiency. If your MySQL has a large data table, you need to spend time researching and building the best indexes or optimizing query statements.
(5) Timing to create an index
Now we have learned how to create an index, so under what circumstances do we 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:
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 time, you need to index city and age, because the mytable table The userame also appears in the JOIN clause, and it is necessary to index it.
I just mentioned that only certain LIKEs need to be indexed. Because MySQL will not use the index when making queries starting with wildcard characters % and _. For example, the following sentence will use the index:
SELECT * FROM mytable WHERE username like'admin%', but the next sentence will not use the index:
SELECT * FROM mytable WHEREt Name like'%admin' Therefore, you should pay attention to the above differences when using LIKE.
(4) Composite index
To visually compare single-column indexes and composite indexes, add multiple fields to the table:
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 establishing a combined index. Just build name, city, age into an index:
ALTER TABLE mytable ADD INDEX name_city_age (name(10),city,age); When creating the table, the length of usernname 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 username, city, and age respectively, so that the table has three single-column indexes, the query efficiency will be very different from the above-mentioned 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 are there no combined indexes 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:
SELECT * FROM mytable WHREE username="admin" AND city="Zhengzhou" SELECT * FROM mytable WHREE username="admin" The following ones will not be used:
SELECT * FROM mytable WHREE age=20 AND city="Zhengzhou" SELECT * FROM mytable WHREE city="Zhengzhou"
(3) Primary key index
It is A special unique index that does not allow null values. Generally, the primary key index is created when creating the table:
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.
(2) Unique index
It is similar to the previous ordinary index, except that the value of the index column must be unique, but null values ​​are allowed. In the case of a composite index, the combination of column values ​​must be unique. It has the following creation methods:
◆Create index
CREATE UNIQUE INDEX indexName ON mytable(username(length)) ◆Modify the table structure
ALTER mytable ADD UNIQUE [indexName] ON (username(length)) ◆Create the table directly Specify
CREATE TABLE mytable( ID INT NOT NULL, username VARCHAR(16) NOT NULL, UNIQUE [indexName] (username(length)) );
(1) Ordinary index
This is the most basic index, it has no restrictions. It has the following creation methods:
◆Create index
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.
◆Modify the table structure
ALTER mytable ADD INDEX [indexName] ON (username(length)) ◆Specify 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;
Index is the key to fast search. The establishment of MySQL index is very important for the efficient operation of MySQL. Here are some common MySQL index types.
In database tables, indexing fields can greatly improve query speed.

The above is the content of Mysql indexing to improve the running speed of the system. For more related articles, please pay attention to the PHP Chinese website (www.php.cn)!


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
What are the different storage engines available in MySQL?What are the different storage engines available in MySQL?Apr 26, 2025 am 12:27 AM

MySQLoffersvariousstorageengines,eachsuitedfordifferentusecases:1)InnoDBisidealforapplicationsneedingACIDcomplianceandhighconcurrency,supportingtransactionsandforeignkeys.2)MyISAMisbestforread-heavyworkloads,lackingtransactionsupport.3)Memoryengineis

What are some common security vulnerabilities in MySQL?What are some common security vulnerabilities in MySQL?Apr 26, 2025 am 12:27 AM

Common security vulnerabilities in MySQL include SQL injection, weak passwords, improper permission configuration, and unupdated software. 1. SQL injection can be prevented by using preprocessing statements. 2. Weak passwords can be avoided by forcibly using strong password strategies. 3. Improper permission configuration can be resolved through regular review and adjustment of user permissions. 4. Unupdated software can be patched by regularly checking and updating the MySQL version.

How can you identify slow queries in MySQL?How can you identify slow queries in MySQL?Apr 26, 2025 am 12:15 AM

Identifying slow queries in MySQL can be achieved by enabling slow query logs and setting thresholds. 1. Enable slow query logs and set thresholds. 2. View and analyze slow query log files, and use tools such as mysqldumpslow or pt-query-digest for in-depth analysis. 3. Optimizing slow queries can be achieved through index optimization, query rewriting and avoiding the use of SELECT*.

How can you monitor MySQL server health and performance?How can you monitor MySQL server health and performance?Apr 26, 2025 am 12:15 AM

To monitor the health and performance of MySQL servers, you should pay attention to system health, performance metrics and query execution. 1) Monitor system health: Use top, htop or SHOWGLOBALSTATUS commands to view CPU, memory, disk I/O and network activities. 2) Track performance indicators: monitor key indicators such as query number per second, average query time and cache hit rate. 3) Ensure query execution optimization: Enable slow query logs, record and optimize queries whose execution time exceeds the set threshold.

Compare and contrast MySQL and MariaDB.Compare and contrast MySQL and MariaDB.Apr 26, 2025 am 12:08 AM

The main difference between MySQL and MariaDB is performance, functionality and license: 1. MySQL is developed by Oracle, and MariaDB is its fork. 2. MariaDB may perform better in high load environments. 3.MariaDB provides more storage engines and functions. 4.MySQL adopts a dual license, and MariaDB is completely open source. The existing infrastructure, performance requirements, functional requirements and license costs should be taken into account when choosing.

How does MySQL's licensing compare to other database systems?How does MySQL's licensing compare to other database systems?Apr 25, 2025 am 12:26 AM

MySQL uses a GPL license. 1) The GPL license allows the free use, modification and distribution of MySQL, but the modified distribution must comply with GPL. 2) Commercial licenses can avoid public modifications and are suitable for commercial applications that require confidentiality.

When would you choose InnoDB over MyISAM, and vice versa?When would you choose InnoDB over MyISAM, and vice versa?Apr 25, 2025 am 12:22 AM

The situations when choosing InnoDB instead of MyISAM include: 1) transaction support, 2) high concurrency environment, 3) high data consistency; conversely, the situation when choosing MyISAM includes: 1) mainly read operations, 2) no transaction support is required. InnoDB is suitable for applications that require high data consistency and transaction processing, such as e-commerce platforms, while MyISAM is suitable for read-intensive and transaction-free applications such as blog systems.

Explain the purpose of foreign keys in MySQL.Explain the purpose of foreign keys in MySQL.Apr 25, 2025 am 12:17 AM

In MySQL, the function of foreign keys is to establish the relationship between tables and ensure the consistency and integrity of the data. Foreign keys maintain the effectiveness of data through reference integrity checks and cascading operations. Pay attention to performance optimization and avoid common errors when using them.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

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

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 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!