database optimization and SQL optimization summary

Source: Internet
Author: User

ways to optimize your database1. Select the most applicable field properties

MySQL is good at supporting large data volumes, but in general, the smaller the tables in the database, the faster queries are executed on it. Therefore, in order to achieve better performance when creating a table, we can set the width of the fields in the table as small as possible.

For example, when you define a ZIP code field, if you set it to CHAR (255), obviously adds unnecessary space to the database and even uses the varchar char (6) mediumint bigin

Another way to improve efficiency is to set the field to Notnull So in the future when the query is executed, the database does not have to compare NULL value. for some text fields, for example " province " or < span> gender " , we can define them as enum mysql font-family enum

2.Use Connection (join) instead of subquery (sub-queries)

MySQL supports SQL subquery starting from 4.1 . This technique can use the SELECT statement to create a single-column query result, and then use the result as a filter for another query. For example, if we want to delete a customer who does not have any orders in the customer's basic information table, we can take advantage of the subquery to remove all the customer IDs from the Sales Information table and then pass the results to the main query, as follows:

Deletefromcustomerinfo

Wherecustomeridnotin (Selectcustomeridfromsalesinfo)

The use of subqueries can be done at one time, many logically require multiple steps to complete SQL operations, but also avoids transaction or table locking and is easy to write. However, in some cases, subqueries can be more efficiently connected (join) . Alternative . For example, suppose we want to take out all the users without an order record, which can be done with the following query:

Select*fromcustomerinfo

Wherecustomeridnotin (Selectcustomeridfromsalesinfo)

If you use a connection ( JOIN): to complete this query, the speed will be much faster . Especially if the Salesinfo table in the CustomerID Index, the performance will be better, query as follows:

Select*fromcustomerinfo

Leftjoinsalesinfooncustomerinfo.customerid=salesinfo. CustomerID

Wheresalesinfo.customeridisnull

Connection ( JOIN): The reason why it's more efficient is because MySQL You do not need to create a temporary table in memory to complete this logical two-step query effort.

3.Use Union (union) instead of manually created temporary table

mysql from 4.0 union query It can take two or more select union We only need to use the union as a keyword put multiple select The statement is connected together, to note that all select The number of fields in the statement wants to be the same. The following example shows a query using the union

Selectname,phonefromclientunion

Selectname,birthdatefromauthorunion

Selectname,supplierfromproduct

4. Business

Although we can use subqueries (sub-queries), join, andUnion (Union) to create a wide variety of queries, not all database operations can be made with one or a few SQL Statement can be done. More often it is necessary to use a series of statements to accomplish some kind of work. But in this case, when one of the statements in this block of statements runs out of error, the operation of the entire statement block becomes indeterminate. Imagine that, to insert a data into two associated tables at the same time, it may be that the first table in the successful update, the database suddenly unexpected situation, resulting in the operation of the second table is not completed, which will result in incomplete data, and even destroy the data in the database. To avoid this situation, you should use a transaction that either succeeds or fails for each statement in the statement block. In other words, the consistency and integrity of the data in the database can be maintained. Things begin with the BEGIN keyword, and theCOMMIT keyword ends. When a SQL operation fails, theROLLBACK command can restore the database to the state it was in before begin.

BEGIN; insertintosalesinfosetcustomerid=14; updateinventorysetquantity=11whereitem= ' book '; COMMIT;

Another important role of transactions is that when multiple users use the same data source at the same time, it can use the method of locking the database to provide users with a secure way to access, so as to ensure that the user's operation is not disturbed by other users.

5. Lock the table

Although a transaction is a good way to maintain database integrity, it can sometimes affect the performance of a database because of its exclusivity, especially in large application systems. Because the database will be locked during the execution of the transaction, other user requests can only be temporarily waited until the transaction ends. If a database system has only a few users to use, the impact of the transaction will not be a big problem, but assuming that there are thousands of users accessing a database system at the same time, such as visiting an e-commerce site, there will be a more severe response delay.

In fact, there are cases where we can get better performance by locking the table. The following example uses the Lock table method to complete the function of the transaction in the previous example.

locktableinventorywriteselectquantityfrominventorywhereitem= ' book ';

...

updateinventorysetquantity=11whereitem= ' book '; Unlocktables

Here, we use a SELECT statement to remove the initial data and, with some calculations, update the new value to the table with the UPDATE statement. The locktable statement with the WRITE keyword guarantees that no additional access is made to the inventory before the unlocktables command is executed, An action that is updated or deleted.

6. Using foreign keys

The method of locking the table can maintain the integrity of the data, but it does not guarantee the data association. At this point we can use foreign keys.

For example, a foreign key can guarantee that each sales record points to an existing customer. In this case, the foreign key can map the CustomerID in the CustomerInfo table to the salesinfo table CustomerID, any one of which is not legally CustomerID records are not updated or inserted into the salesinfo .

Createtablecustomerinfo (Customeridintnotnull,primarykey (CustomerID)) Type=innodb;

Createtablesalesinfo (Salesidintnotnull,customeridintnotnull,

PRIMARYKEY (CUSTOMERID,SALESID),

ForeignKey (CustomerID) referencescustomerinfo (CustomerID) ondeletecascade) Type=innodb;

Note the parameter "Ondeletecascade" in the example. This parameter guarantees that when a customer record in the customerinfo table is deleted, all records related to that customer in thesalesinfo table will be automatically deleted. If you want to use a foreign key in MySQL, be sure to remember to define the table's type as the transaction safe table InnoDB type when you create the table. This type is not the default type for MySQL tables. The method defined is to add type=innodbto the createtable statement. As shown in the example.

7. Use index

Indexes are a common method of improving database performance, which allows the database server to retrieve specific rows at a much faster rate than without indexes, especially when the query contains Max (), MIN (), and the order of these commands.

Which fields should be indexed?

In general, the index should be based on those fields that will be used for join,where judgment and sort by order. Try not to index a field in the database that contains a large number of duplicate values. For a field of an ENUM type, there is a high likelihood of a large number of duplicate values

For example, "province" in CustomerInfo. field, indexing on such a field will not help, and conversely, it may reduce the performance of the database. We can create the appropriate index at the same time when we create the table, or we can use altertable or createindex to create the index later. In addition,MySQL supports full-text indexing and search starting from version 3.23.23 . Full-text indexing is a fulltext type index in MySQL , but can only be used for tables of type MyISAM . For a large database, it is very fast to load the data into a table that does not have a fulltext index and then use altertable or createindex to create the index. However, if you load the data into a table that already has a fulltext index, the execution process will be very slow.

8. Optimized query Statements

In most cases, using an index can improve the speed of the query, but if the SQL statement is used inappropriately, the index will not function as it should.

Here are a few things to be aware of.

    • first, it's best to compare between fields of the same type .

in the This is even a required condition before the MySQL3.23 version. For example, an indexed INT field and a BIGINT field cannot be compared, but as a special case, when the fields of the CHAR type and the VARCHAR Type field are the same size, They can be compared .

    • Second, try not to use functions to work with indexed fields.

For example, in a Using the Yeae () function on a field of DATE type will cause the index to not function as it should. As a result, the following two queries return the same results, but the latter is much faster than the former.

    • Third, when searching for character fields, we sometimes use the LIKE keyword and wildcard characters, which is simple, but at the expense of system performance.

For example, the following query will compare each record in the table.

Select*frombooks

Wherenamelike "mysql%"

However, if you switch to the following query, the result is the same, but the speed will be much faster:

Select*frombooks

wherename>= "MySQL" andname< "mysqm"

Finally, it is important to avoid having MySQL perform automatic type conversions in queries, because the conversion process also makes the index ineffective.

ways to optimize SQL statementsfirst, consider the WHERE statement:

1. Avoid null-valued fields in the WHERE clause, which will cause the engine to discard full-table scans using the index, such as:
Select ID from t where num is null
You can set the default value of 0 on NUM, make sure that the NUM column in the table does not have a null value, and then query:
Select ID from t where num=0

2. Try to avoid using the! = or <> operator in the WHERE clause, or discard the engine for full table scanning using the index

3. You should try to avoid using or in the WHERE clause to join the condition, otherwise it will cause the engine to abandon using the index for a full table scan, such as:
Select ID from t where num=10 or num=20
You can query this:
Select ID from t where num=10
UNION ALL
Select ID from t where num=20

4. The following query will also cause a full table scan:
Select ID from t where name like '%abc% '
To be more efficient, consider full-text indexing.

5.in and not in should also be used with caution, otherwise it will result in full table scans, such as:
Select ID from t where num in
For consecutive values, you can use between instead of in:
Select ID from t where num between 1 and 3

6. You should try to avoid expression operations on the fields in the WHERE clause, which will cause the engine to discard the full table scan using the index. Such as:
Select ID from t where num/2=100
should read:
Select ID from t where num=100*2

7. If you use a parameter in the WHERE clause, it also causes a full table scan. Because SQL resolves local variables only at run time, the optimizer cannot defer the selection of access plans to run time; it must be selected at compile time. However, if an access plan is established at compile time, the value of the variable is still unknown and therefore cannot be selected as an input for the index. The following statement will perform a full table scan:
Select ID from t where [email protected]
You can force the query to use the index instead:
Select ID from T with (index name) where [email protected]

8. You should try to avoid function operations on the fields in the WHERE clause, which will cause the engine to discard the full table scan using the index. Such as:
Select ID from t where substring (name,1,3) = ' abc '--name ID starting with ABC
Select ID from t where DATEDIFF (day,createdate, ' 2005-11-30 ') =0--' 2005-11-30 ' generated ID
should read:
Select ID from t where name like ' abc% '
Select ID from t where createdate>= ' 2005-11-30 ' and createdate< ' 2005-12-1 '

9. Do not perform functions, arithmetic operations, or other expression operations on the left side of "=" in the WHERE clause, or the index may not be used correctly by the system.

Other optimization considerations:

1. To optimize the query, avoid full-table scanning as far as possible, and first consider establishing an index on the columns involved in the Where and order by.

2. When using an indexed field as a condition, if the index is a composite index, you must use the first field in the index as a condition to guarantee that the system uses the index, otherwise the index will not be used, and the field order should be consistent with the index order as much as possible.

3. Do not write meaningless query statements, such as the need to generate an empty table structure:
Select Col1,col2 into #t from T where 1=0
This type of code does not return any result sets, but consumes system resources and can be changed to:
CREATE TABLE #t (...)

4. For multiple large data table joins, you must first page and then join, otherwise the logical reading will be very high, poor performance.

5. Do not use SELECT * from t anywhere, replace "*" with a specific field list, and do not return any fields that are not available.

6. Use numeric fields as much as possible, if the field containing only numeric information should not be designed as a character type, which will reduce the performance of queries and connections and increase storage overhead. This is because the engine compares each character in a string one at a time while processing queries and joins, and it is sufficient for a numeric type to be compared only once.

7. The number of indexes is not as good as possible. Indexing can improve the efficiency of the corresponding select, but it also reduces the efficiency of insert and update, because it is possible to rebuild the index at INSERT or update, so it is important to consider how to build the index, depending on the situation. The number of indexes on a table should not be more than 6, if too many you should consider whether some of the indexes that are not commonly used are necessary.

8.Update statement, if you only change 1, 2 fields, do not Update all fields, otherwise frequent calls will cause significant performance consumption, while bringing a large number of logs.

9. Use Varchar/nvarchar instead of Char/nchar as much as possible, because the first variable length field storage space is small, can save storage space, second, for the query, in a relatively small field in the search efficiency is obviously higher.

10. Use numeric fields as much as possible, if the field containing only numeric information should not be designed as a character type, which will reduce the performance of queries and connections and increase storage overhead. This is because the engine compares each character in a string one at a time while processing queries and joins, and it is sufficient for a numeric type to be compared only once.

11. You should avoid updating clustered index data columns as much as possible, because the order of the clustered index data columns is the physical storage order of the table records, which can consume considerable resources once the column values change to the order in which the entire table is recorded. If your application needs to update clustered index data columns frequently, you need to consider whether the index should be built as a clustered index.

12. When creating a temporary table, if you insert a large amount of data at one time, you can use SELECT INTO instead of CREATE table to avoid causing a large number of logs to increase speed, and if the amount of data is small, create table to mitigate the resources of the system tables. Then insert.

13. Try to use table variables instead of temporary tables. If the table variable contains a large amount of data, be aware that the index is very limited (only the primary key index).

14. When creating a temporary table, if you insert a large amount of data at one time, you can use SELECT INTO instead of CREATE table to avoid causing a large number of logs to increase speed, and if the amount of data is small, create table to mitigate the resources of the system tables. Then insert.

15. Avoid frequent creation and deletion of temporary tables to reduce the consumption of system table resources. Temporary tables are not unusable, and they can be used appropriately to make certain routines more efficient, such as when you need to repeatedly reference a dataset in a large table or a common table. However, for one-time events, it is best to use an export table.

16. If a temporary table is used, be sure to explicitly delete all temporary tables at the end of the stored procedure, TRUNCATE table first, and then drop table, which avoids longer locking of the system tables.

17. Set NOCOUNT on at the beginning of all stored procedures and triggers, set NOCOUNT OFF at the end. You do not need to send a DONE_IN_PROC message to the client after each statement that executes the stored procedure and trigger.

18. Before using a cursor-based method or temporal table method, you should first look for a set-based solution to solve the problem, and the set-based approach is generally more efficient.

19. As with temporary tables, cursors are not unusable. Using Fast_forward cursors on small datasets is often preferable to other progressive processing methods, especially if you must reference several tables to obtain the required data. Routines that include "totals" in the result set are typically faster than using cursors. If development time permits, a cursor-based approach and a set-based approach can all be tried to see which method works better.

20. Try to avoid the return of large data to the client, if the amount of data is too large, should consider whether the corresponding demand is reasonable.

21. Try to avoid large transaction operation and improve the system concurrency ability.

database optimization and SQL optimization summary

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.