[MySQL] This article takes you to understand database indexes and transactions

1. The concept of index

A database index is a data structure that improves the efficiency of database queries. It can quickly locate and access data in the database, thereby greatly improving the speed and efficiency of database queries. Database indexes can construct multiple indexes according to different query requirements to maximize query efficiency.
Database indexes are created based on various fields. When querying, you can directly find the data that meets the conditions through the index without scanning the entire data table. Database indexes can be divided into primary key indexes, unique indexes, common indexes, and full-text indexes. Each type of index has different characteristics and application scenarios.

2. Index creation and use

Database indexes can be created based on various fields, but they are usually created based on fields with high query frequency, complex query conditions, or fields that need to be sorted.
Commonly used index fields include primary key, unique key, foreign key, commonly used query fields, etc.

2.1 Automatically create indexes for corresponding columns

When creating primary key constraints (PRIMARY KEY), unique constraints (UNIQUE), and foreign key constraints (FOREIGN KEY), indexes for corresponding columns are automatically created.

-- 查看索引
show index from 表名;
mysql> create table book(id int primary key, name varchar(10), price int);
Query OK, 0 rows affected (0.02 sec)

mysql> show index from book;
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| book  |          0 | PRIMARY  |            1 | id          | A         |           0 |     NULL | NULL   |      | BTREE      |         |               |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
1 row in set (0.00 sec)

mysql> drop table book;
Query OK, 0 rows affected (0.01 sec)

mysql> create table book(id int unique, name varchar(10), price int);
Query OK, 0 rows affected (0.01 sec)

mysql> show index from book;
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| book  |          0 | id       |            1 | id          | A         |           0 |     NULL | NULL   | YES  | BTREE      |         |               |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

2.2 Create a common index yourself

--自己创建的索引
create index 索引名 on 表名(字段名);
mysql> create table book(id int, name varchar(10), price int);
Query OK, 0 rows affected (0.02 sec)

mysql> show index from book;
Empty set (0.00 sec)

mysql> create index idx_book_id on book(id);
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> show index from book;
+-------+------------+-------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name    | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-------+------------+-------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| book  |          1 | idx_book_id |            1 | id          | A         |           0 |     NULL | NULL   | YES  | BTREE      |         |               |
+-------+------------+-------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

2.3 Delete index

-- 删除
drop index 索引名 on 表名;
mysql> show index from book;
+-------+------------+-------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name    | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-------+------------+-------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| book  |          1 | idx_book_id |            1 | id          | A         |           0 |     NULL | NULL   | YES  | BTREE      |         |               |
+-------+------------+-------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
1 row in set (0.00 sec)

mysql> drop index idx_book_id on book;
Query OK, 0 rows affected (0.01 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> show index from book;
Empty set (0.00 sec)

2.4 Index query

Using the index to query data is the same as normal query, but the data structure saved by the index is mainly B+ tree and hash method, so when there is a lot of data, the query speed will be greatly increased.

mysql> insert into book values(1,'西游'),
    -> (2,'三国'),
    -> (3,'水浒'),
    -> (4,'红楼'),
    -> (5,'0'),
    -> (6,'1'),
    -> (7,'2');
Query OK, 7 rows affected (0.01 sec)
Records: 7  Duplicates: 0  Warnings: 0

mysql> select * from book where id = 4;
+------+------+
| id   | name |
+------+------+
|    4 | 红楼 |
+------+------+
1 row in set (0.00 sec)

3. Disadvantages of indexing

Database indexing can improve query efficiency, but it also increases the storage space of data tables and the time cost of updating data. Therefore, when designing a database, it is necessary to create indexes reasonably according to the actual situation, so as to ensure query efficiency without affecting the speed of data update and insertion.
If the data in the table is frequently modified, the index also needs to be updated accordingly, which will bring a certain performance overhead. Therefore, it is not recommended to create indexes for fields that are not frequently used or have a relatively small value range.
At the same time, there can be more than one index for a table, but too many indexes should be avoided, otherwise the performance of the database will be reduced.

4. The concept of transaction

A transaction is a logical set of operations, either all succeed or all fail. If one operation fails, the entire transaction will be rolled back and restored to the state before execution. Ensure data consistency and reliability. At the same time, transactions can also improve the concurrency performance of the database and ensure the uniqueness and isolation of data. Therefore, it is very important to use transactions in high-concurrency and high-availability application scenarios.

5. Characteristics of transactions

Transactions are grouped into four important ACID properties, namely:

  1. Atomicity: All operations in a transaction are either executed successfully or rolled back on failure, as indivisible as atoms.
  2. Consistency: before and after transaction execution, the integrity and consistency of data must remain consistent.
  3. Isolation: In the process of transaction execution, the operations on data are isolated from each other, and each transaction is executed in an independent environment to avoid mutual interference between data operations.
  4. Durability: Once a transaction is committed, its changes to the data state in the database are permanent, even if the system crashes, it will not be affected, and the data will remain until the next transaction modifies it.

6. Use of transactions

  1. Open transaction: start transaction;
  2. Execute multiple SQL statements
  3. Rollback or commit: rollback/commit;

Rollback means all failures, and commit means all successes.

start transaction;
-- 阿里巴巴账户减少2000
update accout set money=money-2000 where name = '阿里巴巴';
-- 四十大盗账户增加2000
update accout set money=money+2000 where name = '四十大盗';
commit;

Guess you like

Origin blog.csdn.net/weixin_73392477/article/details/131279950