467,922 Members | 1,339 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Share your developer knowledge by writing an article on Bytes.

SQL Tuning tricks

I have been in several ways benefiited from this site. I would like to share some sql tuning techniques(simple, but effective) with you all.

SQL Tuning Tips
Oracle Tips Session #6
Kathy Gleeson

SQL is the heart of the Oracle system. You can use many different SQL statements to achieve the same result. It is often the case that only one statement will be the most efficient choice in a given situation. The tips below include information about whether one form of the statement is always more efficient or whether each statement is an alternative and the efficency will vary depending on your application.

Oracle processes SQL in two steps: parsing and execution. Tuning may speed up your SQL by reducing either parsing, execution or both. Note, tuning SQL should only be done after your code is working correctly. Be aware that there is an inevitable tug-of-war between writing efficient SQL and understandable SQL.
TIP 1 (Best Tip): SQL cannot be shared within Oracle unless it is absolutely identical. Statements must have match exactly in case, white space and underlying schema objects to be shared within Oracle's memory. Oracle avoids the parsing step for each subsequent use of an identical statement.

sql> SELECT NAME FROM S_CUSTOMER WHERE ID = 212; statement to match
sql> SELECT NAME FROM s_customer WHERE ID = 212; lower case
WHERE ID=212; white space

o Use SQL standards within an application. Rules like the following are easy to implement and will allow more sharing within Oracle's memory.

- Using a single case for all SQL verbs
- Beginning all SQL verbs on a new line
- Right or left aligning verbs within the initial SQL verb
- Separating all words with a single space

o Use bind variables. The values of bind variables do not need to be the same for two statements to be considered identical. Bind variables are not substituted until a statement has been successfully parsed.

Sharable SQL
SELECT * FROM emp WHERE emp_no = :B1; Bind value: 123
SELECT * FROM emp WHERE emp_no = :B1; Bind value: 987

Non-sharable SQL
SELECT * FROM emp WHERE emp_no = 123;
SELECT * FROM emp WHERE emp_no = 987;

o Use a standard approach to table aliases. If two identical SQL statements vary because an identical table has two different aliases, then the SQL is different and will not be shared.

o Use table aliases and prefix all column names by their aliases when more than one table is involved in a query. This reduces parse time AND prevents future syntax errors if someone adds a column to one of the tables with the same name as a column in another table. (ORA-00918: COLUMN AMBIGUOUSLY DEFINED)

TIP 2: Beware of WHERE clauses which do not use indexes at all. Even if there is an index over a column that is referenced by a WHERE clause included in this section, Oracle will ignore the index. All of these WHERE clauses can be re-written to use an index while returning the same values. In other words, don't perform operations on database objects referenced in the WHERE clause.

Do Not Use Use
Expand|Select|Wrap|Line Numbers
  2. SELECT account_name, trans_date, amount 
  3. FROM transaction 
  4. WHERE SUBSTR(account_name,1,7) = 'CAPITAL';    
  6. SELECT account_name, trans_date, amount 
  7. FROM transaction 
  8. WHERE account_name LIKE 'CAPITAL%';
  10. SELECT account_name, trans_date, amount 
  11. FROM transaction 
  12. WHERE account_name = NVL ( :acc_name, account_name);    
  14. SELECT account_name, trans_date, amount 
  15. FROM transaction 
  16. WHERE account_name LIKE NVL ( :acc_name, '%');
  18. SELECT account_name, trans_date, amount 
  19. FROM transaction 
  20. WHERE TRUNC (trans_date) = TRUNC (SYSDATE);    
  22. SELECT account_name, trans_date, amount 
  23. FROM transaction 
  26. SELECT account_name, trans_date, amount 
  27. FROM transaction 
  28. WHERE account_name || account_type = 'AMEXA';    
  30. SELECT account_name, trans_date, amount 
  31. FROM transaction 
  32. WHERE account_name = 'AMEX' 
  33. AND account_type = 'A';
  35. SELECT account_name, trans_date, amount 
  36. FROM transaction 
  37. WHERE amount + 3000 < 5000;    
  39. SELECT account_name, trans_date, amount 
  40. FROM transaction 
  41. WHERE amount < 2000;
  43. SELECT account_name, trans_date, amount 
  44. FROM transaction 
  45. WHERE amount != 0;    
  47. SELECT account_name, trans_date, amount 
  48. FROM transaction 
  49. WHERE amount > 0;
  51. SELECT account_name, trans_date, amount 
  52. FROM transaction 
  53. WHERE amount NOT = 0;    
  55. SELECT account_name, trans_date, amount 
  56. FROM transaction 
  57. WHERE amount > 0;
TIP 3: Don't forget to tune views. Views are SELECT statements and can be tuned in just the same way as any other type of SELECT statement can be. All tuning applicable to any SQL statement are equally applicable to views.

TIP 4: Avoid including a HAVING clause in SELECT statements. The HAVING clause filters selected rows only after all rows have been fetched. Using a WHERE clause helps reduce overheads in sorting, summing, etc. HAVING clauses should only be used when columns with summary operations applied to them are restricted by the clause.

Do Not Use Use
Expand|Select|Wrap|Line Numbers
  2. SELECT region, AVG (loc_size) 
  3. FROM location 
  4. GROUP BY region 
  5. HAVING region != 'SYDNEY' 
  6. AND region != 'PERTH';    
  8. SELECT region, AVG (loc_size) 
  9. FROM location 
  10. WHERE region != 'SYDNEY' 
  11. AND region != 'PERTH'; 
  12. GROUP BY region;
TIP 5: Minimize the number of table lookups (subquery blocks) in queries, particularly if your statements include subquery SELECTs or multicolumn UPDATEs.

Separate Subqueries
Expand|Select|Wrap|Line Numbers
  2. SELECT emp_name 
  3. FROM emp 
  4. WHERE emp_cat = (SELECT MAX (category) 
  5. FROM emp_categories) 
  6. AND emp_range = (SELECT MAX (sal_range) 
  7. FROM emp_categories) 
  8. AND emp_dept = 0020;
Combined Subqueries
Expand|Select|Wrap|Line Numbers
  2. SELECT emp_name 
  3. FROM emp 
  4. WHERE (emp_cat, sal_range) 
  5. = (SELECT MAX (category), MAX (sal_range) 
  6. FROM emp_categories) 
  7. AND emp_dept = 0020;
TIP 6: Consider the alternatives EXISTS, IN and table joins when doing multiple table joins. None of these are consistently faster; it depends on your data. If there is a poor performer here, it's likely the IN clause.

(Note, this query returns the employee names from each department in department category 'A'.)
Expand|Select|Wrap|Line Numbers
  2. SELECT emp_name 
  3. FROM emp E 
  5. FROM dept 
  6. WHERE dept_no = E.dept_no 
  7. AND dept_cat = 'A');
  8. SELECT emp_name 
  9. FROM emp E 
  10. WHERE dept_no IN ( SELECT dept_no 
  11. FROM dept 
  12. WHERE dept_no = E.dept_no 
  13. AND dept_cat = 'A');
  14. SELECT emp_name 
  15. FROM dept D, emp E 
  16. WHERE E.dept_no = D.dept_no 
  17. AND D.dept_cat = 'A';
TIP 7: Avoid joins that require the DISTINCT qualifier on the SELECT list in queries which are used to determine information at the owner end of a one-to-many relationship. The DISTINCT operator causes Oracle to fetch all rows satisfying the table join and then sort and filter out duplicate values. EXISTS is a faster alternative, because the Oracle optimizer realizes when the subquery has been satisfied once, there is no need to proceed further and the next matching row can be fetched.

(Note: This query returns all department numbers and names which have at least one employee.)
Expand|Select|Wrap|Line Numbers
  2. Do Not Use    Use
  3. SELECT DISTINCT dept_no, dept_name 
  4. FROM dept D, 
  5. emp E 
  6. WHERE D.dept_no = E.dept_no;    SELECT dept_no, dept_name 
  7. FROM dept D 
  9. SELECT 'X' 
  10. FROM emp E 
  11. WHERE E.dept_no = D.dept_no);
TIP 8: Consider whether a UNION ALL will suffice in place of a UNION. The UNION clause forces all rows returned by each portion of the UNION to be sorted and merged and duplicates to be filtered before the first row is returned. A UNION ALL simply returns all rows including duplicates and does not have to perform any sort, merge or filter. If your tables are mutually exclusive (include no duplicate records), or you don't care if duplicates are returned, the UNION ALL is much more efficient.

Expand|Select|Wrap|Line Numbers
  2. SELECT acct_num, balance_amt 
  3. FROM debit_transactions 
  4. WHERE tran_date = '31-DEC-95' 
  5. UNION 
  6. SELECT acct_num, balance_amt 
  7. FROM credit_transactions 
  8. WHERE tran_date = '31-DEC-95';    
  10. SELECT acct_num, balance_amt 
  11. FROM debit_transactions 
  12. WHERE tran_date = '31-DEC-95' 
  13. UNION ALL 
  14. SELECT acct_num, balance_amt 
  15. FROM credit_transactions 
  16. WHERE tran_date = '31-DEC-95';
TIP 9: Consider using DECODE to avoid having to scan the same rows repetitively or join the same table repetitively. Note, DECODE is not necessarily faster as it depends on your data and the complexity of the resulting query. Also, using DECODE requires you to change your code when new values are allowed in the field.

Expand|Select|Wrap|Line Numbers
  3. FROM emp 
  4. WHERE status = 'Y' 
  5. AND emp_name LIKE 'SMITH%'; 
  6. ---------- 
  8. FROM emp 
  9. WHERE status = 'N' 
  10. AND emp_name LIKE 'SMITH%';
  11. SELECT COUNT(DECODE(status, 'Y', 'X', NULL)) Y_count, 
  12. COUNT(DECODE(status, 'N', 'X', NULL)) N_count 
  13. FROM emp 
  14. WHERE emp_name LIKE 'SMITH%';
TIP 10: Oracle automatically performs simple column type conversions (or casting) when it compares columns of different types. Depending on the type of conversion, indexes may not be used. Make sure you declare your program variables as the same type as your Oracle columns, if the type is supported in the programming language you are using.

field in
clause Your Query After Implicit Conversion Index
numeric SELECT ...
FROM emp
WHERE emp_no = '123'; SELECT ...
FROM emp
WHERE emp_no = TO_NUMBER('123'); YES
varchar2 SELECT ...
FROM emp
WHERE emp_type = 123; SELECT ...
FROM emp
WHERE TO_NUMBER (emp_type) = 123; NO!

Jun 7 '07 #1
  • viewed: 19752

Sign in to post your reply or Sign up for a free account.

Similar topics

3 posts views Thread by Maryam | last post: by
1 post views Thread by Jean-Marc Blaise | last post: by
4 posts views Thread by bearophileHUGS | last post: by
13 posts views Thread by atlaste | last post: by
reply views Thread by travolta004 | last post: by
3 posts views Thread by dunleav1 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.