PROBLEM:
You want to make SQL code review to yourself or to one of your team member
SOLUTION:
Use the following list for a basic SQL code review. Remember - recommendations are good for 90% of cases. Use "Execution plan" to validate your queries
- Always use indexes, even for small tables
- Try to avoid "OR"s - may cause full table scans (UNION can replace OR)
- Use UNION ALL instead of UNION if possible (does not sort)
- Do not use SQL functions around indexed columns (will suppress the use of that index)
- Try to avoid sorts (or use the same order by as the index)
- Try to provide the WHERE clause with as many host variables that match the index
- Avoid JOIN's with many tables
- Use an OUTER JOIN instead of the NOT IN clause
- Using col1 > 0 is better that col1 != 0
- Use col1 = 40 not col1+10 = 50
- Use EXISTS instead of DISTINCT and IN subquery
- Use NOT EXISTS instead of NOT IN
- Use UNION instead of OR
- When 2 indexes exists on the same table and both rank the same (by the optimizer), the first index on the WHERE clause will be used
- Try to use "index only" queries if possible. Consider adding columns to existing indexes
- OR's are processed from left to right
- AND's are processed from right to left
- Put expensive OR's at the end part (right)
- Put expensive AND's at beginning part (left)
- Make proper use of correlated sub-queries
- Break up complicated SQL statements. Do not attempt to solve all situations with single statement
- Beware of NULLS! - IS NULL and IS NOT NULL will not use index
- Use >= 0 to replace NULL expression
If you find this solution useful, you are welcome to press one of the ads in this page.. Thanks!
No comments:
Post a Comment