View creation and deletion of MySQL indexes

From: http://blog.chinaunix.net/uid-25063573-id-3032578.html


1. The role of the index
In the index column, in addition to the above-mentioned ordered search, the database uses a variety of fast positioning technologies, which can greatly improve the query efficiency. Especially when the amount of data is very large and the query involves multiple tables, the use of indexes can often speed up the query by thousands of times.

For example, there are three unindexed tables t1, t2, and t3, which only contain columns c1, c2, and c3. Each table consists of 1,000 rows of data, which are values ​​from 1 to 1,000. Find the query that corresponds to rows with equal values. As follows.


SELECT c1,c2,c3 FROM t1,t2,t3 WHERE c1=c2 AND c1=c3

The result of this query should be 1000 rows, each row contains 3 equal values. To process this query without an index, all combinations of all 3 tables must be found in order to arrive at those rows that match the WHERE clause. And the number of possible combinations is 1000×1000×1000 (one billion), obviously the query will be very slow.

If each table is indexed, the query process can be greatly accelerated. A query using an index is processed as follows.

(1) Select the first row from table t1 and view the data contained in this row.

(2) Using the index on table t2, directly locate the row in t2 that matches the value of t1. Similarly, using the index on table t3, directly locate the row in t3 that matches the value from t1.

(3) Scan the next row of table t1 and repeat the previous process until all rows in t1 are traversed.

In this case, a full scan of table t1 is still performed, but index lookups on tables t2 and t3 can be performed to directly fetch rows from those tables, a million times faster than if no indexes were used.

Using indexes, MySQL speeds up the search for rows that satisfy the condition in the WHERE clause, and in multi-table join queries, it speeds up matching with rows in other tables when performing joins.

2. Create an
index You can create an index when you execute the CREATE TABLE statement, or you can use CREATE INDEX or ALTER TABLE alone to add an index to the table.

1. ALTER TABLE
ALTER TABLE is used to create ordinary, UNIQUE, or PRIMARY KEY indexes.



ALTER TABLE table_name ADD INDEX index_name (column_list)

ALTER TABLE table_name ADD UNIQUE (column_list)

ALTER TABLE table_name ADD PRIMARY KEY (column_list)



where table_name is the name of the table to be indexed, and column_list indicates which columns are to be indexed. Separate them with commas. The index name index_name is optional. By default, MySQL will assign a name based on the first index column. Additionally, ALTER TABLE allows multiple tables to be altered in a single statement, so multiple indexes can be created at the same time.

2. CREATE INDEX
CREATE INDEX can add ordinary or UNIQUE indexes to the table.



CREATE INDEX index_name ON table_name (column_list)

CREATE UNIQUE INDEX index_name ON table_name (column_list)



table_name, index_name, and column_list have the same meaning as in the ALTER TABLE statement, the index name is not optional. Also, PRIMARY KEY indexes cannot be created with the CREATE INDEX statement.

3. Index Type
When creating an index, you can specify whether the index can contain duplicate values. If not included, the index should be created as a PRIMARY KEY or UNIQUE index. For single-column unique indexes, this guarantees that a single column does not contain duplicate values. For multi-column unique indexes, the combination of multiple values ​​is guaranteed not to be repeated.

PRIMARY KEY indexes are very similar to UNIQUE indexes. In fact, a PRIMARY KEY index is just a UNIQUE index with the name PRIMARY. This means that a table can contain only one PRIMARY KEY, because it is impossible to have two indexes with the same name in a table.

The following SQL statement adds a PRIMARY KEY index on the sid to the students table.



ALTER TABLE students ADD PRIMARY KEY (sid)



4. Drop the index You
can use the ALTER TABLE or DROP INDEX statement to drop the index. Similar to the CREATE INDEX statement, DROP INDEX can be handled as a single statement inside ALTER TABLE with the following syntax.



DROP INDEX index_name ON talbe_name

ALTER TABLE table_name DROP INDEX index_name

ALTER TABLE table_name DROP PRIMARY KEY



Among them, the first two statements are equivalent, delete the index index_name in table_name.

The third statement is only used when dropping a PRIMARY KEY index, because a table can only have one PRIMARY KEY index, so there is no need to specify an index name. If no PRIMARY KEY index is created, but the table has one or more UNIQUE indexes, MySQL will drop the first UNIQUE index.

Indexes are affected if a column is removed from the table. For multi-column indexes, if you delete one of the columns, the column will also be deleted from the index. If you drop all the columns that make up the index, the entire index will be dropped.



5. View index

mysql> show index from tblname;

mysql> show keys from tblname;

  · Table

  name.

  · Non_unique

  0 if the index cannot contain duplicate words. 1 if it can.

  · The name of the Key_name

  index.   · Column sequence number in the

  Seq_in_index index, starting from 1.   · Column_name   column name.   · How the Collation   column is stored in the index. In MySQL, there are values ​​'A' (ascending) or NULL (no sort).   · An estimate of the number of unique values ​​in the   Cardinality index. Updates can be made by running ANALYZE TABLE or myisamchk -a. Cardinality is counted against statistics stored as integers, so even for small tables the value does not have to be exact. The larger the cardinality, the greater the chance that MySQL will use that index when doing a union.   · Sub_part   If the column is only partially indexed, the number of characters indexed. NULL if the entire column is indexed.   · Packed





















  Indicates how the keyword is compressed. NULL if not compressed.

  · Null

  contains YES if the column contains NULL. If not, the column contains NO.

  · Index_type

  used index method (BTREE, FULLTEXT, HASH, RTREE).

  · Comment

6. Under what circumstances use
       the primary key of the index table
Automatically create a unique index such as the field unique constraint

of the hbs_bh (user ID number) table in zl_yhjbqk (basic user information) ORACLE uses the index to ensure the integrity of the data As lc_hj (process link) lc_bh+hj_sx (process number + link sequence) fields for direct conditional query Fields used for conditional constraints in SQL such as qc_bh (area book number) in zl_yhjbqk (basic user information) select * from zl_yhjbqk where qc_bh='7001' Fields associated with other tables in the query often establish foreign key relationships, such as jldb_bh (metering point table number) in zl_ydcf (electricity consumption) select * from zl_ydcf a,zl_yhdb b where a.jldb_bh=b.jldb_bh and b. jldb_bh='540100214511'The field sorted in the query If the sorted field is accessed through the index, it will greatly improve the sorting speed



























select * from zl_yhjbqk order by qc_bh (build qc_bh index)

select * from zl_yhjbqk where qc_bh='7001' order by cb_sx (build qc_bh+cb_sx index, note: just an index, including qc_bh and cb_sx fields)

statistics or grouping in query Statistical fields

select max(hbs_bh) from zl_yhjbqk

select qc_bh,count(*) from zl_yhjbqk group by qc_bh Under

what circumstances should no or less indexes be

built

If there are too few records in a table, if there are only 5 records in a table, use indexes to access records , then you need to access the index table first, and then access the data table through the index table. Generally, the index table and the data table are not in the same data block. In this case, ORACLE needs to read the data block back and forth at least twice. Without indexing, ORACLE will read all the data at one time, and the processing speed will obviously be faster than using indexes.

For example, the table zl_sybm (using department) generally has only a few records. Building an index on any field except the primary key will not result in performance optimization. In fact, if you perform statistical analysis on this table, ORACLE will not use it. Indexes, instead perform full table accesses automatically. For example:

select * from zl_sybm where sydw_bh='5401' (building an index on sydw_bh will not produce performance optimization) Tables that are

frequently inserted, deleted, and modified

For some frequently processed business tables, indexes should be minimized if the query allows, such as zl_yhbm, gc_dfss, gc_dfys, gc_fpdy and other business tables.

Table fields with duplicated and evenly distributed data

If a table has 100,000 rows of records, a field A has only two values ​​of T and F, and the distribution probability of each value is about 50%, then building an index on the field A of this table will generally not improve the query speed of the database. .

Table fields that are often queried together with the main field but have many index values ​​in the main field,

such as gc_dfss (electricity bills actually collected) table, often query a specific transaction by charging serial number, household ID number, meter reading date, electricity bill occurrence year and month, and operation flag. In the case of collection, if all fields are built in an index, it will increase the time for data modification, insertion, and deletion. In fact, if a collection is analyzed by the charging serial number index, the records have been reduced to only a few. If the query is indexed by the following fields, it will not have much impact on performance.

Items to build indexes for tens of millions of MySQL databases and means to improve performance

1. Matters needing attention:

First of all, you should consider whether the table space and disk space are sufficient. We know that an index is also a kind of data, and it will inevitably take up a lot of table space when creating an index. Therefore, the first consideration when building an index on a large table is the space capacity issue.

Secondly, the table needs to be locked when the index is established, so it should be noted that the operation is performed when the business is idle.

2. Performance adjustment:

The first consideration is disk I/O. Physically, the index and data should be spread out as far as possible on different disks (regardless of the array). Logically, the data tablespace is separate from the index tablespace. This is the basic guideline that should be followed when indexing.

Secondly, we know that the entire table needs to be scanned when the index is established. Therefore, we should consider increasing the value of the initialization parameter db_file_multiblock_read_count. Typically set to 32 or greater.

Thirdly, in addition to full table scan, index building also needs to perform a large number of sorting operations on the data. Therefore, the size of the sorting area should be adjusted.

    Before 9i, you can increase the size of sort_area_size at the session level, for example, set it to 100m or more.

    After 9i, if the value of the initialization parameter workarea_size_policy is TRUE, the sorting area is automatically allocated from pga_aggregate_target.

Finally, when building an index, you can add the nologging option. In order to reduce a large number of redo generated during the indexing process, thereby improving the execution speed.

Problems that need to be paid attention to when MySql builds indexes and optimizes

Designing MySql indexes can make your database fly and greatly improve the efficiency of the database. When designing MySql indexes, there are a few points to note:
1. Create indexes

For applications where queries dominate, indexes are particularly important. Many times performance problems are simply caused by forgetting to add an index, or not adding a more efficient index. If no

index , then a full table scan will be performed to find even a specific piece of data. If a table has a large amount of data and few qualified results, then no indexing will cause fatal performance degradation.

drop. However, it is not necessary to build an index under all circumstances. For example, there may only be two values ​​for gender. Building an index not only has no advantages, but also affects the update speed. This is called excessive indexing.

2. Compound index For

example there is a statement like this: select * from users where area='beijing' and age=22;

If we create a single index on area and age respectively, because mysql query can only use one index at a time index, so although this has improved a lot of efficiency

compared it will bring higher efficiency if a composite index is created on the area and age columns. If we create (area, age,

salary), then it is actually equivalent to creating three indexes (area, age, salary), (area, age), (area), which is called the best left prefix

feature . Therefore, when we create a composite index, we should place the columns that are most commonly used as constraints on the leftmost and decrease in turn.

3. The index will not contain columns with NULL values.

As long as the columns contain NULL values, they will not be included in the index. As long as there is a column with NULL values ​​in the composite index, this column is invalid for the composite index. So we don't let the default value of the field be NULL when designing the database.

4. Use a short index to index

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

5. Sorted index problem

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

6. Like statement operation In

general , the use of like operation is discouraged. If it must be used, how to use it is also a problem. like "%aaa%" will not use the index while like "aaa%" will use the index.

7. Do not operate on columns

select * from users where

YEAR(adddate)

8. Do not use NOT IN and operations

Neither the NOT IN nor the operation will use the index will do a full table scan. NOT IN can be replaced by NOT EXISTS, id3 can use id>3 or id

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326554193&siteId=291194637