Saturday, December 24, 2011

Overview of SQL Plan management

Overview of SQL Plan Management

SQL plan management is a preventative mechanism that records and evaluates the execution plans of SQL statements over time. This mechanism can build aSQL plan baseline, which is a set of accepted plans for a SQL statement. The accepted plans have been proven to perform well.

The plan history is the set of plans, both accepted and not accepted, that the optimizer generates for a SQL statement over time Because only accepted plans are in the SQL plan baseline, the plans in the baseline form a susbset of the plan history. For example, after the optimizer generates the first acceptable plan for a SQL plan baseline, subsequent plans are part of the plan history but not part of the plan baseline.


When automatic plan capture is enabled, the database automatically creates and maintains the plan history for SQL statements using information provided by the optimizer. The plan history includes relevant information used by the optimizer to reproduce an execution plan, such as the SQL text, outline, bind variables, and compilation environment.


To enable automatic plan capture, set the OPTIMIZER_CAPTURE_SQL_PLAN_BASELINES initialization parameter to TRUE. By default, this parameter is FALSE.

To load plans from a SQL tuning set, use the LOAD_PLANS_FROM_SQLSET function of the DBMS_SPM package. The following example loads the plans stored in the SQL tuning set named tset1:
DECLARE   my_plans PLS_INTEGER; BEGIN   my_plans := DBMS_SPM.LOAD_PLANS_FROM_SQLSET( sqlset_name => 'tset1'); END; / 

To load plans from Automatic Workload Repository (AWR), load the plans stored in AWR snapshots into a SQL tuning set before using theLOAD_PLANS_FROM_SQLSET function as described in this section.

like this

BEGIN   DBMS_SQLTUNE.CREATE_SQLSET(     sqlset_name => 'my_sql_tuning_set',      description  => 'I/O intensive workload'); END; / 

-- Load the SQL set from the Automatic Workload Repository (AWR). DECLARE   l_cursor  DBMS_SQLTUNE.sqlset_cursor; BEGIN   OPEN l_cursor FOR     SELECT VALUE(p)     FROM   TABLE (DBMS_SQLTUNE.select_workload_repository (                     765,  -- begin_snap                     766,  -- end_snap                     NULL, -- basic_filter                     NULL, -- object_filter                     NULL, -- ranking_measure1                     NULL, -- ranking_measure2                     NULL, -- ranking_measure3                     NULL, -- result_percentage                     10)   -- result_limit                   ) p;    DBMS_SQLTUNE.load_sqlset (     sqlset_name     => 'my_sql_tuning_set',     populate_cursor => l_cursor); END; / 


To load plans from the shared SQL area, use the LOAD_PLANS_FROM_CURSOR_CACHE function of the DBMS_SPM package. In the following example, Oracle Database loads the plans located in the shared SQL area for the SQL statement identified by its sql_id:

DECLARE   my_plans PLS_INTEGER; BEGIN   my_plans := DBMS_SPM.LOAD_PLANS_FROM_CURSOR_CACHE( sql_id => '99twu5t2dn5xd'); END; 
/

To view the plans stored in the SQL plan baseline for a given statement, use the DISPLAY_SQL_PLAN_BASELINE function of the DBMS_XPLAN package. The following example displays one or more execution plans for the specified SQL statement, specified by the handle (sql_handle):
SELECT * FROM TABLE(      DBMS_XPLAN.DISPLAY_SQL_PLAN_BASELINE(          sql_handle=>'SYS_SQL_209d10fabbedc741',          format=>'basic')); 

Alternatively, you can display a single plan by supplying a plan name (plan_name).


You can also display SQL plan baseline information using a SELECT statement directly on the DBA_SQL_PLAN_BASELINES view, as shown in the following example:

SELECT SQL_HANDLE, PLAN_NAME, ENABLED, ACCEPTED, FIXED  FROM   DBA_SQL_PLAN_BASELINES;   SQL_HANDLE                PLAN_NAME                      ENA  ACC    FIX ------------------------------------------------------------------------ SYS_SQL_209d10fabbedc741  SYS_SQL_PLAN_bbedc741a57b5fc2  YES  NO     NO SYS_SQL_209d10fabbedc741  SYS_SQL_PLAN_bbedc741f554c408  YES  YES    NO
ENABLED : Bu SQL için yeni planlar oluşturulduğunda Baseline 'a alınır.
ACCEPTED : Kullanılan exec plan'ı tutan Baseline
FIXED : Artık bu SQL için yeni plan aranmaz. Yeni plan oluştuğunda base line'a alınmaz 
The optimizer does not add new plans to a fixed SQL plan baseline. Because the optimizer does not automatically add new plans, the database does not evolve a fixed SQL plan baseline when you execute DBMS_SPM.EVOLVE_SQL_PLAN_BASELINE. However, you can evolve a fixed SQL plan baseline by manually loading new plans into it from the shared SQL area or a SQL tuning set.

During the SQL plan baseline selection phase, Oracle Database detects plan changes based on the stored plan history, and selects plans to avoid potential performance regressions for a set of SQL statements.

Each time the database compiles a SQL statement, the optimizer does the following:

  1. Uses a cost-based search method to build a best-cost plan

  2. Tries to find a matching plan in the SQL plan baseline

  3. Does either of the following depending on whether a match is found:

    • If found, then the optimizer proceeds using the matched plan

    • If not found, then the optimizer evaluates the cost of each accepted plan in the SQL plan baseline and selects the plan with the lowest cost



Sunday, December 4, 2011

SQL MONITORING

Oracle 11g automatically monitors SQL statements if they are run in parallel, or consume 5 or more seconds of CPU or I/O in a single execution. This allows resource intensive SQL to be monitored as it is executing, as well as giving access to detailed information about queries once they are complete.

SQL monitoring requires the STATISTICS_LEVEL parameter to be set to 'TYPICAL' or 'ALL', and the CONTROL_MANAGEMENT_PACK_ACCESS parameter set to 'DIAGNOSTIC+TUNING'.

The MONITOR hint switches on SQL monitoring for statements that would not otherwise initiate it.

select /*+ monitor */. ....

Monitored statements can be identified using the V$SQL_MONITOR view.

V$SQL_MONITOR displays SQL statements whose execution have been (or are being) monitored by Oracle. An entry is created in V$SQL_MONITOR every time the execution of a SQL statement is being monitored. SQL monitoring is automatically started when a SQL statement runs parallel or when it has consumed at least 5 seconds of CPU or I/O time.

When the SQL statement being monitored is executing, statistics in V$SQL_MONITOR are generally refreshed in near real time, once every second. Once the execution ends, monitoring information is not deleted immediately. Instead, it is kept in V$SQL_MONITOR for at least one minute. The entry will eventually be deleted to reclaim its space as new statements are monitored.

Column Datatype Description
KEY NUMBER Artificial join key to efficiently join V$SQL_MONITOR with its corresponding plan level monitoring statistics stored in V$SQL_PLAN_MONITOR
STATUS VARCHAR2(19) SQL execution status:
QUEUED - SQL statement is queued
EXECUTING - SQL statement is still executing
DONE (ERROR) - Execution terminated with an error
DONE (FIRST N ROWS) - Execution terminated by the application before all rows were fetched
DONE (ALL ROWS) - Execution terminated and all rows were fetched
DONE - Execution terminated (parallel execution)
USER# NUMBER User ID of the database user who issued the SQL being monitored
USERNAME VARCHAR2(30) User name of the database user who issued the SQL being monitored
MODULEFoot 1 VARCHAR2(48) Name of the executing module when sampled, as set by the DBMS_APPLICATION_INFO.SET_MODULE procedure
ACTIONFootref 1 VARCHAR2(32) Name of the executing action when sampled, as set by the DBMS_APPLICATION_INFO.SET_ACTION procedure
SERVICE_NAME VARCHAR2(64) Service name of the user session
CLIENT_IDENTIFIER VARCHAR2(64) Client identifier from the user session
CLIENT_INFO VARCHAR2(64) Client information for the user session
PROGRAM VARCHAR2(48) Name of the OS program that issued the monitored SQL
PLSQL_ENTRY_OBJECT_ID NUMBER Object ID of the top-most PL/SQL subprogram on the stack; NULL if there is no PL/SQL subprogram on the stack
PLSQL_ENTRY_SUBPROGRAM_ID NUMBER Subprogram ID of the top-most PL/SQL subprogram on the stack; NULL if there is no PL/SQL subprogram on the stack
PLSQL_OBJECT_ID NUMBER Object ID of the currently executing PL/SQL subprogram; NULL if executing SQL
PLSQL_SUBPROGRAM_ID NUMBER Subprogram ID of the currently executing PL/SQL object; NULL if executing SQL
FIRST_REFRESH_TIME DATE Time when monitoring of the SQL statement started, generally a few seconds after execution start time
LAST_REFRESH_TIME DATE Time when statistics in V$SQL_MONITOR were last updated for the SQL statement. Statistics are generally refreshed every second when the statement executes.
REFRESH_COUNT NUMBER Number of times V$SQL_MONITOR statistics have been refreshed (generally once every second when the SQL statement executes)
SID NUMBER Session identifier executing (or having executed) the SQL statement being monitored
PROCESS_NAME VARCHAR2(5) Process name identifier executing (or having executed)the statement; ora if the process is foreground, else the background process name (for example, p001 for PX server p001)
SQL_ID VARCHAR2(13) SQL identifier of the statement being monitored
SQL_TEXT VARCHAR2(2000) Up to the first 2000 characters of the text of the SQL being monitored
IS_FULL_SQLTEXT VARCHAR2(1) Indicates whether the SQL_TEXT column has the entire SQL text (Y) or not (N)
SQL_EXEC_START DATE Time when the execution started
SQL_EXEC_ID NUMBER Execution identifier. Together, the three columns SQL_ID, SQL_EXEC_START, and SQL_EXEC_ID represent the execution key. The execution key is used to uniquely identify one execution of the SQL statement.
SQL_PLAN_HASH_VALUE NUMBER SQL Plan hash value
EXACT_MATCHING_SIGNATURE NUMBER Signature calculated on the normalized SQL text. The normalization includes the removal of white space and the uppercasing of all non-literal strings.
FORCE_MATCHING_SIGNATURE NUMBER Same as EXACT_MATCHING_SIGNATURE but literals in the SQL text are replaced by binds
SQL_CHILD_ADDRESS RAW(4 | 8) Address of the child cursor (can be used with SQL_ID to join with V$SQL)
SESSION_SERIAL# NUMBER Session serial number executing the statement being monitored
PX_IS_CROSS_INSTANCE VARCHAR2(1) Indicates whether the SQL statement ran parallel across multiple instances (Y) or not (N)
PX_MAXDOP NUMBER Maximum degree of parallelism for any plan operation executed on behalf of the monitored SQL
PX_MAXDOP_INSTANCES NUMBER Number of database instances touched at the maximum degree of parallelism
PX_SERVERS_REQUESTED NUMBER Total number of parallel execution servers requested to execute the monitored SQL
PX_SERVERS_ALLOCATED NUMBER Actual number of parallel execution servers allocated to execute the query
PX_SERVER# NUMBER Logical parallel execution server process number executing (or having executed) the statement being monitored; NULL if this monitoring entry is not associated with an execution server. This is a logical number within the parallel server set (see SERVER# in V$PX_SESSION).
PX_SERVER_GROUP NUMBER Logical parallel execution server group number to which PX_SERVER# belongs (see SERVER_GROUP in V$PX_SESSION); NULL if this monitoring entry is not associated with a parallel execution server. This value is generally 1 unless the SQL statement has one or more parallel sub-queries.
PX_SERVER_SET NUMBER Number (1 or 2) of the logical set of parallel execution servers to which PX_SERVER# belongs (see SERVER_SET in V$PX_SESSION); NULL if this monitoring entry is not associated with a parallel execution server
PX_QCINST_ID NUMBER Instance identifier where the parallel execution coordinator runs; NULL if PX_SERVER# is NULL
PX_QCSID NUMBER Session identifier for the parallel execution coordinator; NULL if PX_SERVER# is NULL
ERROR_NUMBER VARCHAR2(40) Error number encountered in case a SQL fails to execute successfully (for example, 932 in case of ORA-00932)
ERROR_FACILITY VARCHAR2(4) Error facility in case a SQL fails to execute successfully (for example, ORA in case of ORA-00932)
ERROR_MESSAGE VARCHAR2(256) Detailed error message displayed corresponding to the error number and error facility when a SQL fails to execute successfully
BINDS_XML CLOB Information about bind variables used with the SQL, such as name, position, value, data type, and so on (stored in XML format)
OTHER_XML CLOB Additional information about SQL execution stored in XML format
ELAPSED_TIME NUMBER Elapsed time (in microseconds); updated as the statement executes
QUEUING_TIME NUMBER Duration of time (in microseconds) spent by SQL in the statement queue
CPU_TIME NUMBER CPU time (in microseconds); updated as the statement executes
FETCHES NUMBER Number of fetches associated with the SQL statement; updated as the statement executes
BUFFER_GETS NUMBER Number of buffer get operations; updated as the statement executes
DISK_READS NUMBER Number of disk reads; updated as the statement executes
DIRECT_WRITES NUMBER Number of direct writes; updated as the statement executes
IO_INTERCONNECT_BYTES NUMBER Number of I/O bytes exchanged between Oracle Database and the storage system
PHYSICAL_READ_REQUESTS NUMBER Number of physical read I/O requests issued by the monitored SQL
PHYSICAL_READ_BYTES NUMBER Number of bytes read from disks by the monitored SQL
PHYSICAL_WRITE_REQUESTS NUMBER Number of physical write I/O requests issued by the monitored SQL
PHYSICAL_WRITE_BYTES NUMBER Number of bytes written to disks by the monitored SQL
APPLICATION_WAIT_TIME NUMBER Application wait time (in microseconds); updated as the statement executes
CONCURRENCY_WAIT_TIME NUMBER Concurrency wait time (in microseconds); updated as the statement executes
CLUSTER_WAIT_TIME NUMBER Cluster wait time (in microseconds); updated as the statement executes


SET LINESIZE 200 COLUMN sql_text FORMAT A80  SELECT sql_id, status, sql_text FROM   v$sql_monitor WHERE  username = 'SCOTT';
SET LONG 1000000 SET LONGCHUNKSIZE 1000000 SET LINESIZE 1000 SET PAGESIZE 0 SET TRIM ON SET TRIMSPOOL ON SET ECHO OFF SET FEEDBACK OFF  SPOOL /host/report_sql_monitor.htm SELECT DBMS_SQLTUNE.report_sql_monitor(   sql_id       => '526mvccm5nfy4',   type         => 'HTML',   report_level => 'ALL') AS report FROM dual; SPOOL OFF

Examples of the output for each available TYPE are displayed below.

-------------------------


REPORT_SQL_MONITOR_LIST

The REPORT_SQL_MONITOR_LIST function was added in Oracle 11g Release 2 to generate a summary screen, similar to that on the "Monitored SQL Executions" page of Enterprise Manager.


SET LONG 1000000 SET LONGCHUNKSIZE 1000000 SET LINESIZE 1000 SET PAGESIZE 0 SET TRIM ON SET TRIMSPOOL ON SET ECHO OFF SET FEEDBACK OFF  SPOOL /host/report_sql_monitor_list.htm SELECT DBMS_SQLTUNE.report_sql_monitor_list(   type         => 'HTML',   report_level => 'ALL') AS report FROM dual; SPOOL OFF


V$SQL_PLAN_MONITOR displays plan level monitoring statistics for each SQL statement found in V$SQL_MONITOR. Each row in V$SQL_PLAN_MONITOR corresponds to an operation of the execution plan being monitored. As with V$SQL_MONITOR, statistics exposed in V$SQL_PLAN_MONITOR are generally updated every second when the statement executes. These statistics are recycled on the same basis as V$SQL_MONITOR.



Thursday, November 10, 2011

Getting the value of hidden parameters

for example the value of _smm_max_size

select a.ksppinm name, b.ksppstvl value, a.ksppdesc description
from sys.x$ksppi a, sys.x$ksppcv b
where a.indx = b.indx
and a.ksppinm = '_smm_max_size';

Monday, November 7, 2011

oracle 9i shared server

Oracle 9i Shared Server nasıl çalışıyor.
 
1. Dispatcher tanımı gerekiyor.
Sessionlar  öncelikle bir listener’a bağlanıyorlar. Burada  client’ın tnsnames.ora sında SERVER=shared olmalı.
 
If shared server is configured and a client connection request arrives when no
dispatchers are registered, the requests can be handled by a dedicated server
process (configured in the listener.ora file). If you want a particular client
always to use a dispatcher, configure (SERVER=shared) in the connect data
portion of the connect descriptor. For example:
Configuring Shared Server 14-9 – net service qadministrator guide
sales=
(DESCRIPTION=
(ADDRESS=(PROTOCOL=tcp)(HOST=sales-server)(PORT=1521))
(CONNECT_DATA=
(SERVICE_NAME=sales.us.acme.com)
(SERVER=shared)))
 
Bu listener’da bu connection’ı Dispacther’a yönlendiriyor.
Dispatcher’da istekleri Shared serverlara circuit olarak koyuyor. Boş bir shared server işi alıp yapıp tekrar sonucu dispatcher’a dönüyor. Dispatcher’da client’a dönüyor.
Tanımlar şöyle oluyor.
 
Registering Information with a Nondefault Listener
If you want PMON to register with a local listener that does not use TCP/IP, port
1521, configure the LOCAL_LISTENER parameter in the initialization parameter file
to locate the local listener.
For a shared server environment, you can alternatively use the LISTENER attribute
of the DISPATCHERS parameter in the initialization parameter file to register the
dispatchers with a nondefault local listener. Because both the LOCAL_LISTENER
parameter and the LISTENER attribute enable PMON to register dispatcher
information with the listener, it is not necessary to specify both the parameter and
the attribute if the listener values are the same.
See Also: Oracle9i Database Reference for further information about
the SERVICE_NAMES and INSTANCE_NAME parameters
Configuring Service Registration
12-16 Oracle9i Net Services Administrator’s Guide
Set the LOCAL_LISTENER parameter as follows:
LOCAL_LISTENER=listener_alias
Set the LISTENER attribute as follows:
DISPATCHERS="(PROTOCOL=tcp)(LISTENER=listener_alias)"
listener_alias is then resolved to the listener protocol addresses through a
naming method, such as a tnsnames.ora file on the database server.
For example, if the listener is configured to listen on port 1421 rather than port 1521,
you can set the LOCAL_LISTENER parameter in the initialization parameter file as
follows:
LOCAL_LISTENER=listener1
Using the same listener example, you can set the LISTENER attribute as follows:
DISPATCHERS="(PROTOCOL=tcp)(LISTENER=listener1)"
You can then resolve listener1 in the local tnsnames.ora as follows:
listener1=
(DESCRIPTION=
(ADDRESS=(PROTOCOL=tcp)(HOST=sales-server)(PORT=1421)))
Notes:
n To dynamically update the LOCAL_LISTENER parameter, use
the SQL statement ALTER SYSTEM SET:
ALTER SYSTEM SET LOCAL_LISTENER=’listener_alias’
If you set the parameter to null with the statement that follows,
then the default local address of TCP/IP, port 1521 is assumed.
ALTER SYSTEM SET LOCAL_LISTENER=’’
See the Oracle9i SQL Reference for further information about the
ALTER SYSTEM SET statement.
n The LISTENER attribute overrides the LOCAL_LISTENER
parameter. As a result, the SQL statement ALTER SYSTEM SET
LOCAL_LISTENER does not affect the setting of this attribute.
Configuring Service Registration
Configuring and Administering the Listener 12-17
To register information with another local listener:
1. Configure the listener.ora file with the protocol address of the local
listener.
2. Configure the LOCAL_LISTENER parameter in the initialization parameter file
to locate the local listener. If you are using shared server, you can also use the
LISTENER attribute of the DISPATCHERS parameter in the initialization
parameter file.
3. Resolve the listener name alias for the LOCAL_LISTENER or the LISTENER
setting through a tnsnames.ora file or an Oracle Names server.
 
 
DB açıldığı zaman DISPATCHER’daki listener parametresine bakıyor. Buradaki değeri alıp tnsnames.ora ‘ya bakıyor . Buradaki IP ve PORT ‘u alıyor. Sonra bu IP+PORT’u dinleyen listener’ı buluyor. Bu listener’a diyorki. Kardeş ben dispatcher lar açtım. Bunların parametreleri falan falan
Artık sana SERVER=shared gelenleri bu dispatcher’a gönder diyor.
 
Bu listener’ın özelliği listener.ora’da tanımlı olması  ama sadece TCP/IP protokol adreslerinin olması.
Service vereceği yerlerin olmamasıdır. Service vereceği yer Dynamic registration ile halledilmektedir.
Bu kısmına gerek yoktur.
 
SID_LIST_LISTENER=
(SID_LIST=
(SID_DESC=
(GLOBAL_DBNAME=sales.us.acme.com)
(ORACLE_HOME=/oracle9i)
(SID_NAME=sales))
(SID_DESC=
(SID_NAME=plsextproc)
(ORACLE_HOME=/oracle9i)
(PROGRAM=extproc)))
A listener is configured with one or more listening protocol addresses, information
about supported services, and parameters that control its runtime behavior. The
listener configuration is stored in a configuration file named listener.ora.
Because all of the configuration parameters have default values, it is possible to
start and use a listener with no configuration. This default listener has a name of
LISTENER, supports no services upon startup, and listens on the following TCP/IP
protocol address:
(ADDRESS=(PROTOCOL=tcp)(HOST=host_name)(PORT=1521))
Supported services, that is, the services to which the listener forwards client
requests, can be configured in the listener.ora file or this information can be
dynamically registered with the listener. This dynamic registration feature is called
service registration and is used by Oracle9i or Oracle8i instances. The registration is
performed by the PMON process—an instance background process—of each
database instance that has the necessary configuration in the database initialization
parameter file. Dynamic service registration does not require any configuration in
the listener.ora file.
Note: A version 9 listener is required for an Oracle9i database.
Previous versions of the listener are not supported for use with an
Oracle9i database. However, it is possible to use a version 9 listener
with previous versions of the Oracle database.
See Also: "Listener Architecture" on page 4-10
Listener Configuration Overview
Configuring and Administering the Listener 12-3
Service registration offers the following benefits:
n Simplified configuration
Service registration reduces the need for the SID_LIST_listener_name
parameter setting, which specifies information about the databases served by
the listener, in the listener.ora file.
n Connect-time failover
Because the listener always knows the state of the instances, service registration
facilitates automatic failover of the client connect request to a different instance
if one instance is down.
In a static configuration model, a listener would start a dedicated server upon
receiving a client request. The server would later find out that the instance is
not up, causing an "Oracle not available" error message.
n Connection load balancing
Service registration enables the listener to forward client connect requests to the
least loaded instance and dispatcher or dedicated server. Service registration
balances the load across the service handlers and nodes.
Oracle Enterprise Manager tools require static service configuration in the
listener.ora file.
 
 
Shraed Server ile igili tanımları DB admin guiden da ve Net service admin guiden da detaylı bulabilirsin.
Bunları okuman sadece sana hatırlatma yapar.

Thursday, October 27, 2011

DBMS_XPLAN package

:The DBMS_XPLAN package supplies five table functions

DISPLAY - to format and display the contents of a plan table.

DISPLAY_AWR - to format and display the contents of the execution plan of a stored SQL statement in the AWR.

DISPLAY_CURSOR - to format and display the contents of the execution plan of any loaded cursor.

DISPLAY_SQL_PLAN_BASELINE - to display one or more execution plans for the SQL statement identified by SQL handle

DISPLAY_SQLSET - to format and display the contents of the execution plan of statements stored in a SQL tuning set.

----------------- SAMPLES. -------------


Using a View to Display Last Explain Plan

EXPLAIN PLAN FOR
SELECT * FROM emp e, dept d
WHERE e.deptno = d.deptno
AND e.ename='benoit';

Display the plan using the DBMS_XPLAN.DISPLAY table function

SET LINESIZE 130
SET PAGESIZE 0
SELECT * FROM table(DBMS_XPLAN.DISPLAY);



Display the execution plan for the cursor:
SELECT * FROM table(DBMS_XPLAN.DISPLAY_CURSOR(('gwp663cqh5qbf',0));

Display the execution plan of all cursors matching the string 'TOTO':

SELECT t.*
FROM v$sql s, table(DBMS_XPLAN.DISPLAY_CURSOR(s.sql_id, s.child_number)) t WHERE sql_text LIKE '%TOTO%';

------------------------

DISPLAY Function

This table function displays the contents of the plan table.

Syntax

DBMS_XPLAN.DISPLAY(
table_name IN VARCHAR2 DEFAULT 'PLAN_TABLE',
statement_id IN VARCHAR2 DEFAULT NULL,
format IN VARCHAR2 DEFAULT 'TYPICAL',
filter_preds IN VARCHAR2 DEFAULT NULL);

To display the result of the last EXPLAIN PLAN command stored in the plan table:

SELECT * FROM table (DBMS_XPLAN.DISPLAY);
To display from other than the default plan table, "my_plan_table":

SELECT * FROM table (DBMS_XPLAN.DISPLAY('my_plan_table'));
To display the minimum plan information:

SELECT * FROM table (DBMS_XPLAN.DISPLAY('plan_table', null, 'basic'));


------------------------------------------

DISPLAY_AWR Function

This table function displays the contents of an execution plan stored in the AWR.

Syntax

DBMS_XPLAN.DISPLAY_AWR(
sql_id IN VARCHAR2,
plan_hash_value IN NUMBER DEFAULT NULL,
db_id IN NUMBER DEFAULT NULL,
format IN VARCHAR2 DEFAULT TYPICAL);

To display the different execution plans associated with the SQL ID 'atfwcg8anrykp':

SELECT * FROM table(DBMS_XPLAN.DISPLAY_AWR('atfwcg8anrykp'));

-----------------------------------------------------------------------------

DISPLAY_CURSOR Function

This table function displays the explain plan of any cursor loaded in the cursor cache. In addition to the explain plan, various plan statistics (such as. I/O, memory and timing) can be reported (based on the V$SQL_PLAN_STATISTICS_ALL VIEWS).

Syntax

DBMS_XPLAN.DISPLAY_CURSOR(
sql_id IN VARCHAR2 DEFAULT NULL,
child_number IN NUMBER DEFAULT NULL,
format IN VARCHAR2 DEFAULT 'TYPICAL');


child_number
Child number of the cursor to display. If not supplied, the execution plan of all cursors matching the supplied sql_id parameter are displayed. The child_number can be specified only if sql_id is specified.



To display the execution plan of the last SQL statement executed by the current session:

SELECT * FROM table (
DBMS_XPLAN.DISPLAY_CURSOR);
To display the execution plan of all children associated with the SQL ID 'atfwcg8anrykp':

SELECT * FROM table (
DBMS_XPLAN.DISPLAY_CURSOR('atfwcg8anrykp'));
with children 1

SELECT * FROM table (
DBMS_XPLAN.DISPLAY_CURSOR('atfwcg8anrykp',1));

--------------------------------------------------

DISPLAY_SQL_PLAN_BASELINE Function

This table function displays one or more execution plans for the specified SQL handle of a SQL plan baseline.

Syntax

DBMS_XPLAN.DISPLAY_SQL_PLAN_BASELINE (
sql_handle IN VARCHAR2 := NULL,
plan_name IN VARCHAR2 := NULL,
format IN VARCHAR2 := 'TYPICAL')
RETURN dbms_xplan_type_table;

plan_name
Plan name. It identifies a specific plan. Default NULL means all plans associated with identified SQL statement are explained and displayed.

Display all plans of a SQL statement identified by the SQL handle 'SYS_SQL_b1d49f6074ab95af' using TYPICAL format

SET LINESIZE 150
SET PAGESIZE 2000
SELECT t.*
FROM TABLE(DBMS_XPLAN.DISPLAY_SQL_PLAN_BASELINE(
'SYS_SQL_b1d49f6074ab95af')) t;

-----------------------------------------------------

DISPLAY_SQLSET Function


DBMS_XPLAN.DISPLAY_SQLSET(
sqlset_name IN VARCHAR2,
sql_id IN VARCHAR2,
plan_hash_value IN NUMBER := NULL,
format IN VARCHAR2 := 'TYPICAL',
sqlset_owner IN VARCHAR2 := NULL)
RETURN DBMS_XPLAN_TYPE_TABLE PIPELINED;

This table function displays the execution plan of a given statement stored in a SQL tuning set.

plan_hash_value
Optional parameter. Identifies a specific stored execution plan for a SQL statement. If suppressed, all stored execution plans are shown.

To display all execution plans of the SQL ID 'atfwcg8anrykp' stored in the SQL tuning set:

SELECT * FROM table (
DBMS_XPLAN.DISPLAY_SQLSET(
'OLTP_optimization_0405','gwp663cqh5qbf'));

To display the execution plan for the SQL statement associated with SQL ID 'gwp663cqh5qbf' and PLAN HASH 3693697075 in the SQL Tuning Set called 'OLTP_optimization_0405":

SELECT * FROM table (
DBMS_XPLAN.DISPLAY_SQLSET(
'OLTP_optimization_0405','gwp663cqh5qbf', 3693697075));

Thursday, October 20, 2011

11g Upgrade check list

Upgrade-Öncesi
Binary kurulum için gerekli diski bul
Binary leri ve PSU yükle
Outline Topla
SQLArea Topla
SQLPLan bilgileri topla
SQL tuning Set yarat buffer Cache'de yüklemelerini yap.
Upgrade ve/veya downgrade testi yap
XDB yüklenmiş olmalı
utlu112i.sql çalıştır sonuçlarına bak
connect role privs için script hazırla
"select TZ_VERSION from registry$database;
"
DB linklerin backuplarını al
10g Tablo istatistiklerini bir tabloya export et.
EXEC DBMS_STATS.GATHER_DICTIONARY_STATS;
"ACL kullanan userlar

SELECT DISTINCT owner
FROM DBA_DEPENDENCIES
WHERE referenced_name
IN ('UTL_TCP','UTL_SMTP','UTL_MAIL','UTL_HTTP','UTL_INADDR')
AND owner NOT IN ('SYS','PUBLIC','ORDPLUGINS');


SELECT DISTINCT owner
FROM all_tab_columns
WHERE data_type
IN ('ORDIMAGE', 'ORDAUDIO', 'ORDVIDEO', 'ORDDOC','ORDSOURCE', 'ORDDICOM')
AND (data_type_owner = 'ORDSYS' OR data_type_owner = owner)
AND (owner != 'PM');
"
"The DIAGNOSTIC_DEST initialization parameter replaces the
USER_DUMP_DEST, BACKGROUND_DUMP_DEST."
Backup Al
DROP TABLE SYS.PLAN_TABLE;
TRUNCATE TABLE SYS.AUD$
SELECT * FROM v$recover_file;
Disk sistem type 'ına göre ufs veya vfs durumuna göre vfs ise ODM kullanılacaktır filesystemio_options='SETALL' parametresini belirle
Upgrade
copy password file & tnsnames.ora & listener.ora from 9i to 10g
clear dba_2pc_pending
invalid object list table
İş İstek'den invalid compile için snap al.
event='10298 trace name context forever, level 32','10946 trace name context forever,level 262144'
"init.oraya eklemeler yap ._first_spare_parameter=1
*._gby_hash_aggregation_enabled=FALSE
*._ksmg_granule_size=67108864
*._library_cache_advice=FALSE
*._log_archive_callout='LOCAL_FIRST=TRUE'
*._newsort_enabled=FALSE
*._optimizer_cost_based_transformation='OFF'
*._optimizer_rownum_pred_based_fkr=FALSE
*._rollback_segment_count=10000
*._undo_autotune=FALSE JAVA_JIT_ENABLED= FALSE "

STARTUP UPGRADE;
@catupgrd.sql
startup
@utlu112s.sql
@catuppst.sql
@utlrp.sql
Upgrade Sonrası
"Modify the listener.ora file
For the upgraded instance(s) modify the ORACLE_HOME parameter to
point to the new ORACLE_HOME"
"UPDATE Time zone
Updating the RDBMS DST version in 11gR2 (11.2.0.1 and up) using DBMS_DST (Doc ID 977512.1)
"
install XDB component eğer yoksa
Configure (ACL) Fine-Grained Access to External Network Services
invalid objelere bak
İş istekden invalid snapshot al ve karşılaştır
alert logu control etmeye başka
Database console hazırla
vfs varsa ODM kurulumu
Sistem performasını takip et
Standbylar varsa onların işini yap.
exec dbms_scheduler.disable('GATHER_STATS_JOB')
10g Database'in init.ora parametre dosyasını mv et
Backup al

"ACL yaratılır begin
dbms_network_acl_admin.create_acl (
acl => 'utlpkg.xml',
description => 'Normal Access',
principal => 'CONNECT',
is_grant => TRUE,
privilege => 'connect',
start_date => null,
end_date => null
);
commit;
end;
/"
"ACL nin tüm IP ve Portlara erişimi verilir
begin
dbms_network_acl_admin.assign_acl (
acl => 'utlpkg.xml',
host => '*');
commit;
end;
/
"
"
Her bir user için

begin
dbms_network_acl_admin.add_privilege (
acl => 'utlpkg.xml',
principal => 'CEURO',
is_grant => TRUE,
privilege => 'connect',
start_date => null,
end_date => null);
commit;
end;
/

begin
dbms_network_acl_admin.add_privilege (
acl => 'utlpkg.xml',
principal => 'CEURO',
is_grant => TRUE,
privilege => 'resolve',
start_date => null,
end_date => null);
commit;
end;
/"

Tuesday, October 11, 2011

opt_param usage

After 10g you can use opt_param with only below parameter

- OPTIMIZER_DYNAMIC_SAMPLING,
- OPTIMIZER_INDEX_CACHING,
- OPTIMIZER_INDEX_COST_ADJ,
- OPTIMIZER_SECURE_VIEW_MERGING
- STAR_TRANSFORMATION_ENABLED

like this

SELECT /*+ OPT_PARAM('star_transformation_enabled' 'true') */ * FROM ... ;

opt_param

At 10g without alter session you can change optimizer parameter with opt_param

select /*+ opt_param('optimizer_mode','first_rows_10') */

select /*+ opt_param('_optimizer_cost_model','io') */

select /*+ opt_param('optimizer_index_cost_adj',20) */

select /*+ opt_param('optimizer_index_caching',20) */



The OPT_PARAM hint lets you set an initialization parameter for the duration of the current query only. This hint is valid only for the following parameters: OPTIMIZER_DYNAMIC_SAMPLING, OPTIMIZER_INDEX_CACHING, OPTIMIZER_INDEX_COST_ADJ, OPTIMIZER_SECURE_VIEW_MERGING, and STAR_TRANSFORMATION_ENABLED. For example, the following hint sets the parameter STAR_TRANSFORMATION_ENABLED to TRUE for the statement to which it is added:

SELECT /*+ OPT_PARAM('star_transformation_enabled' 'true') */ * FROM ... ;
Parameter values that are strings are enclosed in single quotation marks. Numeric parameter values are specified without quotation marks

Monday, October 10, 2011

Using Stored Outlines for Upgrade to 10g

First give grant to create stored outlines for users

CONN sys/password AS SYSDBA


-- Give grant to all app users

SELECT 'GRANT CREATE ANY OUTLINE TO ' || username || ';'
FROM dba_users
WHERE username NOT IN ('SYSTEM', 'SYS', 'OUTLN', 'DBSNMP', 'MASTER')
AND ( username not LIKE 'ZU%' )
AND ( username not LIKE 'U0%' );

GRANT CREATE ANY OUTLINE TO APPUSER;
GRANT EXECUTE_CATALOG_ROLE TO APPUSER;


-- Start to Collect outlines

alter system set CREATE_STORED_OUTLINES=OLDPLAN;

-- Check Outlines

-- Check Database performance

select name, sql_text, category from dba_outlines;

select count(*) from dba_outlines where category='OLDPLAN'

-- Stop Collecting Outlines

alter system set CREATE_STORED_OUTLINES=false;

--------------------------------------------------------------------------------

-- After collecting outlines upgrade the database
-- set USE_STORED_OUTLINES to correct execution plan


Alter system set USE_STORED_OUTLINES=FIXPLAN;

-- And create temporary tables for queries

Create table match_outlines (
owner varchar2(30),
name varchar2(30),
sql_text clob);

Insert into match_outlines
Select owner,name, to_lob(sql_text)
From dba_outlines ;

-- if there is any problem find the Query and change the execution plan with outlines.

-- Get the stored outline name

select name,sql_text from master.match_outlines where upper(sql_text) like '%Part of the SQL%';

alter outline OUTLINE_NAME change category to FIXPLAN;

-- Or fix the plan by Hash_value if you know it.

BEGIN
DBMS_OUTLN.create_outline(
hash_value => 3909283366,
child_number => 0,
category => 'FIXPLAN');
END;
/




----------- SOME INFORMATION ABOUT OUTLINES ------------------

-- views --
select * from dba_outlines;
select * from dba_outline_hints;
select * from OL$HINTS;

-- packages that you can use

DBMS_OUTLINE.*
DBMS_OUTLINE_EDIT.*


-- Create an outline for a specific SQL statement by CREATE OUTLINE command
-- white spaces are not important
-- But the name of the bind wariables are important
- Capital or small letters are not important


CREATE OUTLINE my_outline FOR CATEGORY oldplan
ON SELECT col1,col2,col4 FROM tablename WHERE col3='BB' and col4= :b1 ;


reading about the subject

http://www.oracle-base.com/articles/misc/Outlines.php