ORACLE Database Health - Query Tunning
ORACLE Database Health - Query Tunning
&
Query Tuning
Database Health Check (ORACLE)
Why to go to DB Health Check
Oracle V$ views & Sys tables used to create
the Sample Script for DB Health Check.
Benefits
Oracle Query Tuning
How to use Explain Plan
Usage of Hints
General Hints
Do and Don’t of using Hints
Q & A
AGENDA
Goal: Reduce Time between
Problem Reporting to Problem Resolution
Database Health Check
By Regular Database health Check
v_$instance :- This view give us the information about db instance.
The following script will help you in deriving the Total Days including Hours
minutes and seconds from when this instance of database is started.
SELECT *
FROM (SELECT c.tablespace_name, ROUND (a.BYTES / 1048576, 2) mb_allocated,
ROUND (b.BYTES / 1048576, 2) mb_free,
ROUND ((a.BYTES - b.BYTES) / 1048576, 2) mb_used,
ROUND (b.BYTES / a.BYTES * 100, 2) tot_pct_free,
ROUND ((a.BYTES - b.BYTES) / a.BYTES, 2) * 100 tot_pct_used
FROM (SELECT tablespace_name, SUM (a.BYTES) BYTES
FROM SYS.dba_data_files a
GROUP BY tablespace_name) a,
(SELECT a.tablespace_name, NVL (SUM (b.BYTES), 0) BYTES
FROM SYS.dba_data_files a, SYS.dba_free_space b
WHERE a.tablespace_name = b.tablespace_name(+)
AND a.file_id = b.file_id(+)
GROUP BY a.tablespace_name) b,
SYS.dba_tablespaces c
WHERE a.tablespace_name = b.tablespace_name(+)
AND a.tablespace_name = c.tablespace_name)
WHERE tot_pct_used >= 0
ORDER BY tablespace_name
Tables .. .contd..
Monitor the size of the database which
can avoid the tablespace issues.
These
stats are generated using “Analyze”
command.
ESTIMATE STATISTICS :-
When estimating statistics, Oracle gathers representative information from portions of an object.
This subset of information provides reasonable, estimated statistics about the object. The
accuracy of estimated statistics depends upon how representative the sampling used by Oracle
is. Only parts of an object are scanned to gather information for estimated statistics, so an object
can be analyzed quickly. You can optionally specify the number or percentage of rows that
Oracle should use in making the estimate.
ANALYZE calculates global statistics for partitioned tables and indexes instead of gathering them directly.
This can lead to inaccuracies for some statistics, such as the number of distinct values. DBMS_Stats won't
do that.
Generate plan
description Execute the
plan
Transform plan
into
Query Tuning –Optimizer Overview
“executable”
An explain plan is a representation of the access path that is taken when a query
is executed within Oracle.
Query processing can be divided into 7 phases:
◦ [1] Syntactic :- Checks the syntax of the query
◦ [2] Semantic :- Checks that all objects exist and are accessible
◦ [3] View Merging :- Rewrites query as join on base tables as opposed to using views
◦ [4] Statement Transformation :- Rewrites query transforming some complex constructs
into simpler ones where appropriate (e.g. subquery merging, in/or transformation)
◦ [5] Optimization :- Determines the optimal access path for the query to take. With the
Rule Based Optimizer (RBO) it uses a set of heuristics to determine access path. With the
Cost Based Optimizer (CBO) we use statistics to analyze the relative costs of accessing
objects.
◦ [6] QEP Generation :- QEP = Query Evaluation Plan
◦ [7] QEP Execution :- QEP = Query Evaluation
Plan Steps [1]-[6] are handled by the parser. Step [7] is the execution of the
statement.
The explain plan is produced by the parser. Once the access path has been
decided upon it is stored in the library cache together with the statement itself.
Tuples :- rows
Driving Table :- This is the row source that we use to seed the query. If this returns
a lot of rows then this can have a negative affect on all subsequent operations
Probed Table :- This is the object we lookup data in after we have retrieved relevant
key data from the driving table.
Query Plan
-----------------------------------------
SELECT STATEMENT [CHOOSE] Cost=
TABLE ACCESS FULL DUAL
Index lookup :- Data is accessed by looking up key values in an index and returning rowid’s.
SQL> explain plan for
select empno,ename from emp where emp_no =10;
Query Plan
------------------------------------
SELECT STATEMENT [CHOOSE] Cost=1
TABLE ACCESS BY ROWID EMP [ANALYZED]
INDEX UNIQUE SCAN EMP_I1
Notice the 'TABLE ACCESS BY ROWID' section. This indicates that the table data is not being
accessed via a FTS operation but rather by a rowid lookup. In this case the rowid has been
produced by looking up values in the index first. The index is being accessed by an 'INDEX
UNIQUE SCAN' operation. This is explained below.
Query Plan
------------------------------------
SELECT STATEMENT [CHOOSE] Cost=1
INDEX UNIQUE SCAN EMP_I1
Indexes are presorted so sorting may be unnecessary if the sort order required is the same
as the index.
SQL> explain plan for select empno,ename from emp
where empno > 7876 order by empno;
Query Plan
-------------------------------------------------------------
SELECT STATEMENT [CHOOSE] Cost=1
TABLE ACCESS BY ROWID EMP [ANALYZED]
INDEX RANGE SCAN EMP_I1 [ANALYZED]
Query Plan
------------------------------------
SELECT STATEMENT [CHOOSE] Cost=1
TABLE ACCESS BY ROWID EMP [ANALYZED]
INDEX UNIQUE SCAN EMP_I1
Query Plan
------------------------------------------
SELECT STATEMENT [CHOOSE] Cost=1
INDEX FAST FULL SCAN BE_IX [ANALYZED]
Selecting the 2nd column of concatenated index:
SQL> explain plan for select ename from big_emp;
Query Plan
------------------------------------------
SELECT STATEMENT [CHOOSE] Cost=1
INDEX FAST FULL SCAN BE_IX [ANALYZED]
Joins
:- A Join is a predicate that attempts to
combine 2 row sources.
Joins Type :-
Sort Merge Join (SMJ)
Nested Loops (NL)
Hash Join
Access
source 1 Methods
source 2 contd..
SQL> explain plan for
select /*+ ordered */ e.deptno,d.deptno
from emp e,dept d
where e.deptno = d.deptno
order by e.deptno,d.deptno;
Query Plan
-------------------------------------
SELECT STATEMENT [CHOOSE] Cost=17
MERGE JOIN
SORT JOIN
TABLE ACCESS FULL EMP [ANALYZED]
SORT JOIN
TABLE ACCESS FULL DEPT [ANALYZED]
Sorting is an expensive operation, especially with large tables.
Because of this, SMJ is often not a particularly efficient join method.
Methods contd..
session.
Output rows
DISK
SQL> explain plan for
select /*+ use_hash(emp) */ empno
from emp,dept
where emp.deptno = dept.deptno;
Query Plan
----------------------------
SELECT STATEMENT [CHOOSE] Cost=3
HASH JOIN
TABLE ACCESS FULL DEPT
TABLE ACCESS FULL EMP
When can be used Any join Equi joins only Equi joins only
Features Works with any join Better than nested Better than nested
loop when indexes is loop when indexes is
missing or search missing or search
criteria is not restrictive criteria is not restrictive
Drawbacks Very inefficient when Must perform an extra sort. Can require lot of memory and
no suitable index exists Cannot return First rows fast. slow down updates and full table scan
Cartesian Product
A Cartesian Product is done where they are no join conditions between 2 row
sources and there is no alternative method of accessing the data Not really a join as
such as there is no join! Typically this is caused by a coding mistake where a join
has been left out. It can be useful in some circumstances - Star joins uses Cartesian
products.
Notice that there is no join between the 2 tables:
SQL> explain plan for
select emp.deptno,dept,deptno
from emp,dept
Query Plan
------------------------------
SLECT STATEMENT [CHOOSE] Cost=5
MERGE JOIN CARTESIAN
TABLE ACCESS FULL DEPT
SORT JOIN
TABLE ACCESS FULL EMP
The CARTESIAN keyword indicate that we are doing a Cartesian product
Arguably, the most important fields within the plan table are
operation, option, object_name, id, and parent_id.
Tuning - HINTS
Hints are not orders but directives to the optimizer.
Hints are provided in comment format that is embedded in the query.
Multiple hints can be provided in a single comment for a statement,
each separated with spaces
Hints are meant for DML statements: INSERT, UPDATE, DELETE and
SELECT
Hints are not case sensitive.
If a wrong or invalid hint is provided, the optimizer ignores it and
continues with the execution of the statement. The optimizer will not
notify the user about such hints.
Hints are CBO features.
Table hints can be provided with the table name. . If an alias name is
provided, use it instead of the table name.
Do Not Use:
Select *
From fin_trxn
Where ft_trxn_ref_no != 0
Use:
Select *
From fin_trxn
Where ft_trxn_ref_no > 0
Use:
Select *
From account
Where ac_type = ‘sav’
And ac_branch = ‘sav001’
Do Not Use:
Select *
From CLIENT where
to_char(CUTT_OFF_TIME, ’yyyymmdd’) =
to_char(sysdate,’yyyymmdd’)
Use:
Select *
From CLIENT
Where CUT_OFF_DATE >=
trunc(sysdate) and CUT_OFF_TIME < trunc(sysdate) + 1
Select *
From acct_trxn
Where to_char(at_value_date,’yyyymmdd’) >
to_char(sysdate,’yyyymmdd’)
Use:
Select *
From acct_trxn
Where at_value_date >= trunc(sysdate) + 1
Do Not Use:
Select *
From acct_trxn
Where to_char(at_value_date,’yyyymmdd’) <
to_char(sysdate,’yyyymmdd’)
Use:
Select *
From acct_trxn
Where at_value_date < trunc(sysdate)
Select *
From acct_trxn
Where to_char(at_value_date,’yyyymmdd’) >=
to_char(sysdate,’yyyymmdd’)
Use:
Select *
From acct_trxn
Where at_value_date >= trunc(sysdate)
Do Not Use:
Select *
From acct_trxn
Where to_char(at_value_date,’yyyymmdd’) <=
to_char(sysdate,’yyyymmdd’)
Use:
Select *
From acct_trxn
Where at_value_date < trunc(sysdate) + 1
select *
from account
where cust_Active_flag = ‘y’ having group = ‘001’
Use: select *
from account
where cust_Active_flag = ‘y’ and group = ‘001’