Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
261 views

ORACLE Database Health - Query Tunning

The document discusses database health checks and query tuning in Oracle databases. It provides details on using Oracle V$ views and system tables to check database health by monitoring instance uptime, tablespace space usage, and object status. It also discusses using the EXPLAIN PLAN to view query execution plans and optimization techniques like analyzing objects to collect statistics and enable cost-based optimization. Hints are mentioned as a way to guide the optimizer's choice of plans.

Uploaded by

Rishi Mathur
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
261 views

ORACLE Database Health - Query Tunning

The document discusses database health checks and query tuning in Oracle databases. It provides details on using Oracle V$ views and system tables to check database health by monitoring instance uptime, tablespace space usage, and object status. It also discusses using the EXPLAIN PLAN to view query execution plans and optimization techniques like analyzing objects to collect statistics and enable cost-based optimization. Hints are mentioned as a way to guide the optimizer's choice of plans.

Uploaded by

Rishi Mathur
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 55

ORACLE Database Health

&
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.

prompt #### Instance Up Time ####


select 'Hostname : ' || host_name
,'Instance Name : ' || instance_name
,'Started At : ' || to_char(startup_time,'DD-MON-YYYY HH24:MI:SS')
stime
,'Uptime : ' || floor(sysdate - startup_time) || ' days(s) ' ||
trunc( 24*((sysdate-startup_time) -
trunc(sysdate-startup_time))) || ' hour(s) ' ||
mod(trunc(1440*((sysdate-startup_time) -
trunc(sysdate-startup_time))), 60) ||' minute(s) ' ||
mod(trunc(86400*((sysdate-startup_time) -
trunc(sysdate-startup_time))), 60) ||' seconds' uptime
from sys.v_$instance;

ORACLE V$ Views & Sys Tables


 sys.dba_tablespaces :- Dictionary view provides the list of
all tablespaces present in the database.
 sys.dba_data_files :- Dictionary view provides the list of all
physical datafiles and their size. DBA_DATA_FILES also
provides the path of the data files in the system. Each data
file is associated with only one tablespace. But a
tablespace is associated with more than one data file.
”Bytes” column present in DBA_DATA_FILES denote the
total bytes allocated to a data file.
 sys.dba_free_space :- Dictionary view provides the free
space information associated with each data file. ”Bytes”
column present in DBA_free_space denote the total free
space in bytes available in a data file.

ORACLE V$ Views & Sys Tables


 Below query calculates the total file size allocated from dba_data_files view, total free
space from dba_free_space view, and then calculates the sum by grouping the data files
associated with a tablespace. This script will help in determining the free space available for
tablespace and can alarm team before ending up in tablespace issues.

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

ORACLE V$ Views & Sys


Tables .. .contd..
 user_objects , sys.dba_objects :- It provides the details
about each object present in user schema (user_objects) or
complete schema (sys.dba_objects).

SELECT object_type, status, COUNT(*) cnt


FROM user_objects
GROUP BY object_type,status;

SELECT owner, object_type, SUBSTR(object_name,1,30)


object_name
FROM sys.dba_objects
WHERE status='INVALID'
ORDER BY object_type;
 user_tables :- Details about the user created tables. To find
ORACLE V$ Views
which is portioned & Sys
table use below query.
SELECT table name FROM user tables WHERE
Tables .. .contd..
partitioned='YES';
 Sys.dba_segments :- Storage allocated for all database
segments.
Checking Max Extents Status:
SELECT segment_name, segment_type, extents,
max_extents FROM sys.dba_segments WHERE
max_extents-extents<100;

ANY partitioned Object approaching TO MAX extents:


SELECT
PARTITION_NAME,EXTENTS,MAX_EXTENTS,NEXT_EXTENT,
max_extents-NVL(next_extent,0) FROM sys.dba_segments
WHERE max_extents-NVL(next_extent,0) < 1000
AND partition_name IS NOT NULL;
 Sample Script Attached for DB Health Check :-

ORACLE V$ Views & Sys SQL File

Tables .. .contd..
Monitor the size of the database which
can avoid the tablespace issues.

Make you DB clean by validating invalid


Objects.

Reduction in US DBA dependency

Monitor the performance of database.

Benefits for DB Health Check


Why Tuning is Required :-

To Improve Response Time

To Improve Batch throughput

To ensure scalability

To reduce system load

To avoid hardware upgrade.

Oracle Query Tuning


Create Cursor Allocate Memory for Cursor

Parse SQL Check Syntax and Security

Associate Program Variable with SQL


Bind Variable

Execute DML Statement or Prepare to Query


Execute Cursor

Query ? Fetch Rows Retrieved one or more rows

Close Cursor SQL Execution Ended

Oracle Query Tuning- SQL


Re-execute
Cursor
Re-execute SQL statement

Processing .. De-allocate Cursor memory and discarded


Close Cursor
 The Combination of steps Oracle uses to execute
statement is called Execution Plan

 It is the process of determining the “Optimal path” to


retrieve Data. There are following approach for Query
Optimization.
 Rule based :- Based on predefined set precedence
rule. Does not take into account the “volume of data”.
 Cost Based :- Takes into account statistical
information related to volume and distribution of data
with in table.
Oracle Query Tuning-
Execution Plan & Query
Optimization
Goals of Query Optimization

Rule :- This specify that optimizer has to


take rule based approach to optimization.

Choose :- This specify the cost based


approach if any table is analyze. If no table
is analyze then use rule based approach.

Oracle Query Tuning- Query


Optimization
Statistics- Cost Based Approach :-
The cost based approach used the statistics to
estimated the cost of each execution plan.

These
stats are generated using “Analyze”
command.

Using these Statistics, the optimizer estimates how


much the I/O,CPU Time and memory are required
to execute the particular SQL statement with
specified plan.

Oracle Query Tuning- Query


Optimization – Cost Based
Query Tuning – Rule Based
Approach
 Rule based optimizer uses a set
of 15 rules to determine how to
best process a query. The rule
chosen is based strictly on query
structure and pays no attention to
the number of rows, partitioning
or other query specific features
and statistics.
 The analyze command within the Oracle database collects statistics about an
object. The information includes the distribution of data, the number of rows in
the table and other important statistics. This information is collected and
supplied to the optimizer to allow for the best possible execution path of a SQL
statement.
 If you are using the cost-based optimizer you must analyze your database
objects. As well when you are analyzing your objects your should tell the
database the size of the sample it should use if you wish to have the database
estimate statistics (this is a faster method). If you wish for an exact
computation of statistics you would use the "compute" argument.
 To estimate statistics:
ANALYZE TABLE tablename ESTIMATE STATISTICS SAMPLE 30 PERCENT;
 To compute statistics:
ANALYZE TABLE tablename COMPUTE STATISTICS;
 You should also remember that statistics get old and dated, you should
regularly schedule to re-analyze your tables and indexes.

Query Tuning – Analyze


Command
Query Tuning – Analyze
Command contd.
COMPUTE STATISTICS :-
When computing statistics, an entire object is scanned to gather data about the object. This data is
used by Oracle to compute exact statistics about the object. Slight variances throughout the object
are accounted for in these computed statistics. Because an entire object is scanned to gather
information for computed statistics, the larger the size of an object, the more work that is required
to gather the necessary information.

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.

Viewing Object Statistics:-


The statistics can be queried using the following data dictionary views:
USER_INDEXES, ALL_INDEXES, DBA_INDEXES
USER_TABLES, ALL_TABLES, DBA_TABLES
USER_TAB_COLUMNS, ALL_TAB_COLUMNS, DBA_TAB_COLUMNS
 Statistics Details:
◦ Number of used blocks in each table
◦ Number of rows in each table
◦ Number of distinct values for each column
◦ Number of nulls in each column
◦ Average length of each column
◦ Number of branch levels of index
◦ Number of leaf-blocks in index
◦ Clustering factor of index

 DBMS_STATS and Analyze command:


The advantage of DBMS_STATS is
- easier to automate
- can analyze external tables.
- can gather system statistics ( 9i onwards )
- DBMS_STATS gathers statistics only for cost-based optimization; it does not gather other statistics. For
example, the table statistics gathered by DBMS_STATS include the number of rows, number of blocks
currently containing data, and average row length but not the number of chained rows, average free space,
or number of unused data blocks.

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.

Query Tuning – Analyze


Command contd.
Check syntax +
semantics

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.

Query Tuning – Explain Plan


 Row Source :- A set of rows used in a query may be a select from a base object or
the result set returned by joining 2 earlier row sources.

 Predicate :- where clause of a query

 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.

 RBO : - Rule Based Optimization

 CBO :- Cost Based Optimization

Query Tuning – Explain Plan -


Terminology
Query Tuning – Explain Plan –
contd..
 How does Oracle access data?
 At the physical level Oracle reads
blocks of data. The smallest
amount of data read is a single
Oracle block, the largest is
constrained by operating system
limits (and multiblock i/o).
 Logically Oracle finds the data to
read by using the following
methods:
◦ Full Table Scan (FTS)

◦ Index Lookup (unique & non-


unique)
 index unique scan
 index range scan
 index full scan
 index fast full scan
◦ Rowid
 Simple Explain Plan :-
Query Plan
-----------------------------------------
SELECT STATEMENT     [CHOOSE] Cost=1234
  TABLE ACCESS FULL LARGE [:Q65001] [ANALYZED]
 In this case TABLE ACCESS FULL LARGE is the first operation. This statement
means we are doing a full table scan of table LARGE.
 The resultant row source is passed up to the next level of the query for
processing. (SELECT STATEMENT)
 [CHOOSE] is an indication of the optimizer_goal for the query
 Explain plan below indicates the use of the CBO because the cost field has values
SELECT STATEMENT     [CHOOSE] Cost=1234
 Explain plan below indicates the use of the RBO because the cost field is Empty
SELECT STATEMENT     [CHOOSE] Cost=
 [:Q65001] indicates that this particular part of the query is being executed in
parallel.
 [ANALYZED] indicates that the object in question has been analyzed

Query Tuning – Explain Plan


Understanding
 Access Methods in detail
 Full Table Scan (FTS) :- In a FTS operation, the whole table is read up to the high water
mark (HWM). HWM marks the last block in the table that has ever had data written to it
Example FTS explain plan:
SQL> explain plan for select * from dual;

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 Tuning – Explain Plan -


Access Methods
 The index name in this case is EMP_I1. If all the required data resides in the index then a
table lookup may be unnecessary and all you will see is an index access with no table access.
 In the following example all the columns (empno) are in the index. Notice that no table
access takes place:
 SQL> explain plan for
select empno from emp where empno=10;

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 Tuning – Explain Plan -


Access Methods contd..
 In this case the index is sorted so there rows will be returned in the order of the
index hence a sort is unnecessary.
 SQL> explain plan for
select /*+ Full(emp) */ empno,ename from emp
where empno> 7876 order by empno;
 Query Plan
-------------------------------------------------------------
SELECT STATEMENT   [CHOOSE] Cost=9
  SORT ORDER BY
    TABLE ACCESS FULL EMP [ANALYZED]  Cost=1 Card=2 Bytes=66
 Because we have forced a FTS the data is unsorted and so we must sort the data
after it has been retrieved.
 There are 4 methods of index lookup:
 index unique scan
 index range scan
 index full scan
 index fast full scan

Query Tuning – Explain Plan -


Access Methods contd..
Index unique scan :- Method for looking up a single key value
via a unique index. Always returns a single value You must
supply AT LEAST the leading column of the index to access data
via the index, However this may return > 1 row as the
uniqueness will not be guaranteed.

SQL> explain plan for


select empno,ename from emp where empno=10;

Query Plan
------------------------------------
SELECT STATEMENT [CHOOSE] Cost=1
TABLE ACCESS BY ROWID EMP [ANALYZED]
    INDEX UNIQUE SCAN EMP_I1

Query Tuning – Explain Plan -


Access Methods contd..
Index range scan
 Method for accessing multiple column values You must supply AT LEAST the
leading column of the index to access data via the index Can be used for range
operations (e.g. > < <> >= <= between)
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]
 A non-unique index may return multiple values for the predicate col1 = 5 and
will use an index range scan
SQL> explain plan for select mgr from emp where mgr = 5
Query plan
--------------------
SELECT STATEMENT [CHOOSE] Cost=1
  INDEX RANGE SCAN EMP_I2 [ANALYZED]

Query Tuning – Explain Plan -


Access Methods contd..
Index Full Scan
In certain circumstances it is possible for the whole
index to be scanned as opposed to a range scan (i.e.
where no constraining predicates are provided for a
table).
 Create concatenated index on big_emp (empno,ename)
SQL> explain plan for select empno,ename
     from big_emp order by empno,ename;
Query Plan
------------------------------------------------------------
SELECT STATEMENT   [CHOOSE] Cost=26
INDEX FULL SCAN BE_IX [ANALYZED]

Query Tuning – Explain Plan -


Access Methods contd..
INDEX FAST FULL SCAN :- Scans all the block in the index Rows are not
returned in sorted order. It is the mechanism behind fast index create and
recreate. Index BE_IX is a concatenated index on big_emp
(empno,ename)
SQL> explain plan for select empno,ename from big_emp;

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]

Query Tuning – Explain Plan -


Access Methods contd..
Rowid :- This is the quickest access method
available Oracle simply retrieves the block
specified and extracts the rows it is interested in.

Joins
:- A Join is a predicate that attempts to
combine 2 row sources.

Joins Type :-
 Sort Merge Join (SMJ)
 Nested Loops (NL)
 Hash Join

Query Tuning – Explain Plan -


Access Methods contd..
Sort Merge Join :-
Rows are produced by Row Source 1 and are
then sorted.
Rows from Row Source 2 are then produced
and sorted by the same sort key as Row
Source 1.
Row Source 1 and 2 are NOT accessed
concurrently.
MERGE
Sorted rows fromIf the
both sides are thenas long asmerged
row sources are already (known to be) sorted then
the sort operation is unnecessary both 'sides' are
together
Sort (joined).
Sort
sorted using the same key. Presorted row sources include
indexed columns and row sources that have already been
sorted in earlier steps. Although the merge of the 2 row

Query Tuning – Explain Plan -


sources is handled serially, the row sources could be
Row Row accessed
in parallel.

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.

Tuning – Explain Plan - Access


Methods contd..
Nested Loops :-
First we return all the rows from row source 1 Then we
probe row source 2 once for each row returned from row
source 1
Row source 1
~~~~~~~~~~~~
Row 1 --------------       -- Probe ->       Row source 2
Row 2 --------------       -- Probe ->       Row source 2
Row 3 --------------       -- Probe ->       Row source 2
Row source 1 is known as the outer table
Row source 2 is known as the inner table
Nested Loop

Tuning – Explain Plan


Access A - Access
Access B
(Full) (ROWID)
Methods contd..
Index Access
SQL> explain plan for
select b.dname, b.sql
from emp a, dept b
where a.deptno = b.deptno;
Query Plan
-------------------------
SELECT STATEMENT [CHOOSE] Cost=5
  NESTED LOOPS
    TABLE ACCESS FULL EMP [ANALYZED]
TABLE ACCESS BY ROWID DEPT [ANALYZED]
  INDEX UNIQUE SCAN PK_DEPT [ANALYZED]
   

Tuning – Explain Plan - Access


Methods contd..
Hash Join :-
More efficient in theory than NL & SMJ.
Only accessible via the CBO
Smallest row source is chosen and used to build a
hash table and a bitmap
The second row source is hashed and checked against
the hash table looking for joins.
The bitmap is used as a quick lookup to check if rows
are in the hash table and are especially
Row source 1
(build input)
useful
Row source 2when
(probe)
the hash table is too large to fit in memory.
Tuning – Explain Plan - Access
Hash joins are enabled by the parameter Hash table

HASH_JOIN_ENABLED=TRUE in thein MEMORY init.ora or


and bitmap filter

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

Tuning – Explain Plan - Access


Methods contd..
Query Tuning- Join
Comparisons
Type of Join Nested Loops Sort-Merge Hash Join

When can be used Any join Equi joins only Equi joins only

Optimizer hint USE_NL USE_MERGE USE_HASH

Resource concerns CPU Temporary segments Memory

init.ora None sort_area_size hash_join_enabled


parameters db_file_multiblock_read_count hash_area_size
hash_multiblock_io_count

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

Tuning – Explain Plan - Access


Methods contd..
The plan table is the table that Oracle fills when you have it explain an
execution plan for an SQL statement. You must make sure such a plan
table exists. Oracle ships with the script UTLXPLAN.SQL which creates
this table, named PLAN_TABLE

Arguably, the most important fields within the plan table are
operation, option, object_name, id, and parent_id.

sql*plus automatically explains the plan for you if autotrace is enabled.

TKPROF stands for transient kernel profiler. To be able to use


TKPROF, you must first enable sql trace. It is used to read the sql trace
and help us in tuning by giving the Explain plan by reading trace.

Tuning – Obtain Explain Plan


Hints are exactly what it means–clues or
directives that will assist the optimizer in choosing
an execution plan.
The following syntax is used for hints:

select /*+ HINT */ name


from emp
where id =1;

Where HINT is replaced by the hint text.

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.

Tuning – HINTS contd..


Commonly Used Hints
FULL
INDEX
ORDERED
USE_NL
PUSH_SUBQ
PARALLEL
ALL_ROWS
FIRST_ROWS(n)

Tuning- Common HINTS


FULL :- The FULL hint explicitly chooses a full table scan for the
specified table.
SELECT /*+ FULL(e) */ employee_id, last_name FROM employees e
WHERE last_name LIKE :b1;
INDEX :- The INDEX hint explicitly chooses an index scan for the
specified table.
SELECT /*+ INDEX (employees emp_department_ix)*/ employee_id,
department_id FROM employees WHERE department_id > 50;
ORDERED :- The ORDERED hint causes Oracle to join tables in the
order in which they appear in the FROM clause
SELECT /*+ORDERED */ o.order_id, c.customer_id, l.unit_price *
l.quantity FROM customers c, order_items l, orders o WHERE
c.cust_last_name = :b1 AND o.customer_id = c.customer_id AND
o.order_id = l.order_id;

Tuning- Common HINTS –


contd..
USE_NL :- The USE_NL hint causes Oracle to join each specified table
to another row source with a nested loops join, using the specified
table as the inner table.
SELECT /*+ USE_NL(l h) */ h.customer_id, l.unit_price * l.quantity
FROM orders h ,order_items l WHERE l.order_id = h.order_id;
PUSH_SUBQ :- The PUSH_SUBQ hint causes non-merged subqueries
to be evaluated at the earliest possible step in the execution plan.
Select /*+ PUSH_SUBQ */ * from emp where emp_dept_no in
(select a_dept_no from a where a_dept_no >10)
PARALLEL :- The PARALLEL hint lets you specify the desired number
of concurrent servers that can be used for a parallel operation. The
hint applies to the SELECT, INSERT, UPDATE, and DELETE portions of
a statement, as well as to the table scan portion.
SELECT /*+ Full(A) PARALLEL(A,8) */ from A where col2 like ‘%’;

Tuning- Common HINTS –


contd..
ALL_ROWS :- The ALL_ROWS hint explicitly chooses the
query optimization approach to optimize a statement block
with a goal of best throughput (that is, minimum total
resource consumption).
SELECT /*+ ALL_ROWS */ employee_id, last_name, salary,
job_id FROM employees WHERE employee_id = 7566;
FIRST_ROWS(n) :- The FIRST_ROWS(n) hint instructs Oracle
to optimize an individual SQL statement for fast response,
choosing the plan that returns the first n rows most
efficiently
SELECT /*+ FIRST_ROWS(10) */ employee_id, last_name,
salary, job_id FROM employees WHERE employee_id =
7566;

Tuning- Common HINTS –


contd..
 Optimize where clause
 Truncate table if possible then delete.
 Don't create index on a column that is modified highly.
 Don't create index on columns that appear in WHERE clause and
uses a function other than MAX, MIN.
 Use SET TRANSACTION where possible use ROLLBACK SEGMENT
 Retrieve only necessary column
 Always use joins instead of sub-quires.
 Avoid NOT in where clause use between “>=“ etc.
 Avoid FTS until its necessary
 Use column name in order by and use it only when its necessary.
 Be care full of group by or order by desc etc
 Use decode to avoid scanning same row repatedly

Tuning – Do and Don’t Hints


 Do Not Use:
Use
Select * from
Account
Where substr(ac_acct_no,1,1) = ‘9’
 Use:
Select * from
Account
Where ac_acct_no like ‘9%’

 Do Not Use:
Select *
From fin_trxn
Where ft_trxn_ref_no != 0
 Use:
Select *
From fin_trxn
Where ft_trxn_ref_no > 0

Tuning – Do and Don’t Hints


 Do Not Use:
Select *
From account
Where ac_type || ac_branch = ‘sav001’

 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

Tuning – Do and Don’t Hints


 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
 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)

Tuning – Do and Don’t Hints


 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)

 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
 

Tuning – Do and Don’t Hints


 Do Not Use:
Select count( *)
From BROKER
 
 Use:
Select count(PRIMARY_KEY or
a non null
INDEX column or
1)
From Broker
 Do Not Use:

select *
from account
where cust_Active_flag = ‘y’ having group = ‘001’

  Use: select *
from account
where cust_Active_flag = ‘y’ and group = ‘001’

Tuning – Do and Don’t Hints


 Do Not Use:
select * from Student
where STUDENT_NUM not in
(select STUDENT_NUM from CLASS)
 
 Use:
select * from STUDENT C
where not exists
(select 1 from CLASS A where
A.STUDENT_NUM = C.STUDENT_NUM)
 Do Not Use:

select * from system_user


where su_user_id not in
(select ac_user from account)

 Use: select * from system_user


where su_user_id in
(select su_user_id from system_user
minus
select ac_user from account)

Tuning – Do and Don’t Hints

You might also like