Friday, October 7, 2011

SQL Query optimization - Part 1


The best way to achieve performance on your SQL code is to know the characteristics
of your queries.

It is not realistic to monitor every query, but you should measure and understand your most commonly used queries.

Query performance requires the cooperation of both Query developer and DBA. Query developer need to right an optimal query and DBA have to design DB to ensure it is optimally designed like Index mechanisms.


  • Ensure that your queries are correctly formed.
  • Ensure that your joins are correct
  • all parts of the keys are included in the ON clause
  • ensure that no cross products result from missing ON
  • or WHERE clauses for joined tables. Cross products are also known as Cartesian products.
  • Do not automatically add a DISTINCT clause to SELECT statements.


  • There is no need to include a DISTINCT clause by default. If you find that you need it because
    duplicate data is returned, the duplicate data may be the result of an incorrect data
    model or an incorrect join. For example, a join of a table with a composite primary
    key against a table with a foreign key that is referencing only part of the primary key
    results in duplicate values. You should investigate queries that return redundant data
    for these problems.
Return Only the Rows and Columns Needed
queries that
return too many columns or too many rows.

One query in particular that returns
too many columns is the often-abused SELECT * FROM construct.

Columns in the
SELECT clause are also considered by the optimizer when it identifies indexes for
execution plans. Using a SELECT * query not only returns unnecessary data, but it
also can force clustered index scans for the query plan, regardless of the WHERE
clause restrictions. This happens because the cost of going back to the clustered index
to return the remaining data from the row after using a non-clustered index to limit
the result set is actually more resource-intensive than scanning the clustered index.

Queries that call other queries that return too many columns and rows to the calling
query are another often-overlooked consideration. This includes queries that are
written as views or table-valued functions or views. Although views are useful for
many reasons, they may return more columns than you need, or they may return all
the rows in the underlying table to the calling query.


Avoid Expensive Operators Such as NOT LIKE

Some operators in joins or predicates tend to produce resource-intensive operations.
The LIKE operator with a value enclosed in wildcards (“%a value%”) almost always
causes a table scan. This type of table scan is a very expensive operation because of
the preceding wildcard. LIKE operators with only the closing wildcard can use an
index because the index is part of a B+ tree, and the index is traversed by matching
the string value from left to right.
Negative operations, such as <> or NOT LIKE, are also very difficult to resolve
efficiently. Try to rewrite them in another way if you can. If you are only checking for
existence, use the IF EXISTS or the IF NOT EXISTS construct instead. You can use an
index. If you use a scan, you can stop the scan at the first occurrence.


Avoid Explicit or Implicit Functions in WHERE Clauses

The optimizer cannot always select an index by using columns in a WHERE clause
that are inside functions. Columns in a WHERE clause are seen as an expression
rather than a column. Therefore, the columns are not used in the execution plan
optimization. A common problem is date functions around datetime columns. If
you have a datetime column in a WHERE clause, and you need to convert it or use
a data function, try to push the function to the literal expression.
The following query with a function on the datetime column causes a table scan in
the NorthWind database, even though there is an index on the OrderDate column:
SELECT OrderID FROM NorthWind.dbo.Orders WHERE DATEADD(day, 15, OrderDate) =
'07/23/1996'
Chapter 14: Improving SQL Server Performance 653
However, by moving the function to the other side of the WHERE equation, an index
can be used on the datetime column. This is shown in the following example:
SELECT OrderID FROM NorthWind.dbo.Orders WHERE OrderDate = DATEADD(day, -15,
'07/23/1996')
The graphical execution plan for both of these queries is shown in Figure 14.7, which
shows the difference in plans. Note the Scan icon for the first query and the Seek icon
for the second query. Figure 14.7 also shows the comparative difference in query costs
between the two queries; the first query has an 85.98 percent cost compared to the
14.02 percent cost for the second query. The costs on your computer may be different.
Figure 14.7
Query comparison
Implicit conversions also cause table and index scans, often because of data type
mismatches. Be especially wary of nvarchar and varchar data type mismatches and
nchar and char data type mismatches that cause an implicit conversion. You can see
these in the following execution plan. The following example uses a local variable of
type char against an nchar column in the Customers table. The type mismatch causes
an implicit conversion and a scan in this example:
DECLARE @CustID CHAR(5)
SET @CustID = 'FOLKO'
SELECT CompanyName FROM NorthWind.dbo.Customers WHERE CustomerID = @CustID
654 Improving .NET Application Performance and Scalability
Figure 14.8 shows the results of the type mismatch.
Figure 14.8
Output showing an implicit conversion

Fully Qualify Database Objects
By fully qualifying all database objects with the owner, you minimize overhead
for name resolution, and you avoid potential schema locks and execution plan
recompiles. For example, the SELECT * FROM dbo.Authors statement or the EXEC
dbo.CustOrdersHist statement performs better than the SELECT * FROM Authors or
the EXEC CustOrderHist statements. In systems that have many stored procedures,
the amount of time that is spent to resolve a non-qualified stored procedure name
adds up.

Evaluate Sorts and Filters

Sorts and filters are both CPU intensive and memory intensive because the server
performs these operations in memory. When there are instances of sorts and filters,
find out if you can create an index that would support the sorting or the filtering.
Filtering is often the result of an implicit conversion, so investigate the filter to learn
if a conversion occurred. Sorts and filters are not always bad, but they are key
indicators of potential problems, and you should investigate them further.

use TOP (sqlServer) and LIMIT to limit the number of results where appropriate

SELECT TOP 10 jim,sue,avril FROM names

2. fully reference table names

SELECT TOP 10 jim,sue,avril FROM dbo.names


* One: only "tune" sql after code is confirmed as working correctly.

* Two: ensure repeated sql statements are written absolutely identically to facilate efficient reuse: re-parsing can often be avoided for each subsequent use.

Writing best practices: all sql verbs in upper-case i.e. SELECT; separate all words with a single space; all sql verbs begin on a new line; sql verbs aligned right or left within the initial verb; set and maintain a table alias standard; use table aliases and when a query involves more than one table prefix all column names with their aliases. Whatever you do, be consistent.

* Three: code the query as simply as possible i.e. no unnecessary columns are selected, no unnecessary GROUP BY or ORDER BY.

* Four: it is the same or faster to SELECT by actual column name(s). The larger the table the more likely the savings.
Use:
SELECT customer_id, last_name, first_name, street, city FROM customer; Rather than:
SELECT * FROM customer;

* Five: do not perform operations on DB objects referenced in the WHERE clause:
Use:
SELECT client, date, amount FROM sales WHERE amount > 0;
Rather than:
SELECT client, date, amount FROM sales WHERE amount!= 0;

* Six: avoid a HAVING clause in SELECT statements - it only filters selected rows after all the rows have been returned. Use HAVING only when summary operations applied to columns will be restricted by the clause. A WHERE clause may be more efficient.
Use:
SELECT city FROM country WHERE city!= 'Vancouver' AND city!= 'Toronto'; GROUP BY city;
Rather than:
SELECT city FROM country GROUP BY city HAVING city!= 'Vancouver' AND city!= 'Toronto';

* Seven: when writing a sub-query (a SELECT statement within the WHERE or HAVING clause of another sql statement):
-- use a correlated (refers to at least one value from the outer query) sub-query when the return is relatively small and/or other criteria are efficient i.e. if the tables within the sub-query have efficient indexes.
-- use a noncorrelated (does not refer to the outer query) sub-query when dealing with large tables from which you expect a large return (many rows) and/or if the tables within the sub-query do not have efficient indexes.
-- ensure that multiple sub-queries are in the most efficient order.
-- remember that rewriting a sub-query as a join can sometimes increase efficiency.

* Eight: minimise the number of table lookups especially if there are sub-query SELECTs or multicolumn UPDATEs.

* Nine: when doing multiple table joins consider the benefits/costs for each of EXISTS, IN, and table joins. Depending on your data one or another may be faster.
Note: IN is usually the slowest.
Note: when most of the filter criteria are in the sub-query IN may be more efficient; when most of the filter criteria are in the parent-query EXISTS may be more efficient.

* Ten: where possible use EXISTS rather than DISTINCT.

* Eleven: where possible use a non-column expression (putting the column on one side of the operator and all the other values on the other). Non-column expressions are often processed earlier thereby speeding the query.
Use:
WHERE SALES < 1000/(1 + n);
Rather than:
WHERE SALES + (n * SALES) < 1000;

* Twelve: the most efficient method for storing large binary objects, i.e. multimedia objects, is to place them in the file system and place a pointer in the DB.

Tips for writing more efficient SQL

Space doesn’t permit me to discuss every detail of Oracle tuning, but I can share some general rules for writing efficient SQL in Oracle regardless of the optimizer that is chosen. These rules may seem simplistic but following them in a diligent manner will generally relieve more than half of the SQL tuning problems that are experienced:

  • Rewrite complex subqueries with temporary tables - Oracle created the global temporary table (GTT) and the SQL WITH operator to help divide-and-conquer complex SQL sub-queries (especially those with with WHERE clause subqueries, SELECT clause scalar subqueries and FROM clause in-line views). Tuning SQL with temporary tables (and materializations in the WITH clause) can result in amazing performance improvements.
  • Use minus instead of EXISTS subqueries - Some say that using the minus operator instead of NOT IN and NOT Exists will result in a faster execution plan.
  • Use SQL analytic functions - The Oracle analytic functions can do multiple aggregations (e.g. rollup by cube) with a single pass through the tables, making them very fast for reporting SQL.
  • Re-write NOT EXISTS and NOT EXISTS subqueries as outer joins - In many cases of NOT queries (but ONLY where a column is defined as NULL), you can re-write the uncorrelated subqueries into outer joins with IS NULL tests. Note that this is a non-correlated sub-query, but it could be re-written as an outer join.

select book_key from book
where
book_key NOT IN (select book_key from sales);

Below we combine the outer join with a NULL test in the WHERE clause without using a sub-query, giving a faster execution plan.

select b.book_key from book b, sales s
where
b.book_key = s.book_key(+)
and
s.book_key IS NULL;

  • Index your NULL values - If you have SQL that frequently tests for NULL, consider creating an index on NULL values. To get around the optimization of SQL queries that choose NULL column values (i.e. where emp_name IS NULL), we can create a function-based index using the null value built-in SQL function to index only on the NULL columns.
  • Leave column names alone - Never do a calculation on an indexed column unless you have a matching function-based index (a.k.a. FBI). Better yet, re-design the schema so that common where clause predicates do not need transformation with a BIF:

where salary*5 > :myvalue
where substr(ssn,7,4) = "1234"
where to_char(mydate,mon) = "january"

  • Avoid the use of NOT IN or HAVING. Instead, a NOT EXISTS subquery may run faster (when appropriate).
  • Avoid the LIKE predicate = Always replace a "like" with an equality, when appropriate.
  • Never mix data types - If a WHERE clause column predicate is numeric, do not to use quotes. For char index columns, always use quotes. There are mixed data type predicates:

where cust_nbr = "123"
where substr(ssn,7,4) = 1234

  • Use decode and case - Performing complex aggregations with the “decode” or "case" functions can minimize the number of times a table has to be selected.
  • Don't fear full-table scans - Not all OLTP queries are optimal when they uses indexes. If your query will return a large percentage of the table rows, a full-table scan may be faster than an index scan. This depends on many factors, including your configuration (values for db_file_multiblock_read_count, db_block_size), query parallelism and the number of table/index blocks in the buffer cache.
  • Use those aliases - Always use table aliases when referencing columns.

Also, see these related SQL tuning notes:

Oracle SQL undocumented tuning hints
SQL tuning using materialized views
\

SQL Tuning/SQL Optimization Techniques:

1) The sql query becomes faster if you use the actual columns names in SELECT statement instead of than '*'.

For Example: Write the query as

SELECT id, first_name, last_name, age, subject FROM student_details;

Instead of:

SELECT * FROM student_details;

2) HAVING clause is used to filter the rows after all the rows are selected. It is just like a filter. Do not use HAVING clause for any other purposes.
For Example: Write the query as

SELECT subject, count(subject)
FROM student_details
WHERE subject != 'Science'
AND subject != 'Maths'
GROUP BY subject;

Instead of:

SELECT subject, count(subject)
FROM student_details
GROUP BY subject
HAVING subject!= 'Vancouver' AND subject!= 'Toronto';

3) Sometimes you may have more than one subqueries in your main query. Try to minimize the number of subquery block in your query.
For Example: Write the query as

SELECT name
FROM employee
WHERE (salary, age ) = (SELECT MAX (salary), MAX (age)
FROM employee_details)
AND dept = 'Electronics';

Instead of:

SELECT name
FROM employee
WHERE salary = (SELECT MAX(salary) FROM employee_details)
AND age = (SELECT MAX(age) FROM employee_details)
AND emp_dept = 'Electronics';

4) Use operator EXISTS, IN and table joins appropriately in your query.
a) Usually IN has the slowest performance.
b) IN is efficient when most of the filter criteria is in the sub-query.
c) EXISTS is efficient when most of the filter criteria is in the main query.

For Example: Write the query as

Select * from product p
where EXISTS (select * from order_items o
where o.product_id = p.product_id)

Instead of:

Select * from product p
where product_id IN
(select product_id from order_items

5) Use EXISTS instead of DISTINCT when using joins which involves tables having one-to-many relationship.
For Example: Write the query as

SELECT d.dept_id, d.dept
FROM dept d
WHERE EXISTS ( SELECT 'X' FROM employee e WHERE e.dept = d.dept);

Instead of:

SELECT DISTINCT d.dept_id, d.dept
FROM dept d,employee e
WHERE e.dept = e.dept;

6) Try to use UNION ALL in place of UNION.
For Example: Write the query as

SELECT id, first_name
FROM student_details_class10
UNION ALL
SELECT id, first_name
FROM sports_team;

Instead of:

SELECT id, first_name, subject
FROM student_details_class10
UNION
SELECT id, first_name
FROM sports_team;

7) Be careful while using conditions in WHERE clause.
For Example: Write the query as

SELECT id, first_name, age FROM student_details WHERE age > 10;

Instead of:

SELECT id, first_name, age FROM student_details WHERE age != 10;

Write the query as

SELECT id, first_name, age
FROM student_details
WHERE first_name LIKE 'Chan%';

Instead of:

SELECT id, first_name, age
FROM student_details
WHERE SUBSTR(first_name,1,3) = 'Cha';

Write the query as

SELECT id, first_name, age
FROM student_details
WHERE first_name LIKE NVL ( :name, '%');

Instead of:

SELECT id, first_name, age
FROM student_details
WHERE first_name = NVL ( :name, first_name);

Write the query as

SELECT product_id, product_name
FROM product
WHERE unit_price BETWEEN MAX(unit_price) and MIN(unit_price)

Instead of:

SELECT product_id, product_name
FROM product
WHERE unit_price >= MAX(unit_price)
and unit_price <= MIN(unit_price)

Write the query as

SELECT id, name, salary
FROM employee
WHERE dept = 'Electronics'
AND location = 'Bangalore';

Instead of:

SELECT id, name, salary
FROM employee
WHERE dept || location= 'ElectronicsBangalore';

Use non-column expression on one side of the query because it will be processed earlier.

Write the query as

SELECT id, name, salary
FROM employee
WHERE salary < 25000;

Instead of:

SELECT id, name, salary
FROM employee
WHERE salary + 10000 < 35000;

Write the query as

SELECT id, first_name, age
FROM student_details
WHERE age > 10;

Instead of:

SELECT id, first_name, age
FROM student_details
WHERE age NOT = 10;

8) Use DECODE to avoid the scanning of same rows or joining the same table repetitively. DECODE can also be made used in place of GROUP BY or ORDER BY clause.
For Example: Write the query as

SELECT id FROM employee
WHERE name LIKE 'Ramesh%'
and location = 'Bangalore';

Instead of:

SELECT DECODE(location,'Bangalore',id,NULL) id FROM employee
WHERE name LIKE 'Ramesh%';

9) To store large binary objects, first place them in the file system and add the file path in the database.

10) To write queries which provide efficient performance follow the general SQL standard rules.

a) Use single case for all SQL verbs
b) Begin all SQL verbs on a new line
c) Separate all words with a single space
d) Right or left aligning verbs within the initial SQL verb