Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

SQL Performance Tuning: Query Optimization 101

DZone's Guide to

SQL Performance Tuning: Query Optimization 101

The following page describes some of the best practices of using SQL queries from a performance perspective. We use Oracle as our primary reference but most of the recommendations are applicable to other RDBMS SQL engines as well.

· Database Zone
Free Resource

Read why times series is the fastest growing database category.

The following page describes some of the best practices of using SQL queries from a performance perspective. We use Oracle as our primary reference but most of the recommendations are applicable to other RDBMS SQL engines as well.

Efficient Parsing Alias Used

The parse phase for statements can be decreased by efficient use of aliasing.

If an alias is not present, the engine must resolve which tables own the specified columns. A short alias is parsed more quickly than a long table name or alias. If possible, reduce the alias to a single letter.

The following is an example:

Bad Statement

SELECT first_name, last_name, country FROM employee, countries WHERE country_id = id AND last_name = ‘HALL’;

Good Statement

SELECT e.first_name, e.last_name, c.country FROM employee e, countries c WHERE e.country_id = c.id AND e.last_name = ‘HALL’;

Driving Tables

The structure of the FROM and WHERE clauses in a DML statement is very important to drive the overall performance of the query. There are 2 major rules that get applied to determine how the query will be executed.

These are cost-based and rule-based optimizers. These optimizers are used to select the driving table for a query.

Core Principles

A. If a decision cannot be made, the order of processing is from the end of the FROM clause to the start. Therefore, you should always place your driving table at the end of the FROM clause. Always choose the table with the less number of records as the driving table. If three tables are being joined, select the intersection tables as the driving table.

B. The intersection table is the table that has many tables dependent on it. Subsequent driven tables should be placed in order so that those retrieving the most rows are nearer to the start of the FROM clause. However, the WHERE clause should be written in the opposite order, with the driving tables conditions first and the final driven table last (example below).

FROM d, c, b, a

WHERE a.join_column = 12345

AND a.join_column = b.join_column AND b.join_column =

c.join_column AND c.join_column = d.join_column;

If we now want to limit the rows brought back from the “D” table, we may write the following:

FROM d, c, b, a

WHERE a.join_column = 12345 AND a.join_column =

b.join_column AND b.join_column = c.join_column AND

c.join_column = d.join_column AND d.name = ‘JONES’;

Depending on the number of rows and the presence of indexes, Oracle may now pick "D" as the driving table. Since "D" now has two limiting factors (join_column and name), it may be a better candidate as a driving table.

The statement may be better written as:

FROM c, b, a, d

WHERE d.name = ‘JONES’

AND d.join_column = 12345

AND d.join_column = a.join_column AND a.join_column =

b.join_column AND b.join_column = c.join_column

This grouping of limiting factors will guide the optimizer more efficiently, making table "D" return relatively few rows, and so making it a more efficient driving table.

Note: Remember, the order of the items in both the FROM and WHERE clause will not force the optimizer to pick a specific table as a driving table, but it may influence the optimizer’s decision.

C. Choose the join order so as to join fewer rows to tables later in the join order.

Avoid Using Select * Clauses

Do not use the * feature because it is very inefficient—the * has to be converted to each column in turn. The SQL parser handles all the field references by obtaining the names of valid columns from the data dictionary and substitutes them on the command line, which is time consuming.

Exists vs. In

The EXISTS function searches for the presence of a single row that meets the stated criteria, as opposed to the IN statement that looks for all occurrences.

PRODUCT 1000 rows

ITEMS 1000 rows

A.

SELECT p.product_id

FROM products p

WHERE p.item_no IN (SELECT i.item_no

FROM items i);

B.

SELECT p.product_id

FROM products p

WHERE EXISTS (SELECT ‘1’

FROM items i

WHERE i.item_no = p.item_no)

For query A, all rows in ITEMS will be read for every row in PRODUCTS. The effect will be 1,000,000 rows read from ITEMS. In the case of query B, a maximum of 1 row from ITEMS will be read for each row of PRODUCTS, thus reducing the processing overhead of the statement.

Not Exists vs. Not In

In sub query statements such as the following, the NOT IN clause causes an internal sort/ merge:

SELECT * FROM student WHERE student_num NOT IN (SELECT student_num FROM class)

Instead, use:

SELECT * FROM student c WHERE NOT EXISTS (SELECT 1 FROM class a WHERE a.student_num = c.student_num)

In With Minus vs. Not In for Non-Indexed Columns

In subquery statements such as the following, the NOT IN clause causes an internal sort/ merge:

SELECT * FROM system_user

WHERE su_user_id NOT IN

(SELECT ac_user FROM account)

Instead, use:

SELECT * FROM system_user

WHERE su_user_id IN

(SELECT su_user_id FROM system_user

MINUS

SELECT ac_user FROM account)

Inequalities

If a query uses inequalities (item_no > 100), the optimizer must estimate the number of rows returned before it can decide the best way to retrieve the data. This estimation is prone to errors.

If an index is being used for a range scan on the column in question, the performance can be improved by substituting >= for >. In this case, item_no > 100 becomes item_no >= 101. In the first case, a full scan of the index will occur. In the second case, Oracle jumps straight to the first index entry with an item_no of 101 and range scans from this point. For large indexes, this may significantly reduce the number of blocks read.

Using Union in Place of Or

In general, always consider the UNION verb instead of OR verb in the WHERE clauses. Using OR on an indexed column causes the optimizer to perform a fulltable scan rather than an indexed retrieval.

Using Union All Instead of Union

The SORT operation is very expensive in terms of CPU consumption. The UNION operation sorts the result set to eliminate any rows that are within the subqueries.

UNION ALL includes duplicate rows and does not require a sort. Unless you require that these duplicate rows be eliminated, use UNION ALL.

Using Union Instead of Outer Joins

Rewrite the UNION using a FULL OUTER JOIN with the NVL function: it is suggested that this has faster performance than the UNION operator.

select empno, ename, nvl(dept.deptno,emp.deptno) deptno, dname

from emp

full outer join dept

on (emp.deptno = dept.deptno) order by 1,2,3,4;

Using Indexes to Improve Performance

Avoid using functions like "UPPER" or "LOWER" on the column that has an index. In case there is no way that the function can be avoided, use Functional Indexes.

Why Indexes Are Not Used

If a column is defined as a Varchar2(10), and if there is an index built on that column, reference the column values within single quotes. Even if you only store numbers in it, you still need to use single quotes around your values in the WHERE clause, as not doing so will result in a full table scan.

Avoid Transformed Columns in the WHERE Clause

When you need to use SQL functions on filters or join predicates, do not use them on the columns on which you want to have an index, as in the following statement:

varcol = TO_CHAR(numcol)

Instead, use them on the opposite side of the predicate, as in the following statement:

TO_CHAR(numcol) = varcol

Use untransformed column values. For example, use:

WHERE a.order_no = b.order_no

Do not use SQL functions in predicate clauses or WHERE clauses. Any expression using a column, such as a function having the column as its argument, causes the optimizer to ignore the possibility of using an index on that column, even a unique index, unless there is a function based index defined that the database can use.

Thanks to Shalabh Mehrotra from GlobalLogic for his great references (site: https://www.globallogic.com/wp-content/uploads/2012/12/SQL-Performance-Tuning.pdf)

Learn how to get 20x more performance than Elastic by moving to a Time Series database.

Topics:
database ,oracle ,sql ,performance tuning

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}