当前位置:网站首页>A good habit to develop when writing SQL

A good habit to develop when writing SQL

2022-07-24 00:20:00 000X000

Preface

Every good habit is a fortune , This article is divided into SQL Regret , SQL performance optimization ,SQL Three directions of standardization and elegance , Share and write SQL Of 21 A good habit .

1. finish writing sth. SQL First explain View execution plan (SQL performance optimization )

Daily development write SQL When , Try to form this good habit : finish writing sth. SQL after , use explain Look at the , Especially pay attention to index .

explain select userid,name,age from user 
where userid =10086 or age =18;

2、 operation delete perhaps update sentence , Add one limit(SQL Regret )

In the execution of delete or update statements , Try to add limit, Take the following one SQL Take an example. :

delete from euser where age > 30 limit 200;

Because of the addition of limit The main advantages are :

  • 「 Reduce writing errors SQL The price of 」, You do this on the command line SQL When , If not limit, When it comes to execution, it's a 「 My hand is shaking 」, Maybe all the data has been deleted , If 「 Deletion error 」 What about it ? added limit 200, Not so . Erasure is just a loss 200 Data , Can pass binlog Log fast recovery .

  • 「SQL It's likely to be more efficient 」, you are here SQL In line , added limit 1, If the first one hits the target return, No, limit Words , The scan table will continue .

  • 「 Avoid long business 」,delete Execution time , If age Indexed ,MySQL Write lock and gap lock will be added to all related lines , All execution related lines will be locked , If the number of deletions is large , It will directly affect the relevant business and cannot be used .

  • 「 If there is a large amount of data , Easy to put CPU Full 」, If you delete a lot of data , No addition limit Limit the number of records , Easy to put cpu Full , Resulting in slower and slower deletion .

3. When designing tables , All tables and fields are annotated accordingly (SQL Standard and elegant )

This good habit must be developed , When designing database tables , All tables and fields are annotated accordingly , It's easier to maintain later .

「 Example :」

CREATE TABLE `account` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT ' Primary key Id',
  `name` varchar(255) DEFAULT NULL COMMENT ' Account name ',
  `balance` int(11) DEFAULT NULL COMMENT ' balance ',
  `create_time` datetime NOT NULL COMMENT ' Creation time ',
  `update_time` datetime NOT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT ' Update time ',
  PRIMARY KEY (`id`),
  KEY `idx_name` (`name`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1570068 DEFAULT CHARSET=utf8 ROW_FORMAT=REDUNDANT COMMENT=' Account form ';

「 Counter example :」

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;

4. SQL Writing format , Keep the keyword size consistent , Use indent .(SQL Standard and elegant )

「 Example :」

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

「 Counter example :」

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

obviously , Uniform keyword case consistency , Use indent to align , It will make you SQL Looks more elegant ~

5. INSERT Statement to indicate the corresponding field name (SQL Standard and elegant )

「 Counter example :」

insert into Student values ('666',' A little boy picking up snails ','100');

「 Example :」

insert into Student(student_id,name,score) values ('666',' A little boy picking up snails ','100');

6. change SQL The operation is executed in the test environment first , Write the detailed operation steps and rollback scheme , And before production review.(SQL Regret )

  • change SQL The operation is tested in the test environment first , It's time to avoid grammatical mistakes in production .

  • change Sql Operation requires detailed operation steps , Especially when there's dependency , Such as : First modify the table structure and then add the corresponding data .

  • change Sql The operation has a rollback scheme , And before production ,review Corresponding change SQL.

7. When designing database tables , Add three fields : Primary key ,create_time,update_time.(SQL Standard and elegant )

「 Counter example :」

CREATE TABLE `account` (
  `name` varchar(255) DEFAULT NULL COMMENT ' Account name ',
  `balance` int(11) DEFAULT NULL COMMENT ' balance ',
) ENGINE=InnoDB AUTO_INCREMENT=1570068 DEFAULT CHARSET=utf8 ROW_FORMAT=REDUNDANT COMMENT=' Account form ';

「 Example :」

CREATE TABLE `account` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT ' Primary key Id',
  `name` varchar(255) DEFAULT NULL COMMENT ' Account name ',
  `balance` int(11) DEFAULT NULL COMMENT ' balance ',
  `create_time` datetime NOT NULL COMMENT ' Creation time ',
  `update_time` datetime NOT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT ' Update time ',
  PRIMARY KEY (`id`),
  KEY `idx_name` (`name`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1570068 DEFAULT CHARSET=utf8 ROW_FORMAT=REDUNDANT COMMENT=' Account form ';

「 reason :」

  • The primary key should be added , A table without a primary key is soulless

  • Create time and update time , It's better to add , Detailed audit 、 Tracking record , It's all useful .

Ali development manual also mentioned this point , Pictured

8. finish writing sth. SQL sentence , Check where,order by,group by The next column , Whether the columns associated with multiple tables are indexed , Give priority to composite indexes .(SQL performance optimization )

「 Counter example :」

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

「 Example :」

 Add index 
alter table user add index idx_address_age (address,age)

9. Before modifying or deleting important data , Back up first , Backup first , Backup first (SQL Regret )

If you want to modify or delete data , In execution SQL Be sure to back up the data to be modified before , In case of misoperation , And eat 「 Regret 」~

10. where Later fields , Pay attention to the implicit conversion of its data type (SQL performance optimization )

「 Counter example :」

//userid  yes varchar String type 
select * from user where userid =123;

「 Example :」

select * from user where userid ='123';

「 reason :」

  • Because without single quotation marks , It's a comparison of strings and numbers , They don't match ,MySQL Can do implicit type conversion , Convert them to floating-point numbers and compare them , Finally, the index is invalid

11. Try to define all columns as NOT NULL(SQL Standard and elegant )

  • 「NOT NULL Columns save space 」,NULL The column needs an extra byte to determine whether it is NULL The mark of a .

  • 「NULL Columns need to pay attention to null pointers 」,NULL When calculating and comparing , We need to pay attention to the null pointer problem .

12. Modify or delete SQL, First write WHERE Check it out , Confirm and then add delete or update(SQL Regret )

Especially when working with production data , In case of modification or deletion SQL, First add a where Check it out. , confirm OK after , Re execution update perhaps delete operation

13. Reduce unnecessary field returns , If you use select < Specific fields > Instead of select * (SQL performance optimization )

「 Counter example :」

select * from employee;

「 Example :」

select id,name from employee;

reason :

  • Save resources 、 Reduce network overhead .

  • Coverage index may be used , Reduce back to the table , Improve query efficiency .

14. All tables must use Innodb Storage engine (SQL Standard and elegant )

Innodb「 Support transactions , Row level locking is supported , Better recovery 」, High and lower performance is better , So , No special requirements ( namely Innodb Functions that cannot be satisfied, such as : Column store , Storage space data, etc ) Under the circumstances , All tables must use Innodb Storage engine

15. The character set of database and table should be used uniformly as much as possible UTF8(SQL Standard and elegant )

Try to unify the use UTF8 code

  • Can avoid the problem of garbled code

  • You can avoid , Compare and convert different character sets , The resulting index invalidation problem

「 If you need to store emoticons , So choose utf8mb4 To store , Pay attention to it and utf-8 Coding differences .」

16. Use as much as possible varchar Instead of char.(SQL performance optimization )

「 Counter example :」

  `deptName` char(100) DEFAULT NULL COMMENT ' Department name '

「 Example :」

`deptName` varchar(100) DEFAULT NULL COMMENT ' Department name '

reason :

  • Because first of all the longer fields have less storage space , You can save storage space .

17. If you modify the meaning of the field or append the status of the field representation , Field comments need to be updated in a timely manner .(SQL Standard and elegant )

This point , It's in the Alibaba development manual ,Mysql The statute of . Your fields , Especially when it represents enumeration state , If the meaning is changed , Or when the state is appended , For better maintenance later , You need to update the field's comments immediately .

18. SQL The command line modifies the data , To develop begin + commit Business habits (SQL Regret )

「 Example :」

begin;
update account set balance =1000000
where name =' A little boy picking up snails ';
commit;

「 Counter example :」

update account set balance =1000000
where name =' A little boy picking up snails ';

19. Index naming should be standardized , The primary key index name is pk_ Field name ; The unique index name is uk _ Field name ; Normal index name is idx _ Field name .(SQL Standard and elegant )

explain :pk_ namely primary key;uk_ namely unique key;idx_ namely index For short .

20. WHERE Do not perform function conversion and expression evaluation on columns in clauses

hypothesis loginTime Indexed

「 Counter example :」

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... On the index column mysql Built in functions for , Index failure

21. If modified / Too much update data , Consider doing it in batches .

Counter example :

delete from account  limit 100000;

Example :

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

reason :

  • Mass operations can cause master-slave delays .

  • Mass operations can result in large transactions , Blocking .

  • Mass operation , Too much data , Will be able to cpu Full .

原网站

版权声明
本文为[000X000]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/205/202207240018085684.html