Design and use of mysql index
Design and use of indexes
5.1 Overview of Mysql indexes
All MySQL column types can be indexed. Using indexes on related columns is the best way to improve the performance of SELECT operations. Define the maximum number of indexes and maximum index length for each table according to the storage engine. All storage engines support at least 16 indexes per table, with a total index length of at least 256 bytes. Most storage engines have higher limits.
In MySQL 5.1, for MyISAM and InnoDB tables, prefixes can be up to 1000 bytes long. Note that the limit of a prefix should be measured in bytes, whereas the prefix length in the CREATE TABLE statement is interpreted as a number of characters. Be sure to consider this when specifying a prefix length for columns that use multibyte character sets.
You can also create FULLTEXT indexes. The index can be used for full-text search. Only the MyISAM storage engine supports FULLTEXT indexes, and only for CHAR, VARCHAR, and TEXT columns. Indexes are always performed on the entire column, partial (prefix) indexes are not supported. Indexes can also be created on spatial column types. Only the MyISAM storage engine supports spatial types. Spatial indexes use R-trees. By default, the MEMORY (HEAP) storage engine uses hash indexes, but B-tree indexes are also supported.
5.2 Principles of index design
1. The index column to be searched is not necessarily the column to be selected. In other words, the most suitable columns for indexing are the columns that appear in the WHERE clause, or the columns specified in the join clause, rather than the columns that appear in the select list after the SELECT keyword.
2. Use unique index. Consider the distribution of values in a column. Indexes work best for columns with unique values and worst for columns with multiple duplicate values. For example, the column holding age has different values, making it easy to distinguish between rows.
The column used to record gender only contains "M" and "F", so indexing this column is of little use (no matter which value is searched, about half of the rows will be obtained)
3. Use a short index. If you are indexing a string, you should specify a prefix length, and this should be done whenever possible.
For example, if you have a CHAR(200) column, if most values are unique within the first 10 or 20 characters, then don't index the entire column. Indexing the first 10 or 20 characters can save a lot of index space and may make queries faster. Smaller indexes involve less disk I/O, and shorter values compare faster.
More importantly, for shorter key values, the blocks in the index cache can hold more key values, so MySQL can also hold more values in memory. This increases the likelihood of finding the row without reading larger blocks in the index.
(Of course, some common sense should be used. For example, indexing only by the first character of the column value is unlikely to be of much benefit, because there will not be many different values in this index.)
4. Use the leftmost prefix. When you create an n-column index, you actually create n indexes that MySQL can use.
A multi-column index can function as several indexes because the leftmost set of columns in the index can be used to match rows. Such a set of columns is called a leftmost prefix. (This is different from indexing the prefix of a column, which uses the first n characters of the column as the index value.)
5. Don’t over-index. Don't think that "the more indexes, the better". It's wrong to use indexes for everything. Each additional index takes up additional disk space and reduces the performance of write operations, which we have already introduced. When the contents of the table are modified, the index must be updated and sometimes may need to be reconstructed. Therefore, the more indexes, the longer it takes. If you have an index that is rarely or never used, it will unnecessarily slow down modifications to the table.
In addition, MySQL must consider each index when generating an execution plan, which also takes time. Creating redundant indexes creates more work for query optimization. Too many indexes may also prevent MySQL from selecting the best index to use. Keeping only the required indexes facilitates query optimization. If you want to add an index to an already indexed table, you should consider whether the index to be added is the leftmost index of an existing multi-column index. If so, don't bother adding this index because it already exists.
6. Consider the types of comparisons you make on columns. Indexes can be used with the " < ", " < = ", " = ", " > = ", " >" and BETWEEN operations. Indexes are also used in LIKE operations when the pattern has a literal prefix. If a column is only used for other types of operations (such as STRCMP()), there is no value in indexing it.
5.3 btree index and hash index
For BTREE and HASH index, when using =, <=>, IN, IS NULL or IS NOT NULL operators, the comparison relationship between key elements and constant values corresponds to a range condition. Hash indexes have some additional features: they are only used for equality comparisons using the = or <=> operators (but fast). The optimizer cannot use hash indexes to speed up ORDER BY operations.
(This type of index cannot be used to search for the next entry in sequence). MySQL cannot determine approximately how many rows there are between two values (this is used by the range optimizer to determine which index to use). If you change a MyISAM table to a hash-indexed MEMORY table, some queries will be affected. Only the entire keyword can be used to search a row. (With a B-tree index, the leftmost prefix of any key can be used to find the row).
For BTREE index, when using >, <, >=, <=, BETWEEN, != or <>, or LIKE 'pattern' (where 'pattern' does not start with a wildcard) operator, The comparison relationship between key elements and constant values corresponds to a range condition.
"Constant value" refers to: a constant in a query string, a const in the same join or a column in the system table, the result of an uncorrelated subquery, an expression composed entirely of subexpressions of the previous type
Here are some Examples of queries with range conditions in the WHERE clause:
The following range queries are applicable to btree indexes and hash indexes
SELECT * FROM t1WHEREkey_col = 1ORkey_col IN (15,18,20);
The following range queries are applicable to btree indexes
SELECT * FROM t1WHERE key_col > A row with a specific value in the column. Without using an index, MySQL must start at record 1 and read through the entire table until it finds the relevant row. The larger the table, the more time it takes. If the queried column in the table has an index, MySQL can quickly get to a point where it searches the middle of the data file without having to look at all the data. For example, if a table has 1000 rows, this is at least 100 times faster than sequential reading. Note that if you need to access a large portion of the rows, sequential reading is much faster because at that point we avoid a disk seek.
Most MySQL indexes (PRIMARY KEY, UNIQUE, INDEX and FULLTEXT) are stored in B-trees. Only spatial column type indexes use R-tree, and MEMORY tables also support hash indexes.
For a detailed explanation of the circumstances under which the database will use indexes and the circumstances under which the database will not use indexes, please refer to the relevant chapters of the optimization chapter, which will not be repeated here.
If you want to get more related articles, please pay attention to php Chinese website (www.php.cn)!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

According to news on April 17, HMD teamed up with the well-known beer brand Heineken and the creative company Bodega to launch a unique flip phone - The Boring Phone. This phone is not only full of innovation in design, but also returns to nature in terms of functionality, aiming to lead people back to real interpersonal interactions and enjoy the pure time of drinking with friends. Boring mobile phone adopts a unique transparent flip design, showing a simple yet elegant aesthetic. It is equipped with a 2.8-inch QVGA display inside and a 1.77-inch display outside, providing users with a basic visual interaction experience. In terms of photography, although it is only equipped with a 30-megapixel camera, it is enough to handle simple daily tasks.

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

According to news on April 26, ZTE’s 5G portable Wi-Fi U50S is now officially on sale, starting at 899 yuan. In terms of appearance design, ZTE U50S Portable Wi-Fi is simple and stylish, easy to hold and pack. Its size is 159/73/18mm and is easy to carry, allowing you to enjoy 5G high-speed network anytime and anywhere, achieving an unimpeded mobile office and entertainment experience. ZTE 5G portable Wi-Fi U50S supports the advanced Wi-Fi 6 protocol with a peak rate of up to 1800Mbps. It relies on the Snapdragon X55 high-performance 5G platform to provide users with an extremely fast network experience. Not only does it support the 5G dual-mode SA+NSA network environment and Sub-6GHz frequency band, the measured network speed can even reach an astonishing 500Mbps, which is easily satisfactory.

According to news on April 3, Taipower’s upcoming M50 Mini tablet computer is a device with rich functions and powerful performance. This new 8-inch small tablet is equipped with an 8.7-inch IPS screen, providing users with an excellent visual experience. Its metal body design is not only beautiful but also enhances the durability of the device. In terms of performance, the M50Mini is equipped with the Unisoc T606 eight-core processor, which has two A75 cores and six A55 cores, ensuring a smooth and efficient running experience. At the same time, the tablet is also equipped with a 6GB+128GB storage solution and supports 8GB memory expansion, which meets users’ needs for storage and multi-tasking. In terms of battery life, M50Mini is equipped with a 5000mAh battery and supports Ty

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension
