Three principles for adding mysql indexes _ MySQL

Source: Internet
Author: User
Three principles for adding mysql indexes I. importance of indexes

The index is used to quickly find rows with a specific value in a column. If no index is used, MySQL must start with 1st records and read the entire table until related rows are found. The larger the table, the more time it takes. If the column to be queried in the table has an index, MySQL can quickly find the data file in the middle of a location, and there is no need to read all the data. Note that if you want to access most rows, sequential reading is much faster, because disk search is avoided.

If you use the Xinhua dictionary to find the Chinese character "Zhang" without using a directory, it may take two hours to find the last page from the first page of the Xinhua Dictionary. The thicker the dictionary, the more time you spend. Now you can use the directory to search for the Chinese character "Zhang". The first letter of the Chinese character is z. The Chinese character starting with z starts from more than 900 pages. with this clue, it may take one minute to search for a Chinese character, this shows the importance of indexes. But is the index created more and better? of course not. if the directory of a book is divided into several levels, I think you will also be dizzy.

2. preparations

 
 
  1. // Prepare two test tables
  2. Mysql> create table 'test _ t '(
  3. -> 'Id' int (11) not null auto_increment,
  4. -> 'Num' int (11) not null default '0 ',
  5. -> 'D _ num' varchar (30) not null default '0 ',
  6. -> Primary key ('id ')
  7. ->) ENGINE = MyISAM default charset = utf8 AUTO_INCREMENT = 1;
  8. Query OK, 0 rows affected (0.05 sec)
  9. Mysql> create table 'test _ test '(
  10. -> 'Id' int (11) not null auto_increment,
  11. -> 'Num' int (11) not null default '0 ',
  12. -> Primary key ('id ')
  13. ->) ENGINE = MyISAM default charset = utf8 AUTO_INCREMENT = 1;
  14. Query OK, 0 rows affected (0.05 sec)
  15. // Create a stored procedure to facilitate data insertion
  16. Mysql> delimiter |
  17. Mysql> create procedure I _test (pa int (11), tab varchar (30 ))
  18. -> Begin
  19. -> Declare max_num int (11) default 100000;
  20. -> Declare I int default 0;
  21. -> Declare rand_num int;
  22. -> Declare double_num char;
  23. ->
  24. -> If tab! = 'Test _ test' then
  25. -> Select count (id) into max_num from test_t;
  26. -> While I <pa do
  27. -& Gt; if max_num & lt; 100000 then
  28. -> Select cast (rand () * 100 as unsigned) into rand_num;
  29. -> Select concat (rand_num, rand_num) into double_num;
  30. -> Insert into test_t (num, d_num) values (rand_num, double_num );
  31. -> End if;
  32. -> Set I = I + 1;
  33. -> End while;
  34. -> Else
  35. -> Select count (id) into max_num from test_test;
  36. -> While I <pa do
  37. -& Gt; if max_num & lt; 100000 then
  38. -> Select cast (rand () * 100 as unsigned) into rand_num;
  39. -> Insert into test_test (num) values (rand_num );
  40. -> End if;
  41. -> Set I = I + 1;
  42. -> End while;
  43. -> End if;
  44. -> End |
  45. Query OK, 0 rows affected (0.00 sec)
  46. Mysql> delimiter;
  47. Mysql> show variables like "% pro %"; // check whether the profiling is enabled and disabled by default.
  48. + --------------------------- + ------- +
  49. | Variable_name | Value |
  50. + --------------------------- + ------- +
  51. | Profiling | OFF |
  52. | Profiling_history_size | 15 |
  53. | Protocol_version | 10 |
  54. | Slave_compressed_protocol | OFF |
  55. + --------------------------- + ------- +
  56. 4 rows in set (0.00 sec)
  57. Mysql> set profiling = 1; // after enabling, it is used to compare the execution time after the index is added.
  58. Query OK, 0 rows affected (0.00 sec)

III. instances

1. if there is too little data in a single table, indexing will affect the speed.

 
 
  1. Mysql> call I _test (10, 'Test _ t'); // Insert 10 conditions to the test_t table
  2. Query OK, 1 row affected (0.02 sec)
  3. Mysql> select num from test_t where num! = 0;
  4. Mysql> explain select num from test_t where num! = 0/G;
  5. * *************************** 1. row ***************************
  6. Id: 1
  7. Select_type: SIMPLE
  8. Table: test_t
  9. Type: ALL
  10. Possible_keys: NULL
  11. Key: NULL
  12. Key_len: NULL
  13. Ref: NULL
  14. Rows: 10
  15. Extra: Using where
  16. 1 row in set (0.00 sec)
  17. ERROR:
  18. No query specified
  19. Mysql> create index num_2 on test_t (num );
  20. Query OK, 10 rows affected (0.19 sec)
  21. Records: 10 Duplicates: 0 Warnings: 0
  22. Mysql> select num from test_t where num! = 0;
  23. Mysql> explain select num from test_t where num! = 0/G;
  24. * *************************** 1. row ***************************
  25. Id: 1
  26. Select_type: SIMPLE
  27. Table: test_t
  28. Type: index
  29. Possible_keys: num_2
  30. Key: num_2
  31. Key_len: 4
  32. Ref: NULL
  33. Rows: 10
  34. Extra: Using where; Using index
  35. 1 row in set (0.00 sec)
  36. ERROR:
  37. No query specified
  38. Mysql> show profiles;
  39. + ---------- + ------------ + ----------------------------------------------- +
  40. | Query_ID | Duration | Query |
  41. + ---------- + ------------ + ----------------------------------------------- +
  42. | 1 | 0.00286325 | call I _test (10, 'Test _ t') | // Insert 10 data records
  43. | 1 | 0.00026350 | select num from test_t where num! = 0 |
  44. | 3 | 0.00022250 | explain select num from test_t where num! = 0 |
  45. | 4 | 0.18385400 | create index num_2 on test_t (num) | // create an index
  46. | 5 | 0.00127525 | select num from test_t where num! = 0 | // after the index is used, it is about 0.2 times that no index is used.
  47. | 6 | 0.00024375 | explain select num from test_t where num! = 0 |
  48. + ---------- + ------------ + ----------------------------------------------- +
  49. 6 rows in set (0.00 sec)

Explanation:

Id: the SQL execution sequence.

Select_type: SIMPLE, PRIMARY, UNION, dependent union, union result, SUBQUERY, dependent subquery, and DERIVED different query statements have different select_types.

Table: The name of the table to be searched.

Type: indicates whether the index type is used or whether the index is used. efficiency from high to low const, eq_reg, ref, range, index, and ALL. In fact, the root of your SQL statement has a direct relationship. for example, you can use the primary key to use the primary key, add the index to the condition after the where clause.

Possible_keys: possible indexes

Key: Use Index

Key_len: used index length

Ref: which column or constant is used together with the key to select rows from the table. this is generally used in multi-table joint queries.

Rows: number of lines found

Extra: additional instructions

I wrote a blog post about mysql distinct and group by some time ago. some friends left a message saying that the test results are different from the test results I did at the time. I explained it by analogy, today, we have time to express the indexing principles more intuitively in the context of examples.

2. when filtering conditions such as 'order by' and 'group by' after 'where', it is best to add an index to the following fields. Select indexes such as primary key, UNIQUE, and INDEX based on the actual situation, but the more indexes, the better.

3. join queries, subqueries, and other multi-table operations require indexed joined Fields

 
 
  1. Mysql> call I _test (10, 'Test _ test'); // Insert 10 data records to the test_test table.
  2. Query OK, 1 row affected (0.02 sec)
  3. Mysql> explain select a. num as num1, B. num as num2 from test_t as a left join tes
  4. T_test as B on a. num = B. num/G;
  5. * *************************** 1. row ***************************
  6. Id: 1
  7. Select_type: SIMPLE
  8. Table:
  9. Type: index
  10. Possible_keys: NULL
  11. Key: num_2
  12. Key_len: 4
  13. Ref: NULL
  14. Rows: 10
  15. Extra: Using index
  16. * *************************** 2. row ***************************
  17. Id: 1
  18. Select_type: SIMPLE
  19. Table: B
  20. Type: ref
  21. Possible_keys: num_1
  22. Key: num_1
  23. Key_len: 4
  24. Ref: bak_test.a.num // bak_test is the database name, and a. num is a field of test_t.
  25. Rows: 1080
  26. Extra: Using index
  27. 2 rows in set (0.01 sec)
  28. ERROR:
  29. No query specified

When the data size is very large, it is best not to use joint queries, even if you have performed an index.

The above is just a personal summary.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.