When querying a MySQL table, if the amount of data in the table is relatively large, the data query speed will be much slower. At this time, if the table has a primary key or index set, the query speed will be qualitatively improved
basic concept:
Primary key: The primary key is one or more fields in the table, and its value is used to uniquely identify a record in the table
Index: An index is a separate, physical storage structure that sorts the values of one or more columns in a database table. It is a collection of one or several column values in a table and the corresponding physical identifiers in the table A list of logical pointers to the data pages for these values
When I was studying before, a teacher said: the index is like the table of contents of a book, and it is much faster to find data according to the table of contents than to read it page by page.
primary key
The primary key should be noted that the primary key field is unique and cannot have duplicate values. It is generally used for the id field of the table
ALTER TABLE <data table name> ADD PRIMARY KEY(<field name>);
ALTER TABLE user_info ADD PRIMARY KEY(id);
If the field to be set as the primary key has duplicate values, an error will be reported:
After deleting the duplicate data, the modification is complete
Comparison of query speed before and after the primary key column:
It can be seen that after gradually setting, the query time is almost 0
index
When setting the index, you don’t need to consider whether there will be duplicate data, you can set it for the column that needs to be added to the index
ALTER TABLE <data table name> ADD INDEX index name (column name);
ALTER TABLE user_info ADD INDEX city(city);
--索引名可以和列名一样
Going back to the previous python task that used this table, it also performs the insertion of 10 pieces of data, and compares the execution speed before and after: