SQL statement optimization solution

Source: Internet
Author: User


1. efficient SQL statement design: Generally, the following methods can be used to optimize SQL statements for data operations: (1) Reduce the number of queries to the database, that is, you can reduce the number of queries to the database by using distributed database objects such as snapshots and graphs. (2) try to use the same or very similar SQL statements for queries. This not only makes full use of the analyzed syntax tree in the SQL sharing pool, the possibility of hitting the data to be queried in SGA is also greatly increased. (3) Avoid executing SQL statements without any conditions. When an SQL statement without any conditions is executed, it is usually required to perform the FTS. The database first locates a data block and then searches for other data in sequence, this is a long process for large tables. (4) If you have constraints on the data in some tables, it is best to use the description integrity of the SQL statements in the table to be created, rather than in the SQL program. I. Operator optimization: www.2cto.com
1. the SQL statement written using the IN operator is easier to write and understand, which is suitable for modern software development. However, SQL statements using IN always have low performance. The following differences exist between SQL statements using IN and SQL statements without IN: ORACLE tries to convert it to the join of multiple tables. If the conversion fails, it first executes the subquery IN and then queries the outer table records, if the conversion is successful, multiple tables are directly connected for query. It can be seen that at least one conversion process is added to SQL statements using IN. General SQL statements can be converted successfully, but SQL statements that contain grouping statistics cannot be converted. Avoid using the IN operator IN business-intensive SQL statements. When optimizing SQL statements, the in statement is often used. You must replace it with exists because Oracle performs the Or statement when processing In statements, even if you use an index, it will be slow. 2. The not in operator is NOT recommended for strong columns because it cannot apply table indexes. Use the not exists or (Outer Join + to determine if it is null) scheme to replace 3, is null or is not null operation to determine whether the field is null. Generally, indexes are NOT applied, because the B-tree index does not index null values. Replace it with other operation operations with the same function, and change a is not null to a> 0 or a>. Fields are not allowed to be empty, but a default value is used to replace null values. For example, status fields in the application for expansion cannot be empty. The default value is application.
Avoid using is null and is not null in the index column to avoid using any columns that can be empty in the index. ORACLE will NOT be able to use this index. this record does not exist in the index if the column contains a null value. for a composite index, if each column is empty, this record does not exist in the index. if at least one column is not empty, the record is stored in the index. for example, if the unique index is created in column A and column B of the table, and the and B values of A record exist in the table are (123, null ), ORACLE will not accept the next record with the same A, B value (123, null) (insert ). however, if all index columns are empty, ORACLE considers the entire key value to be null, but null is not equal to null. therefore, you can insert 1000 records with the same key value. Of course, they are empty! Because the null value does not exist in the index column, the null value of the index column in The WHERE clause will make ORACLE disable the index. Inefficiency: (index failure) SELECT... From department where DEPT_CODE ISNOTNULL; efficient: (index valid) SELECT... From department where DEPT_CODE> = 0;
4.> and <operator (greater than or less than operator) greater than or less than operator generally do not need to be adjusted, because it uses index search if it has an index, but in some cases, you can optimize it. For example, A table has 1 million records, A numeric field, 0.3 million of records A = 3. Therefore, the effect of executing A> 2 and A> = 3 is very different, because ORACLE will first find the record index of 2 and then compare it, when A> = 3, ORACLE directly finds the record Index = 3. Use> = to replace> efficient: www.2cto.com SELECT... From department where DEPT_CODE> = 0; inefficiency: SELECT * from empwhere deptno> 3 the difference between the two is, the former DBMS will directly jump to the first record where DEPT is equal to 4, while the latter will first locate the record where dept no = 3 and scan forward to the record where the first DEPT is greater than 3. 5. like operator: The LIKE operator can be used for wildcard queries. The wildcard combinations in the LIKE operator may be almost arbitrary queries. However, poor use may result in performance problems, for example, LIKE '% 100' does not reference the index, while LIKE 'x5400%' references the range index. An actual example: the user ID following the Business ID in the YW_YHJBQK table can be used to query the Business ID YY_BH LIKE '% 100'. This condition will generate a full table scan, if you change to YY_BH LIKE 'x5400% 'OR YY_BH LIKE 'b5400%', the index of YY_BH will be used to query the two ranges, and the performance will be greatly improved. 6. Replace DISTINCT with EXISTS: when you submit a query that contains one-to-many table information (such as the Department table and employee table), avoid using DISTINCT in the SELECT clause. in general, you can consider replacing it with EXIST, and EXISTS makes the query more rapid, because the RDBMS core module will return the result immediately after the subquery conditions are met. example: (inefficient): SELECTDISTINCT DEPT_NO, DEPT_NAMEFROM dept d, emp ewhere d. DEPT_NO = E. DEPT_NO (efficient): SELECT DEPT_NO, DEPT_NAMEFROM dept d whereexists (SELECT 'x' from emp ewhere e. DEPT_NO = D. DEPT_NO );
For example, replace IN with EXISTS and not exists with not in: IN many basic table-based queries, to meet one condition, you often need to join another table. in this case, using EXISTS (or not exists) usually improves the query efficiency. IN a subquery, the not in Clause executes an internal sorting and merging. IN either case, not in is the most inefficient (because it executes a full table traversal for the table IN the subquery ). to avoid the use of not in, we can rewrite it into an Outer join (Outer Joins) or not exists. example: www.2cto.com (efficient): SELECT * from emp (basic table) where empno> 0 ANDEXISTS (SELECT 'x' from deptwhere dept. DEPTNO = EMP. deptno and loc = 'melb') (inefficient): SELECT * from emp (basic table) WHERE EMPN O> 0AND DEPTNOIN (select dep tnofrom dept where loc = 'melb') 7. replace OR with UNION (applicable to index columns, replacing OR in the WHERE clause with UNION will produce better results. using OR for index columns will scan the entire table. note that the preceding rules are only valid for multiple index columns. if a column is not indexed, the query efficiency may be reduced because you did not select OR. in the following example, both LOC_ID and REGION have indexes. (efficient): SELECT LOC_ID, LOC_DESC, regionfrom location where LOC_ID = 10 UNIONSELECT LOC_ID, LOC_DESC, regionfrom location where region = 'melbourne' (inefficient): SELECT LOC_ID, LOC_DESC, REGIO Nfrom location where LOC_ID = 10OR REGION = 'melbourne' if you insist on using OR, you need to write at the beginning of the returned index column. 8. replace OR with IN. This is a simple and easy-to-remember rule, but the actual execution results must be tested. IN ORACLE8i, the execution paths of the two seem to be the same. inefficient: SELECT .... From location where LOC_ID = 10OR LOC_ID = 20OR LOC_ID = 30 efficiency: SELECT... From location where LOC_IN IN (10, 20, 30 );
Ii. SQL statement structure optimization: www.2cto.com 1. Avoid using '*': 2 in the SELECT clause. Replace DELETE with TRUNCATE: replace DELETE with TRUNCATE to DELETE the full table record: (large data volume table usage method) When you DELETE the record in the table, the rollback segment (rollback segments) is usually used) used to store information that can be recovered. if you do not have a COMMIT transaction, ORACLE will recover the data to the State before the deletion (which is precisely the State before the deletion command is executed). When TRUNCATE is used, rollback segments no longer store any recoverable information. 3. Replace HAVING clause with the Where clause: avoid HAVING clause. HAVING filters the result set only after all records are retrieved. this process requires sorting, total, and other operations. if the WHERE clause can be used to limit the number of records, this overhead can be reduced. (in non-oracle) where on, where, and having can be added, on is the first statement to execute, where is the second clause, and having is the last clause, because on filters out records that do not meet the conditions before making statistics, it can reduce the data to be processed by intermediate operations. It is reasonable to say that the speed is the fastest, where should be faster than having.
4. SQL statements are capitalized because oracle always parses SQL statements first, converts lowercase letters to uppercase and then executes them. 5. Try to use the connector "+" to connect strings in java code! 6. Avoid changing the index column type.: When comparing data of different data types, ORACLE automatically performs simple type conversion on columns. assume that EMPNO is a numeric index column. SELECT... From emp where empno = '000000' in fact, after ORACLE type conversion, the statement is converted to: SELECT... From emp where empno = TO_NUMBER ('123') Fortunately, the type conversion does not occur on the index column, and the purpose of the index is not changed. assume that EMP_TYPE is a character-type index column. SELECT... From emp where EMP_TYPE = 123
This statement is converted to: SELECT… by ORACLE... From emp WHERETO_NUMBER (EMP_TYPE) = 123 because of internal type conversion, this index will not be used! To avoid implicit type conversion for your SQL statements, it is best to explicitly display the type conversion. note: When comparing characters and values, ORACLE converts the value type to the character type first. 7. Optimize group by: www.2cto.com to improve the efficiency of group by statements, you can filter out unnecessary records before group. the following two queries return the same results, but the second one is much faster. inefficient: 1 select job, AVG (SAL) from emp GROUPby jobhaving job = 'President 'or job = 'manager' efficiency: 1 select job, AVG (SAL) from emp where job = 'President 'or job = 'manager' GROUPby JOB database optimization solution 1. table partition partitions are used to physically separate data. Data in different partitions can be stored in data files on different disks. In this way, when querying this table, you only need to perform a row scan in the table partition instead of a full table scan, which significantly shortens the query time, in addition, partitions on different disks will also distribute the data in this table to different disk I/O, A well-configured partition can evenly distribute data transmission to disk I/O competition. This method can be used for tables with large data volumes. Table partitions can be automatically created on a monthly basis. 2. Using aliases is an application technique of large databases, that is, using a letter as an alias for a table name or column name in a query is 1.5 times faster than creating a connection table. 3. The Optimize Design of Index can greatly accelerate the database query speed. The Index maps the logical values in the table to the secure RowID, so the Index can quickly locate the physical address of the data. When you query a large table with an index, index data may use up all the data block cache space. ORACLE has to perform disk read/write frequently to obtain data, therefore, after partitioning a large table, you can create a partition index based on the corresponding partition. However, I personally think that not all tables need to be indexed, but only for tables with large data volumes. Disadvantages: First, it takes time to create and maintain indexes. This time increases with the increase of data volume. Second, indexes occupy physical space. In addition to data tables, each index occupies a certain amount of physical space. To create a clustered index, the required space is larger. Third, when adding, deleting, and modifying data in the table, the index must also be dynamically maintained, which reduces the Data Maintenance speed. Www.2cto.com indexes need to be maintained: To maintain system performance, after an index is created, the index page is broken due to frequent operations such as adding, deleting, and modifying data. Therefore, indexes must be maintained. 4. The hard disk I/O adjustment step is completed before the information system development. The database administrator can store data files in the same tablespace on different hard disks to achieve I/O load balancing between hard disks. When the disk is richer, the following principles should be followed: separating tables from indexes; Creating user tablespaces and separating disks from system tablespaces; specify different tablespaces when creating tables and indexes. Create tablespaces dedicated to rollback segments to prevent space competition from affecting the completion of transactions. create temporary tablespaces for sorting operations, try to prevent database fragments from being stored in multiple tablespaces. In the process of using materialized views, we can "treat it as a real data table" without worrying about the efficiency, optimization, and other materialized views of the Basic Tables of the view. for complex and high-consumption queries, if frequently used, a materialized view should be built. 2. materialized View is a typical performance optimization method with space for time. exercise caution when using materialized views for frequently updated tables. 4. select an appropriate refresh method. Generally, the view is virtual, while the materialized view is a real data area that occupies storage space. Of course, the creation and management of materialized views are different from those of general views. In contrast, materialized views occupy a certain amount of storage space. In addition, refreshing materialized views by the system also consumes a certain amount of resources, but it brings efficiency and flexibility. Reduce IO and network transmission times 1. try to use a small number of database requests to obtain the required data. 2. for batch operations that frequently operate databases, stored procedures should be used to reduce unnecessary network transmission deadlocks and congestion. for data that needs to be updated frequently, try to avoid putting it in long transactions to avoid chain reactions. it is not a last resort. It is best not to add your own locks in addition to the ORACLE lock mechanism. 3. reduce the transaction size and promptly submit the transaction www.2cto.com 4. avoid cross-database distributed transactions as much as possible, because of the complexity of the environment, it is easy to cause blocking 5. use Bitmap indexes with caution. Table partitions are automatically added due to deadlocks when updating data. This program can be executed as an Oracle JOB before the 28th day of each month (for the reason of January 1, February 28 ), automatically adds partitions to the partition table of this user. create or replace procedure guan_add_partition/* automatically adds partitions for all partition tables under a user. the partition column is of the date type. The partition name is similar to: p200706./* create by David */asv_table_name varchar2 (50); v_partition_name varchar2 (50); v_month char (6 ); v_add_month_1 char (6); v_ SQL _string varchar2 (2000); v_add_month varchar2 (20); cursor cur_part is select distinct u. table_name, max (p. partition_name) max_part_name from user_tables u, user_tab_partitions pwhere u. table_name = p. table_name and u. partitioned = 'yes' group by u. table_name; Beginselect to_char (sysdate, 'yyymmm ') into v_month from dual; select to_char (add_months (sysdate, 1), 'yyymmd') into v_add_month_1 from dual; select to_char (add_months (trunc (sysdate, 'mm'), 2), 'yyyy-mm-dd') into v_add_month from dual; www.2cto.com open cur_part; loopfetch cur_part into v_table_name, v_partition_name; exit when cur_part % notfound; if to_number (substr (v_partition_name, 2) <= to_number (substr (v_month, 1) thenv_ SQL _string: = 'alter table' | v_table_name | 'add partition P' | v_add_month_1 | 'values less than (to_date (''' | v_add_month | ''', ''yyyy-mm-dd'') tablespace users '; execute immediate v_ SQL _string; elsenull; end if; end loop; close cur_part; end;

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.