Query Optimization
Query Optimization
Query Optimization
DR. RICHA SHARMA
L O C K H AV E N U N I V E R S I T Y
1
Introduction
End-user would like database queries to execute as fast as
possible!
So, database performance must be closely monitored and
regularly tuned.
2
How about DB design?
Fine-tuning the performance of a database requires a holistic
approach – other than CPU, RAM, I/O, a good database
design is an important factor in determining the database
system’s performance efficiency.
Database performance-tuning activities can be divided into
those on the client side and those on the server side:
On the client side, we want to write an SQL query that returns
the correct answer in the least amount of time, using the
minimum amount of resources at the server end. This goal can
be achieved by SQL performance tuning!
On the server side, DBMS environment must be properly
configured to respond to SQL query in the fastest way
possible, while making optimum use of existing resources.
Such activities are referred to as DBMS performance tuning!
3
DB Architecture
Source: Chapter 11, Database Systems (13 ed.) by Coronel and Morris 4
Query Processing
DBMS processes a query in three phases: :
Parsing – DBMS parses the SQL query and chooses the
most efficient access/execution plan.
Execution – DBMS executes the SQL query using the
chosen execution plan.
Fetching – DBMS fetches the data and sends the result
set back to the client.
Compilation of program takes longest.
Processing of SQL DDL statements (such as CREATE TABLE) is
different from the processing required by DML statements.
7
Indexes
Indexes are crucial in speeding up data access because they
facilitate searching, sorting, and using aggregate functions and
even join operations.
An index is an ordered set of values that contains the index key
and pointers – that’s how data access is improved!
Pointers are the row IDs for the actual table rows.
An index scan is more efficient than a full table scan because
the index data is preordered and the amount of data is usually
much smaller.
When performing searches with Select query, it is always
better for the DBMS to use the index to access a table than to
scan all rows in a table sequentially.
8
Indexes - example
Source: Chapter 11, Database Systems (13 ed.) by Coronel and Morris 9
Few SQL Tuning tips
SQL query becomes faster if we use the actual columns names
in SELECT statement instead of than '*’.
Number of subquery blocks should be minimum in an SQL
query and using SQL JOIN instead of subqueries is better!
When a new table is created, it is always a good idea to create
a unique clustered index, possibly numeric type.
UNION ALL is better to use in place of UNION!
Replacing OR clause by UNION will result in faster query,
example: SELECT * FROM A, B WHERE A.p = B.q OR A.x = B.y
Can be re-written as: SELECT * FROM A, B WHERE A.p = B.q
UNION SELECT * FROM A, B
WHERE A.x = B.y
10