MySQL specification and performance optimization

1. After writing SQL, first explain to view the execution plan (SQL performance optimization)

When developing and writing SQL on a daily basis, try to develop this good habit: After writing SQL, use explain to analyze it, and pay special attention to whether to use the index.

2. Operate the delete or update statement and add a limit (SQL regret medicine)

  • "Reduce the cost of writing wrong SQL" . When you execute this SQL on the command line, if you do not increase the limit, you will get an "accidental hand shake" when you execute it , and all data may be deleted. What if you "delete the wrong SQL " ? With limit 200 added, it is different. The deletion of the error is only the loss of 200 pieces of data, which can be quickly recovered through the binlog log.

  • "SQL efficiency is likely to be higher" , you add limit 1 to the SQL line, if the first one hits the target return, if there is no limit, the scan table will continue to be executed.

  • "Avoid long transactions" . When delete is executed, if age adds an index, MySQL will add write locks and gap locks to all related rows, and all execution related rows will be locked. If the number of deletions is large, it will directly affect related businesses. Not available.

  • "If the amount of data is large, it is easy to  fill up the CPU." If you delete a large amount of data, do not limit the number of records, it is easy to fill up the cpu, resulting in slower and slower deletion.

3. When designing the table, add corresponding comments to all tables and fields (the SQL specification is elegant)

This good habit must be developed. When designing database tables, all tables and fields are added with corresponding comments, which is easier to maintain later.

"Counterexample:"

CREATE TABLE `account` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `balance` int(11) DEFAULT NULL,
  `create_time` datetime NOT NULL ,
  `update_time` datetime NOT NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_name` (`name`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1570068 DEFAULT CHARSET=utf8;

"Example:"

CREATE TABLE `account` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键Id',
  `name` varchar(255) DEFAULT NULL COMMENT '账户名',
  `balance` int(11) DEFAULT NULL COMMENT '余额',
  `create_time` datetime NOT NULL COMMENT '创建时间',
  `update_time` datetime NOT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  KEY `idx_name` (`name`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1570068 DEFAULT CHARSET=utf8 ROW_FORMAT=REDUNDANT COMMENT='账户表';

4. SQL writing format, keep the keyword size consistent, and use indentation. (SQL specification is elegant)

"Counterexample:"

SELECT stu.name, sum(stu.score) from Student stu WHERE stu.classNo = '1班' group by stu.name.

"Example:"

SELECT stu.name, sum(stu.score)
FROM Student stu
WHERE stu.classNo = '1班'
GROUP BY stu.name

5. INSERT statement indicates the corresponding field name (SQL specification elegant)

"Counterexample:"

insert into Student values ('666','捡田螺的小男孩','100');

"Example:"

insert into Student(student_id,name,score) values ('666','捡田螺的小男孩','100');

 6. The changed SQL operation is executed in the test environment first, and the detailed operation steps and rollback plan are written, and reviewed before production. (SQL regret medicine)

  • The changed SQL operation is tested in the test environment first to avoid syntax errors and put it on production.

  • To change the Sql operation, you need to specify the detailed operation steps, especially when there are dependencies, such as: modify the table structure first and then add the corresponding data.

  • There is a rollback plan for changing SQL operations, and before production, review the corresponding change SQL.

7. When designing the database table, add three fields: primary key, create_time, update_time. (SQL specification is elegant)

"Counterexample:"

CREATE TABLE `account` (
  `name` varchar(255) DEFAULT NULL COMMENT '账户名',
  `balance` int(11) DEFAULT NULL COMMENT '余额',
) ENGINE=InnoDB AUTO_INCREMENT=1570068 DEFAULT CHARSET=utf8 ROW_FORMAT=REDUNDANT COMMENT='账户表';

"Example:"

CREATE TABLE `account` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键Id',
  `name` varchar(255) DEFAULT NULL COMMENT '账户名',
  `balance` int(11) DEFAULT NULL COMMENT '余额',
  `create_time` datetime NOT NULL COMMENT '创建时间',
  `update_time` datetime NOT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  KEY `idx_name` (`name`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1570068 DEFAULT CHARSET=utf8 ROW_FORMAT=REDUNDANT COMMENT='账户表';

"Reason:"

  • The primary key is generally added, the table without a primary key has no soul

  • It is recommended to add the creation time and update time. Detailed audit and tracking records are all useful.

The Ali development manual also mentions this point, as shown in the figure

8. After writing the SQL statement, check the columns behind where, order by, group by, and whether the columns associated with multiple tables have been indexed, and the combined index is preferred. (SQL performance optimization)

 "Counterexample:"

select * from user 
where address ='深圳' order by age;

"Example:"

添加索引
alter table user add index idx_address_age (address,age)

 

9. Before modifying or deleting important data, back up, back up first, back up first (SQL regret medicine)

If you want to modify or delete data, you must back up the data to be modified before executing SQL. In case of misoperation, you can still take a bite of "regret medicine" ~

10. The field behind where, pay attention to the implicit conversion of its data type (SQL performance optimization)

"Counterexample:"

//userid 是varchar字符串类型
select * from user where userid =123;

"Example:" 

select * from user where userid ='123';

"Reason:"

Because when the single quotation marks are not added, it is a comparison between a string and a number, and their types do not match. MySQL will do implicit type conversion, convert them to floating point numbers and then compare them, and finally cause the index to fail

11. Try to define all columns as NOT NULL (the SQL specification is elegant)

  • "NOT NULL column saves more space." NULL column needs an extra byte as a flag to determine whether it is NULL.

  • "NULL columns need to pay attention to the issue of null pointers" . When calculating and comparing NULL columns, you need to pay attention to the issue of null pointers.

12. To modify or delete SQL, first write WHERE to check, and then add delete or update after confirmation (SQL regret medicine)

Especially when operating the produced data, if you encounter modified or deleted SQL, first add a where query, confirm OK, and then perform the update or delete operation

13. Reduce unnecessary field return, such as using select <specific field> instead of select * (SQL performance optimization)

"Counterexample:"

select * from employee;

"Example:"

select id,name from employee;

Reason:

  • Save resources and reduce network overhead.

  • Covering indexes may be used to reduce back tables and improve query efficiency.

14. All tables must use the Innodb storage engine (SQL specification elegant)

Innodb  "supports transactions, supports row-level locks, and better recoverability" , and performance is better under high concurrency, so there are no special requirements (that is, functions that Innodb cannot meet, such as column storage, storage space data, etc.) , All tables must use the Innodb storage engine

15. Try to use UTF8 uniformly for the character set of the database and table (SQL specification is elegant)

Try to use UTF8 encoding uniformly

  • Can avoid the garbled problem

  • Can avoid the index invalidation problem caused by the comparison and conversion of different character sets

"If you need to store emoticons, then choose utf8mb4 to store, pay attention to the difference between it and utf-8 encoding."

begin;
update account set balance =1000000
where name ='捡田螺的小男孩';
commit;

16. Try to use varchar instead of char. (SQL performance optimization)

"Counterexample:"

 `deptName` char(100) DEFAULT NULL COMMENT '部门名称'

"Example:"

`deptName` varchar(100) DEFAULT NULL COMMENT '部门名称'

Reason:

  • Because the storage space of variable-length fields is small, storage space can be saved.

17. If you modify the meaning of a field or add to the state of the field, you need to update the field comment in time. (SQL specification is elegant)

This point is the Mysql protocol in the Ali development manual. Your field, especially the enumeration status, if the meaning is modified, or the status is added, for better maintenance later, you need to update the comments of the field immediately.

18. SQL command line to modify data, develop the habit of begin + commit transaction (SQL regret medicine)

"Counterexample:"

update account set balance =1000000
where name ='捡田螺的小男孩';

"Example:"

begin;
update account set balance =1000000
where name ='捡田螺的小男孩';
commit;

19. Index naming should be standardized, the primary key index is named pk_ field name; the unique index is named uk _ field name; the ordinary index name is idx _ field name. (SQL specification is elegant)

Description: pk_ is the primary key; uk_ is the unique key; idx_ is the abbreviation of index.

20. Function conversion and expression calculation are not performed on columns in the WHERE clause

Assuming loginTime is indexed

"Counterexample:"

select userId,loginTime 
from loginuser
where Date_ADD(loginTime,Interval 7 DAY) >=now();

"Example:"

explain  select userId,loginTime 
from loginuser 
where  loginTime >= Date_ADD(NOW(),INTERVAL - 7 DAY);

"Reason:"

Use MySQL's built-in function on the index column, the index is invalid

21. If you modify/update too much data, consider batching.

"Counterexample:"

delete from account  limit 100000;

"Example:"

for each(200次)
{
 delete from account  limit 500;
}

"Reason:"

  • Large batch operations will cause master-slave delays.

  • Large-scale operations will generate large transactions and block.

  • Large-scale operations and too much data will fill up the cpu.

 

Previous: Oracle database access performance optimization

Next: PostgreSQL database backup and recovery

 

Reprinted: https://blog.csdn.net/weiwenhou/article/details/109505984

 

Guess you like

Origin blog.csdn.net/guorui_java/article/details/111302048