Table of Contents
Detailed explanation of MySQL index types
Home Database Mysql Tutorial What index types are there in mysql?

What index types are there in mysql?

Jun 27, 2022 pm 04:51 PM
mysql

Index types include: 1. B-tree index, so that each row in the table will have a corresponding value on the index; 2. Hash index, which can be obtained based on the hash value corresponding to the index column. The record row of the table; 3. Ordinary index, which allows inserting duplicate values ​​and null values ​​​​in the columns that define the index; 4. Unique index, which can avoid duplication of data; 5. Primary key index, which is an index created for the primary key field; 6. Spatial index is an index established on fields of spatial data type; 7. Full-text index is used to find keywords in text; 8. Single-column index, that is, the index only contains one column of the original table.

What index types are there in mysql?

The operating environment of this tutorial: windows7 system, mysql8 version, Dell G3 computer.

Detailed explanation of MySQL index types

The type of index is related to the storage engine, and the index types supported by each storage engine are not necessarily exactly the same. MySQL indexes can be classified from a storage method, a logical perspective, and a practical usage perspective.

Storage method distinction

According to different storage methods, commonly used indexes in MySQL are physically divided into B-tree indexes There are two types of indexes: and HASH indexes. Each of the two different types of indexes has its own different scope of application.

1) B-tree index

B-tree index is also called BTREE index, currently most Indexes are stored using B-tree indexes.

B-tree index is a typical data structure, which mainly contains the following components:

  • Leaf nodes: The entries contained directly point to the data rows in the table. Leaf nodes are connected to each other, and one leaf node has a pointer to the next leaf node.
  • Branch node: Contains entries pointing to other branch nodes or leaf nodes in the index.
  • Root node: A B-tree index has only one root node, which is actually the branch node located at the top of the tree.

Based on this tree data structure, each row in the table will have a corresponding value on the index. Therefore, when performing data query in the table, the row where the data is located can be located step by step according to the index value.

B-tree index can perform full key value, key value range and key value prefix query, and can also ORDER BY sort the query results. However, the B-tree index must follow the left prefix principle and the following constraints must be considered:

  • The query must start from the leftmost column of the index.
  • The query cannot skip an index column and must be matched from left to right.
  • The storage engine cannot use the columns to the right of the range condition in the index.

2) Hash Index

Hash (Hash) is generally translated as "hash", and some are directly transliterated into "hash", that is The input of any length (also called pre-mapping, pre-image) is transformed into a fixed-length output through a hash algorithm, and the output is the hash value.

Hash Index is also called Hash Index or HASH Index. MySQL currently only supports this type of index for the MEMORY storage engine and HEAP storage engine. Among them, the MEMORY storage engine can support B-tree indexes and HASH indexes, and uses HASH as the default index.

HASH index is not based on a tree data structure to find data, but obtains the record rows of the table based on the hash value corresponding to the index column. The biggest feature of hash index is fast access speed, but it also has the following shortcomings:

  • MySQL needs to read the value of the index column in the table to participate in hash calculation. Hash calculation It is a relatively time-consuming operation. In other words, building a hash index will take more time than a B-tree index.
  • Cannot use HASH index sorting.
  • HASH index only supports equality comparison, such as "=", "IN()" or "<=>".
  • HASH index does not support partial matching of keys, because the HASH value is calculated through the entire index value.

Logical distinction

According to the specific purpose of the index, the indexes in MySQL are logically divided into the following 5 categories:

1) Ordinary index

Ordinary index is the most basic index type in MySQL. It has no restrictions and its only task is to speed up the system's processing of data. Access speed.

Normal indexes allow duplicate values ​​and null values ​​to be inserted into the columns in which the index is defined.

When creating a normal index, the keywords usually used are INDEX or KEY.

Example 1

The following creates an index named index_id on the id field in the tb_student table.

CREATE INDEX index_id ON tb_student(id);
Copy after login

2) Unique index

唯一索引与普通索引类似,不同的是创建唯一性索引的目的不是为了提高访问速度,而是为了避免数据出现重复。

唯一索引列的值必须唯一,允许有空值。如果是组合索引,则列值的组合必须唯一。

创建唯一索引通常使用 UNIQUE 关键字。

例 2

下面在 tb_student 表中的 id 字段上建立名为 index_id 的索引,SQL 语句如下:

CREATE UNIQUE INDEX index_id ON tb_student(id);
Copy after login

其中,id 字段可以有唯一性约束,也可以没有。

3) 主键索引

顾名思义,主键索引就是专门为主键字段创建的索引,也属于索引的一种。

主键索引是一种特殊的唯一索引,不允许值重复或者值为空。

创建主键索引通常使用 PRIMARY KEY 关键字。不能使用 CREATE INDEX 语句创建主键索引。

4) 空间索引

空间索引是对空间数据类型的字段建立的索引,使用 SPATIAL 关键字进行扩展。

创建空间索引的列必须将其声明为 NOT NULL,空间索引只能在存储引擎为 MyISAM 的表中创建。

空间索引主要用于地理空间数据类型 GEOMETRY。对于初学者来说,这类索引很少会用到。

例 3

下面在 tb_student 表中的 line 字段上建立名为 index_line 的索引,SQL 语句如下:

CREATE SPATIAL INDEX index_line ON tb_student(line);
Copy after login

其中,tb_student 表的存储引擎必须是 MyISAM,line 字段必须为空间数据类型,而且是非空的。

5) 全文索引

全文索引主要用来查找文本中的关键字,只能在 CHAR、VARCHAR 或 TEXT 类型的列上创建。在 MySQL 中只有 MyISAM 存储引擎支持全文索引。

全文索引允许在索引列中插入重复值和空值。

不过对于大容量的数据表,生成全文索引非常消耗时间和硬盘空间。

创建全文索引使用 FULLTEXT 关键字。

例 4

在 tb_student 表中的 info 字段上建立名为 index_info 的全文索引,SQL 语句如下:

CREATE FULLTEXT INDEX index_info ON tb_student(info);
Copy after login

其中,index_info 的存储引擎必须是 MyISAM,info 字段必须是 CHAR、VARCHAR 和 TEXT 等类型。

实际使用区分

索引在逻辑上分为以上 5 类,但在实际使用中,索引通常被创建成单列索引和组合索引。

1)单列索引

单列索引就是索引只包含原表的一个列。在表中的单个字段上创建索引,单列索引只根据该字段进行索引。

单列索引可以是普通索引,也可以是唯一性索引,还可以是全文索引。只要保证该索引只对应一个字段即可。

例 5

下面在 tb_student 表中的 address 字段上建立名为 index_addr 的单列索引,address 字段的数据类型为 VARCHAR(20),索引的数据类型为 CHAR(4)。SQL 语句如下:

CREATE INDEX index_addr ON tb_student(address(4));
Copy after login

这样,查询时可以只查询 address 字段的前 4 个字符,而不需要全部查询。

2)多列索引

组合索引也称为复合索引多列索引。相对于单列索引来说,组合索引是将原表的多个列共同组成一个索引。多列索引是在表的多个字段上创建一个索引。该索引指向创建时对应的多个字段,可以通过这几个字段进行查询。但是,只有查询条件中使用了这些字段中第一个字段时,索引才会被使用。

例如,在表中的 id、name 和 sex 字段上建立一个多列索引,那么,只有查询条件使用了 id 字段时,该索引才会被使用。

例 6

下面在 tb_student 表中的 name 和 address 字段上建立名为 index_na 的索引,SQL 语句如下:

CREATE INDEX index_na ON tb_student(name,address);
Copy after login

该索引创建好了以后,查询条件中必须有 name 字段才能使用索引。

提示:一个表可以有多个单列索引,但这些索引不是组合索引。一个组合索引实质上为表的查询提供了多个索引,以此来加快查询速度。比如,在一个表中创建了一个组合索引(c1,c2,c3),在实际查询中,系统用来实际加速的索引有三个:单个索引(c1)、双列索引(c1,c2)和多列索引(c1,c2,c3)。

【相关推荐:mysql视频教程

The above is the detailed content of What index types are there in mysql?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 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.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 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.

How to connect to the database of apache How to connect to the database of apache Apr 13, 2025 pm 01:03 PM

Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

How to start mysql by docker How to start mysql by docker Apr 15, 2025 pm 12:09 PM

The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

How to install mysql in centos7 How to install mysql in centos7 Apr 14, 2025 pm 08:30 PM

The key to installing MySQL elegantly is to add the official MySQL repository. The specific steps are as follows: Download the MySQL official GPG key to prevent phishing attacks. Add MySQL repository file: rpm -Uvh https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm Update yum repository cache: yum update installation MySQL: yum install mysql-server startup MySQL service: systemctl start mysqld set up booting

See all articles