Teach you to write high-quality SQL (required for practice)

1. Try not to use select * when querying SQL, but select specific fields.

//反例子
select * from sys_user;
//正例子
select id,name from sys_user;

reason:

Only take the required fields to save resources and reduce network overhead; when selecting * to query, it is likely that the covering index will not be used, which will result in querying back to the table;

Covering index: All column data required by SQL can be obtained on only one index tree, without returning to the table, and the speed is faster.
For example:

Back-to-table query: First locate the clustered index value through the value of the common index, and then locate the row record data through the value of the clustered index. It needs to scan the index B+ tree twice, and its performance is lower than scanning the index tree once.

2. If you know that there is only one query result or only one maximum/minimum record, it is recommended to use limit1

Assuming that there is a sys_user user table now, it is necessary to find a person whose mobile phone number is 18811112299;

//反例
select id,name from sys_user where mobile = '18811112299'
//正例
select id,name from sys_user where mobile = '18811112299' limit 1

reason:

  • After adding limit1, as long as a corresponding record is found, it will not continue to scan downwards, and the efficiency of scanning the entire table will be greatly improved;
  • Of course, if mobile is the only index, there is no need to add limit1,

Guess you like

Origin blog.csdn.net/weixin_40205234/article/details/124668408