You have to develop these 21 good habits for writing SQL

Preface

Every good habit is a treasure. This article is based on MySQL, divided into three directions: SQL regret medicine, SQL performance optimization, and SQL standard elegance. I share 21 good habits for writing SQL. Thank you for reading, come on~

Public account: "The Little Boy Who Picks Up the Snails"

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.

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

You have to develop these 21 good habits for writing SQL

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

When executing a delete or update statement, try to add limit as much as possible. Take the following SQL as an example:

delete from euser where age > 30 limit 200;

Because the addition of limit has these advantages:
You have to develop these 21 good habits for writing SQL

  • "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" during execution, and all data may be deleted. What if you "delete wrong"? With limit 200 added, it is different. Deletion is only 200 pieces of data lost, which can be quickly recovered through binlog.
  • "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 add limit to 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.

"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='账户表';

"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;

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

"Example:"

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

"Counterexample:"

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

Obviously, unifying keywords with consistent capitalization and using indentation alignment will make your SQL look more elegant~

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 write 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 must be added, a 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
    You have to develop these 21 good habits for writing SQL

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 ;

You have to develop these 21 good habits for writing SQL

"Example:"

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

You have to develop these 21 good habits for writing SQL

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;

You have to develop these 21 good habits for writing SQL
"Example:"

select * from user where userid ='123';

You have to develop these 21 good habits for writing SQL
"Reason:"

  • Because when the single quotation marks are not added, it is the comparison between strings and numbers, 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 (SQL specification 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 Innodb storage engine (SQL specification elegant)

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

15. The character set of the database and the table uniformly use UTF8 (the SQL standard is elegant)

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

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.
  • Secondly, for queries, searching in a relatively small field is more efficient.

17. If you modify the meaning of a field or add to the status 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 when representing the enumeration status, if the meaning is modified or when the status is added, for better maintenance later, you need to update the comments of the field immediately.

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

"Example:"

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

"Counterexample:"

update account set balance =1000000
where name ='捡田螺的小男孩';
  1. 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 elegant)
    Description: pk
    is primary key; uk is unique key; idx is the abbreviation of index.

20. WHERE clause does not perform function conversion and expression calculation on columns

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
    You have to develop these 21 good habits for writing SQL

21. If you modify/update too much data, consider doing it in batches.
Counter example:

delete from account  limit 100000;

Normal 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.

Reference and thanks

the public

You have to develop these 21 good habits for writing SQL

Guess you like

Origin blog.51cto.com/14989534/2546874