Showing posts with label Oracle Database. Show all posts
Showing posts with label Oracle Database. Show all posts

Friday, May 8, 2015

Quick Oracle Database Tunning Tips without OEM(Enterprice Manager)


http://docs.oracle.com/cd/B28359_01/server.111/b28274/sql_tune.htm
http://www.pythian.com/news/584/wouldnt-automatic-sql-plan-management-be-the-11g-killer-app/

create a tunning task
---------------------
variable stmt_task VARCHAR2(64);
variable sts_task  VARCHAR2(64);
variable spa_tune_task VARCHAR2(64);
EXEC :stmt_task := DBMS_SQLTUNE.CREATE_TUNING_TASK( sql_text => 'SELECT S.EMPLID ,S.EMPL_RCD , PDE.EFFDT ,INS.PER_ORG ,INS.ORIG_HIRE_DT ,PDE.SEX ,PRS.BIRTHDATE ,PRS.BIRTHPLACE ,PRS.BIRTHCOUNTRY ,PRS.BIRTHSTATE ,PRS.DT_OF_DEATH ,PDE.HIGHEST_EDUC_LVL ,PDE.FT_STUDENT ,PDE.LANG_CD ,PDE.ALTER_EMPLID ,PDE.MAR_STATUS ,ASG.HOME_HOST_CLASS ,ASG.CMPNY_SENIORITY_DT ,ASG.SERVICE_DT ,ASG.PROF_EXPERIENCE_DT ,ASG.LAST_VERIFICATN_DT ,ASG.OWN_5PERCENT_CO ,ASG.PROBATION_DT ,ASG.ORG_INSTANCE_ERN ,ASG.SENIORITY_PAY_DT FROM PS_PERSON PRS ,PS_PER_ORG_ASGN ASG ,PS_PER_ORG_INST INS ,PS_PERS_DATA_EFFDT PDE ,PS_GP_PYE_STAT_WRK S WHERE S.RUN_CNTL_ID ='ABS_JAN2012_IND' AND S.OPRID = 12345 AND S.EMPLID BETWEEN 1000 AND 19999 AND S.EMPLID = PRS.EMPLID AND S.EMPLID = PDE.EMPLID AND S.FRST_JOB_SEG_IND = 'Y' AND S.EMPLID = ASG.EMPLID AND S.EMPL_RCD = ASG.EMPL_RCD AND ASG.EMPLID = INS.EMPLID AND ASG.ORG_INSTANCE_ERN = INS.ORG_INSTANCE_ERN ORDER BY S.EMPLID, S.EMPL_RCD, PDE.EFFDT DESC ');
---or-----
EXEC :stmt_task := DBMS_SQLTUNE.CREATE_TUNING_TASK(task_name=>'hello1223',sql_id => '4qh14ksgd4dd8',scope='COMPREHENSIVE');
---or-----
DECLARE
sql_text clob;
sqlprofile_name varchar2(30);
task_name varchar2(100);
BEGIN
sql_text :=
task_name:=dbms_sqltune.create_tuning_task(sql_text,task_name=>'TASKREQ01',scope=>'COMPREHENSIVE');
END;
/
execute a tunning task
----------------------
EXEC DBMS_SQLTUNE.EXECUTE_TUNING_TASK(:stmt_task);
display a tunning task
----------------------
SET LONG 1000
SET LONGCHUNKSIZE 1000
SET LINESIZE 100
SELECT DBMS_SQLTUNE.report_tuning_task('TASK_4188') AS recommendations FROM dual
SELECT DBMS_SQLTUNE.report_tuning_task(:stmt_task) AS recommendations FROM dual
accept a recommendation sql profile
execute dbms_sqltune.accept_sql_profile(task_name => 'TASK_4256',task_owner => 'MD86506', replace => TRUE);
disable sql profile
EXEC DBMS_SQLTUNE.ALTER_SQL_PROFILE('SYS_SQLPROF_013c237dab800000','STATUS','DISABLED');

view task information
--------------------
SELECT task_name, status FROM dba_advisor_log WHERE owner = 'MD86506';

primary_gl_tb 

SELECT DBMS_SQLTUNE.report_tuning_task('primary_gl_tb') AS recommendations FROM dual ;
execute dbms_sqltune.accept_sql_profile(task_name => 'primary_gl_tb',task_owner => 'MD86506', replace => TRUE);

USER_ADVISOR_TASKS <-- table which have task information
•DBA_ADVISOR_TASKS
•DBA_ADVISOR_FINDINGS
•DBA_ADVISOR_RECOMMENDATIONS
•DBA_ADVISOR_RATIONALE
•DBA_SQLTUNE_STATISTICS
•DBA_SQLTUNE_BINDS
•DBA_SQLTUNE_PLANS
•DBA_SQLSET
•DBA_SQLSET_BINDS
•DBA_SQLSET_STATEMENTS
•DBA_SQLSET_REFERENCES
•DBA_SQL_PROFILES
•V$SQL
•V$SQLAREA
•V$ACTIVE_SESSION_HISTORY
enable/dislabe/delete sql profile
=================================

SELECT *
  FROM DBA_SQL_PROFILES prof,
       DBMSHSXP_SQL_PROFILE_ATTR attr
  WHERE prof.NAME=attr.PROFILE_NAME
  ORDER BY prof.name,
           attr.attr_number;
Enable/Disable
Locate the name of the SQL Profile you would like to disable and plug it in to the following statement:
EXEC DBMS_SQLTUNE.ALTER_SQL_PROFILE('PROFILE_NAME','STATUS','DISABLED');
Dropping a SQL Profile
EXEC DBMS_SQLTUNE.DROP_SQL_PROFILE('PROFILE_NAME');

 
SQL for Tunning task

Ref:
http://docs.oracle.com/cd/E11882_01/server.112/e25523/parallel006.htm
http://docs.oracle.com/cd/E11882_01/server.112/e16638/hintsref.htm
http://docs.oracle.com/cd/E14072_01/server.112/e10837/parallel.htm
http://docs.oracle.com/cd/E11882_01/server.112/e25523/parallel002.htm
Query to check parallel executions on instance:
----------------------------------------------
SELECT QCSID, SID, INST_ID "Inst", SERVER_GROUP "Group", SERVER_SET "Set",
  DEGREE "Degree", REQ_DEGREE "Req Degree"
FROM GV$PX_SESSION ORDER BY QCSID, QCINST_ID, SERVER_GROUP, SERVER_SET;

SELECT NAME, VALUE FROM GV$SYSSTAT
WHERE UPPER (NAME) LIKE '%PARALLEL OPERATIONS%'
OR UPPER (NAME) LIKE '%PARALLELIZED%' OR UPPER (NAME) LIKE '%PX%';

SELECT px.SID "SID", p.PID, p.SPID "SPID", px.INST_ID "Inst",
       px.SERVER_GROUP "Group", px.SERVER_SET "Set",
       px.DEGREE "Degree", px.REQ_DEGREE "Req Degree", w.event "Wait Event"
FROM GV$SESSION s, GV$PX_SESSION px, GV$PROCESS p, GV$SESSION_WAIT w
WHERE s.sid (+) = px.sid AND s.inst_id (+) = px.inst_id AND
      s.sid = w.sid (+) AND s.inst_id = w.inst_id (+) AND
      s.paddr = p.addr (+) AND s.inst_id = p.inst_id (+)
ORDER BY DECODE(px.QCINST_ID,  NULL, px.INST_ID,  px.QCINST_ID), px.QCSID,
DECODE(px.SERVER_GROUP, NULL, 0, px.SERVER_GROUP), px.SERVER_SET, px.INST_ID;

SELECT * from v$pq_sysstat;
SELECT * FROM v$px_process;
SELECT * FROM v$px_sesstat;
SELECT * FROM v$px_process_sysstat;


Examples
========
ALTER TABLE table_name PARALLEL (DEGREE 8);
SELECT /*+PARALLEL(table_alias, degree, nodes)*/ *
  FROM table_name ...
OR
SELECT /*+PARALLEL */ * FROM table_name/View name ...


 

CONSUMING WEB SERVICE FROM ORACLE DATABASE 11G USING UTL_HTTP PACKAGE


Contents







 

 

1. Create access control list and assign host


1.1 Create access control list


 

BEGIN

   DBMS_NETWORK_ACL_ADMIN.CREATE_ACL (

    ACL          => 'STREAM_TEST.XML',

    DESCRIPTION  => 'PERMISSIONS TO ACCESS ESUPPORT WEBSITE',

    PRINCIPAL    => 'MD86506',

    IS_GRANT     => TRUE,

    PRIVILEGE    => 'CONNECT');

   COMMIT;

END;

/

 

1.2 Create Role and assign to access control list


 

BEGIN

   DBMS_NETWORK_ACL_ADMIN.ADD_PRIVILEGE (

    ACL          => 'STREAM_TEST.XML',               

    PRINCIPAL    => 'DBA',

    IS_GRANT     => TRUE,

    PRIVILEGE    => 'CONNECT',

    POSITION     => NULL);

   COMMIT;

END;

/

 

1.3 Add hosts


 

BEGIN

   DBMS_NETWORK_ACL_ADMIN.ASSIGN_ACL (

    ACL          => 'STREAM_TEST.XML',               

    HOST         => '*.satyam.com);

   COMMIT;

END;

/

 

 

BEGIN

   DBMS_NETWORK_ACL_ADMIN.ASSIGN_ACL (

    ACL          => 'STREAM_TEST.XML',               

    HOST         => '172.16.187.25');

   COMMIT;

END;

/

 

1.4 Test Access


 

CREATE OR REPLACE PROCEDURE GETTITLE (PURL VARCHAR2)

IS

  VRESULT CLOB;

BEGIN

  VRESULT := REPLACE(UTL_HTTP.REQUEST(PURL),CHR(10),' ');

  VRESULT := REGEXP_REPLACE(VRESULT,'.*<TITLE> ?(.+) ?</TITLE>.*','\1',1,1,'I');

  DBMS_OUTPUT.PUT_LINE (VRESULT);

END;

/

 

SET SERVEROUTPUT ON

EXECUTE GETTITLE ('HTTP://172.16.187.119:8050');

 

 

 

 

 

 

2. Write procedure to call web service


 

2.1 UTL_HTTP


1.       UTL_HTTP.BEGIN_REQUEST : UTL_HTTP.BEGIN_REQUEST('http://172.16.187.25:8000/sap/xi/adapter_plain?bs=FILE'||'&'||'namespace=http%3A//file2file.com'||'&'||'interface=FILEHTML'||'&'||'qos=EO','POST',NULL,NULL);

Opens http request to the specified URL

2.       UTL_HTTP.SET_HEADER:

UTL_HTTP.SET_HEADER (req,'Content-Type','text/xml');

UTL_HTTP.SET_HEADER (req,'Content-Length','200');

 

Set communication parameters for the http request

 

3.       UTL_HTTP.WRITE_TEXT

 

UTL_HTTP.WRITE_TEXT (req,'<?xml version="1.0" encoding="UTF-8"?><ns0:FILEHTML xmlns:ns0="http://file2file.com"><row><EMPLID>865072</EMPLID><EMPLANAME>fromDB4</EMPLANAME></row></ns0:FILEHTML>');

Write data into http stream

4.       UTL_HTTP.RESPONSE:

-resp := UTL_HTTP.GET_RESPONSE (req);

Capture response of the http stream

5.       UTL_HTTP.END_RESPONSE:

Close request and response http connections

6.       UTL_HTTP.END_REQUEST:

Close request http connections

2.2 UTL_DBWS

Monday, January 7, 2013

problem with uninstalling oracle on windows, this works


problem with uninstalling oracle on windows, below method works.....

    1.Uninstall all Oracle components using the Oracle Universal Installer (OUI).
    2.Run regedit.exe and delete the HKEY_LOCAL_MACHINE/SOFTWARE/ORACLE key. This contains registry entires for all Oracle products.
    3.Delete any references to Oracle services left behind in the following part of the registry (HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services/Ora*). It should be pretty obvious which ones relate to Oracle.
    4.Reboot your machine.
    5.Delete the "C:\Oracle" directory, or whatever directory is your ORACLE_BASE.
    6.Delete the "C:\Program Files\Oracle" directory.
    7.Empty the contents of your "C:\temp" directory.
    8.Empty your recycle bin.

Saturday, June 23, 2012

Understanding AWR (Automatic Workload Repository)


Understanding AWR


Viewing AWR Reports awrrpt.sql and awrrpti.sql displays statistics ,  awrinfo.sql displays general information.

Notes:

565812.1
274496.1
396940.1 -- Troubleshooting and Diagnosing ORA-4031 Erro

The following list includes the meanings of particular hit ratios:

Buffer Hit Ratio: Measures how many times a required block was found in memory rather than having to execute an expensive read operation on disk to get the block.

Buffer Nowait %: Shows the percentage of times when data buffers were accessed directly without any wait time.

Library Hit %: Shows the percentage of times when SQL statements and PL/SQL packages were found in the shared pool.

Execute to Parse %: Shows how often parsed SQL statements are reused without reparsing.

Parse CPU to Parse Elapsd %: Gives the ratio of CPU time spent to parse SQL statements.

Redo NoWait %: Shows whether the redo log buffer has sufficient size.

In-memory Sort %: Shows the percentage of times when sorts are performed in memory instead of using temporary tablespaces.

Soft Parse %: Shows how often sessions issued a SQL statement that is already in the shared pool and how it can use an existing version of that statement.

Latch Hit %: Shows how often latches were acquired without having to wait.

% Non-Parse CPU: Shows the percentage of how much CPU resources were spent on the actual SQL execution.

In the above list of statistics, special attention should be paid to parse-related statistics. The Instance Efficiency Percentage report provided previously shows that about 95 percent of the parses are soft as indicated by the Soft Parse %. This is good enough, indicating that the SQL statements are actively reused by Oracle.

The next interesting item to review is the Parse CPU to Parse Elapsd % statistic. In this case, it is about three percent, which is very low. This fact reveals that Oracle waits for some resources during parsing of SQL statements. This should be investigated further to find the cause.

In this case, % Non-Parse CPU statistic is about 97 percent, which is quite high.  This indicates Oracle utilizes the CPU mostly for statement execution but not for parsing.

As a rule of thumb, one should always minimize the number of hard parses in your production database. This reduction yields the benefit of minimizing CPU overhead spent performing costly parse work.

This following sample report section shows shared pool related statistics:

Shared Pool Statistics        Begin    End

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

             Memory Usage %:   92.70   92.49

    % SQL with executions>1:   86.73   84.20

  % Memory for SQL w/exec>1:   84.12   71.86

In this example, the Memory Usage % statistic shows that almost all, approximately 92 percent, of the shared pool memory is consumed. This could indicate that the system experiences some overhead while aging out old shared memory structures like cursors, PL/SQL programs, and so on. This places additional overhead on the CPU to perform reparsing aging-out. The size of the shared pool should be increased appropriately to eliminate such overhead. In general, this statistic should be near 70 percent after the database has been running a long time. If it is quite low, memory is being wasted.

The % SQL with executions>1 statistic indicates how many SQL statements are executed more than one time. This measures how well production applications are tuned and how well they make use of bind variables.

Regards
Manoj

Oracle Database Granules


The DB_CACHE_SIZE parameter, rather than DB_BLOCK_BUFFERS, is used to define the size of the buffer cache for the standard block size. This can be set to any size, but it will be rounded to the nearest whole granule. If the total SGA is less then 128M the granule size is 4M, greater than 128M and it becomes 16M. The DB_CACHE_SIZE must be at least 1 granule in size and defaults to 48M.

Regards
Manoj

Diagnose performance problems, using the wait interface in Oracle 10g.


Source: http://www.oracle.com/technology/oramag/oracle/04-jul/o44tech_perf.html

=======================
Perform Without Waiting
By Arup Nanda
========================

Diagnose performance problems, using the wait interface in Oracle 10g.
----------------------------------------------------------------------


John, the DBA at Acme Bank, is on the phone with an irate user, Bill, who complains that his database session is hanging, a complaint not unfamiliar to most DBAs. What can John do to address Bill's complaint?

Acme Bank's database is Oracle Database 10g, so John has many options. Automatic Database Diagnostic Manager (ADDM), new in Oracle Database 10g, can tell John about the current overall status and performance of the database, so John starts with ADDM to determine whether what Bill's session is experiencing is the result of a databasewide issue. The ADDM report identifies no databasewide issues that could have this impact on Bill's session, so John moves on to the next option.

One way to diagnose session-level events such as Bill's is to determine whether the session is waiting for anything, such as the reading of a block of a file, a lock on a table row, or a latch. Oracle has provided mechanisms to display the waits happening inside the database since Oracle7, and during the last several years, the model has been steadily perfected, with more and more diagnostic information added to it. In Oracle Database 10g, which makes significantly improved wait event information available, diagnosing a session slowdown has become even easier. This article shows you how to use the wait events in Oracle Database 10g to identify bottlenecks.

Session Waits

How can John the DBA determine what's causing Bill's session to hang? Actually, the session is not hanging; it's waiting for an event to happen, and that's exactly what John checks for.

To continue his investigation, John could use Oracle Enterprise Manager or he could directly access V$ views from the command line. John has a set of scripts he uses to diagnose these types of problems, so he uses the command line.

============================================================================================================
John queries the V$SESSION view to see what Bill's session is waiting for. (Note that John filters out all idle events.)

select sid, username, event, blocking_session,
   seconds_in_wait, wait_time
from v$session where state in ('WAITING')
and wait_class != 'Idle';

The output follows, in vertical format.

SID              : 270
USERNAME         : BILL
EVENT            : enq: TX - row lock
                 contention
BLOCKING_SESSION : 254
SECONDS_IN_WAIT  : 83
WAIT_TIME        : 0

============================================================================================================
Looking at this information, John immediately concludes that Bill's session with SID 270 is waiting for a lock on a table and that that lock is held by session 254 (BLOCKING_SESSION).

=====================================================================================================================
But John wants to know which SQL statement is causing this lock. He can find out easily, by issuing the following query joining the V$SESSION and V$SQL views:

select sid, sql_text
from v$session s, v$sql q
where sid in (254,270)
and (
   q.sql_id = s.sql_id or
   q.sql_id = s.prev_sql_id);

=====================================================================================================================
Listing 1 shows the result of the query. And there (in Listing 1) John sees it—both sessions are trying to update the same row. Unless session 254 commits or rolls back, session 270 will continue to wait for the lock. He explains this to Bill, who, considerably less irate now, decides that something in the application has gone awry and asks John to kill session 254 and release the locks.

Wait Classes

After John kills the blocking session, Bill's session continues but is very slow. John decides to check for other problems in the session. Again, he checks for any other wait events, but this time he specifically checks Bill's session.

=====================================================================================================================
In Oracle Database 10g, wait events are divided into various wait classes, based on their type. The grouping of events lets you focus on specific classes and exclude nonessential ones such as idle events. John issues the following against the V$SESSION_WAIT_CLASS view:

select wait_class_id, wait_class,
   total_waits, time_waited
from v$session_wait_class
where sid = 270;
=====================================================================================================================
The output, shown in Listing 2, shows the wait classes and how many times the session has waited for events in each class. It tells John that application-related waits such as those due to row locks have occurred 17,760 times, for a total of 281,654 centiseconds (cs)—hundredths of a second—since the instance started. John thinks that this TIME_WAITED value is high for this session. He decides to explore the cause of these waits in the application wait class. The times for individual waits are available in the V$SYSTEM_EVENT view. He issues the following query to identify individual waits in the application wait class (class id 4217450380):
=====================================================================================================================
select event, total_waits, time_waited
from v$system_event e, v$event_name n
where n.event_id = e.event_id
and wait_class_id = 4217450380;
=====================================================================================================================
Listing 3 shows the output of this query. It shows that lock contentions (indicated by the event enq: TX - row lock contention) constitute the major part of the waiting time in the application wait class. This concerns John. Is it possible that a badly written application made its way through to the production database, causing these lock contention problems?

Being the experienced DBA that he is, however, John does not immediately draw that conclusion. The data in Listing 3 merely indicates that the users have experienced lock-contention-related waits a total of 2,275 times, for 280,856 cs. It is possible that mostly 1- or 2-cs waits and only one large wait account for the total wait time, and in that case, the application isn't faulty. A single large wait may be some freak occurrence skewing the data and not representative of the workload on the system. How can John determine whether a single wait is skewing the data?
=====================================================================================================================
Oracle 10g provides a new view, V$EVENT_HISTOGRAM, that shows the wait time periods and how often sessions have waited for a specific time period. He issues the following against V$EVENT_HISTOGRAM:

select wait_time_milli bucket, wait_count
 from v$event_histogram
 where event =
    'enq: TX - row lock contention';

The output looks like this:

    BUCKET     WAIT_COUNT
-----------    ----------
         1          252
         2             0
         4             0
         8             0
        16             1
        32             0
        64            4
       128            52
       256          706
       512           392
      1024           18
      2048            7
      4096           843
=====================================================================================================================
The V$EVENT_HISTOGRAM view shows the buckets of wait times and how many times the sessions waited for a particular event—in this case, a row lock contention—for that duration. For example, sessions waited 252 times for less than 1 millisecond (ms), once less than 16 ms but more than 1 ms, and so on. The sum of the values of the WAIT_COUNT column is 2,275, the same as the value shown in the event enq: TX - row lock contention, shown in Listing 3. The V$EVENT_HISTOGRAM view shows that the most waits occurred in the ranges of 256 ms, 512 ms, and 4,096 ms, which is sufficient evidence that the applications are experiencing locking issues and that this locking is the cause of the slowness in Bill's session. Had the view showed numerous waits in the 1-ms range, John wouldn't have been as concerned, because the waits would have seemed normal.

Time Models

Just after John explains his preliminary findings to Bill, Lora walks in with a similar complaint: Her session SID 355 is very slow. Once again, John looks for the events the session is waiting for, by issuing the following query against the V$SESSION_WAIT view:
=====================================================================================================================
select event, seconds_in_wait,
   wait_time
from v$session_wait
where sid = 355;
=====================================================================================================================
The output, shown in Listing 4, shows a variety of wait events in Lora's session, including latch contention, which may be indicative of an application design problem. But before he sends Lora off with a prescription for an application change, John must support his theory that bad application design is the cause of the poor performance in Lora's session. To test this theory, he decides to determine whether the resource utilization of Lora's session is extraordinarily high and whether it slows not only itself but other sessions too.

In the Time Model interface of Oracle Database 10g, John can easily view details of time spent by a session in various activities. He issues the following against the V$SESS_TIME_MODEL view:
=====================================================================================================================
select stat_name, value
from v$sess_time_model
where sid = 355;
 =====================================================================================================================

ADDM Advises

Oracle Diagnostics Pack 10g includes the Automatic Database Diagnostic Monitor (ADDM)—a self-diagnostic engine built right into the Oracle Database 10g kernel. This is a revolutionary performance self-diagnostic solution that enables Oracle Database 10g to automatically diagnose its performance problems.

ADDM periodically examines the state of the database, automatically identifies potential database performance bottlenecks, and recommends corrective actions. Each ADDM finding has an associated impact and benefit measure to enable prioritized handling of the most critical issues. In addition to reporting potential performance issues, ADDM also documents the nonproblem areas of the system.
The output, shown in Listing 5, displays the time (in microseconds) spent by the session in various places. From this output, John sees that the session spent 503,996,336 microseconds parsing (parse time elapsed), out of a total of 878,088,366 microseconds on all SQL execution (sql execute elapsed time), or 57 percent of the SQL execution time, which indicates that a cause of this slowness is high parsing. John gives Lora this information, and she follows up with the application design team.

OS Statistics

While going over users' performance problems, John also wants to rule out the possibility of the host system's being a bottleneck. Before Oracle 10g, he could use operating system (OS) utilities such as sar and vmstat and extrapolate the metrics to determine contention. In Oracle 10g, the metrics at the OS level are collected automatically in the database. To see potential host contention, John issues the following query against the V$OSSTAT view:

select * from v$osstat;

The output in Listing 6 shows the various elements of the OS-level metrics collected. All time elements are in cs. From the results in Listing 6, John sees that the single CPU of the system has been idle for 51,025,805 cs (IDLE_TICKS) and busy for 2,389,857 cs (BUSY_TICKS), indicating a CPU that is about 4 percent busy. From this he concludes that the CPU is not a bottleneck on this host. Note that if the host system had more than one CPU, the columns whose headings had the prefix AVG_, such as AVG_IDLE_TICKS, would show the average of these metrics over all the CPUs.

Active Session History

So far the users have consulted John exactly when each problem occurred, enabling him to peek into the performance views in real time. This good fortune doesn't last long—Janice comes to John complaining about a recent performance problem. When John queries the V$SESSION view, the session is idle, with no events being waited for. How can John check which events Janice's session was waiting for when the problem occurred?

Oracle 10g collects the information on active sessions in a memory buffer every second. This buffer, called Active Session History (ASH), which can be viewed in the V$ACTIVE_SESSION_HISTORY dynamic performance view, holds data for about 30 minutes before being overwritten with new data in a circular fashion. John gets the SID and SERIAL# of Janice's session and issues this query against the V$ACTIVE_SESSION_HISTORY view to find out the wait events for which this session waited in the past.
=====================================================================================================================
select sample_time, event, wait_time
from v$active_session_history
where session_id = 271
and session_serial# = 5;
=====================================================================================================================
Next Steps

READ more about wait events
Oracle Database Reference Guide

Oracle Database Performance Tuning Guide

about AWR

about ADDM
Oracle Database Performance Tuning Guide
The output, excerpted in Listing 7, shows several important pieces of information. First it shows SAMPLE_TIME—the time stamp showing when the statistics were collected—which lets John tie the occurrence of the performance problems to the wait events. Using the data in the V$ACTIVE_SESSION_HISTORY view, John sees that at around 3:17 p.m., the session waited several times for the log buffer space event, indicating that there was some problem with redo log buffers. To further aid the diagnosis, John identifies the exact SQL statement executed by the session at that time, using the following query of the V$SQL view:
=====================================================================================================================
select sql_text, application_wait_time
from v$sql
where sql_id in (
  select sql_id
  from v$active_session_history
  where sample_time =
   '22-FEB-04 03.17.31.188 PM'
  and session_id = 271
  and session_serial# = 5
);
=====================================================================================================================
The output is shown in Listing 8.

The column APPLICATION_WAIT_TIME shows how long the sessions executing that SQL waited for the application wait class. In addition to the SQL_ID, the V$ACTIVE_SESSION_HISTORY view also lets John see specific rows being waited for (in case of lock contentions), client identifiers, and much more.

What if a user comes to John a little late, after the data is overwritten in this view? When purged from this dynamic performance view, the data is flushed to the Active Workload Repository (AWR), a disk-based repository. The purged ASH data can be seen in the DBA_HIST_ACTIVE_SESSION_HIST view, enabling John to see the wait events of a past session. The data in the AWR is purged by default after seven days.

Conclusion

Oracle Database 10g introduces a number of enhancements designed to automate and simplify the performance diagnostic process. Wait event information is more elaborate in Oracle Database 10g and provides deeper insight into the cause of problems, making the diagnosis of performance problems a breeze in most cases, especially in proactive performance tuning.

Regards
Manoj

SQL Queries for Database Locks


SQL to check lock held by sessions


select substr(to_char(l.session_id)||','||to_char(s.serial#),1,12) sid_ser,
substr(l.os_user_name||'/'||l.oracle_username,1,12) username,
l.process,
p.spid,
substr(o.owner||'.'||o.object_name,1,35) owner_object,
decode(l.locked_mode,
1,'No Lock',
2,'Row Share',
3,'Row Exclusive',
4,'Share',
5,'Share Row Excl',
6,'Exclusive',null) locked_mode,
substr(s.status,1,8) status
from
v$locked_object l,
all_objects o,
v$session s,
v$process p
where
l.object_id = o.object_id
and l.session_id  = s.sid
and s.paddr = p.addr
and s.status != 'KILLED';


SQL to check lock held by particular session 

select substr(to_char(l.session_id)||','||to_char(s.serial#),1,12) sid_ser,
    substr(l.os_user_name||'/'||l.oracle_username,1,12) username,
    l.process,
  p.spid,
    substr(o.owner||'.'||o.object_name,1,35) owner_object,
    decode(l.locked_mode,
    1,'No Lock',
    2,'Row Share',
    3,'Row Exclusive',
    4,'Share',
    5,'Share Row Excl',
    6,'Exclusive',null) locked_mode,
    substr(s.status,1,8) status
    from
  v$locked_object l,
    all_objects o,
    v$session s,
    v$process p
        where
    l.object_id = o.object_id
    and l.session_id = s.sid
    and s.paddr = p.addr
    and s.sid=978;

-------------
sample output
-------------

SID_SER      USERNAME    PROCESS      SPID        OWNER_OBJECT                      LOCKED_MODE    STATUS
------------ ------------ ------------ ------------ ----------------------------------- -------------- --------
978,60077    appmyfai/APP 6275        15225        ONT.OE_HEADERS_IFACE_ALL            Row Exclusive  KILLED
978,60077    appmyfai/APP 6275        15225        ONT.OE_ACTIONS_IFACE_ALL            Row Exclusive  KILLED
978,60077    appmyfai/APP 6275        15225        ONT.OE_PRICE_ADJS_IFACE_ALL        Row Exclusive  KILLED
978,60077    appmyfai/APP 6275        15225        ONT.OE_LINES_IFACE_ALL            Row Exclusive  KILLED
978,60077    appmyfai/APP 6275        15225      BOLINF.XXMF_TX_IN_ORDER_HEADERS    Row Exclusive  KILLED
978,60077    appmyfai/APP 6275        15225        BOLINF.XXMF_TX_IN_COUPONS          Row Exclusive  KILLED
978,60077    appmyfai/APP 6275        15225        BOLINF.XXMF_TX_IN_ORDER_LINES      Row Exclusive  KILLED
978,60077    appmyfai/APP 6275        15225        BOLINF.XXMF_ORDER_HEADERS          Row Exclusive  KILLED
978,60077    appmyfai/APP 6275        15225        BOLINF.XXMF_ORDER_LINES            Row Exclusive  KILLED

Regards
Manoj

Find sessions consuming high memory


Find sessions consuming high memory

SELECT  ss.SID,se.status,
        se.command,
        ss.VALUE CPU,
        se.username,
        se.program,
      se.module,
se.SQL_HASH_VALUE,
        se.logon_time
FROM v$sesstat ss, v$session se
WHERE ss.statistic# IN
(SELECT statistic#
FROM v$statname
WHERE NAME = 'session uga memory') AND se.SID=ss.SID AND ss.SID>6 AND se.username IS  NOT NULL AND se.username<>'SYS'
ORDER BY 4 DESC


Regards
Manoj

Database locks In Detail


Database locks in Detail

Create a blocking lock

To begin, create a situation where one user is actively blocking another. Open two sessions. Issue the following commands in Session 1 to build the test table:

SQL> create table tstlock (foo varchar2(1), bar varchar2(1));

Table created.

SQL> insert into tstlock values (1,'a');

1 row created.

SQL> insert into tstlock values (2, 'b');

1 row created.

SQL> select * from tstlock ;

FOO BAR
--- ---
1   a
2   b

2 rows selected.

SQL> commit ;

Commit complete.

Now grab a lock on the whole table, still in Session 1:

SQL> select * from tstlock for update ;

And in Session 2, try to update a row:

SQL> update tstlock set bar=
  2  'a' where bar='a' ;

This statement will hang, blocked by the lock that Session 1 is holding on the entire table.

Identify the blocking session

Oracle provides a view, DBA_BLOCKERS, which lists the SIDs of all blocking sessions. But this view is often, in my experience, a good bit slower than simply querying V$LOCK, and it doesn't offer any information beyond the SIDs of any sessions that are blocking other sessions. The V$LOCK view is faster to query, makes it easy to identify the blocking session, and has a lot more information.

SQL> select * from v$lock ;

ADDR     KADDR           SID TY        ID1        ID2      LMODE    REQUEST      CTIME      BLOCK
-------- -------- ---------- -- ---------- ---------- ---------- ---------- ---------- ----------
AF9E2C4C AF9E2C60        479 TX     131078      16739          0          6        685          0
ADDF7EC8 ADDF7EE0        422 TM      88519          0          3          0        697          0
ADDF7F74 ADDF7F8C        479 TM      88519          0          3          0        685          0
ADEBEA20 ADEBEB3C        422 TX     131078      16739          6          0        697          1
....     ....            ... ...      ....       ....       ....       ....        ....      ....

Note the BLOCK column. If a session holds a lock that's blocking another session, BLOCK=1. Further, you can tell which session is being blocked by comparing the values in ID1 and ID2. The blocked session will have the same values in ID1 and ID2 as the blocking session, and, since it is requesting a lock it's unable to get, it will have REQUEST > 0.

In the query above, we can see that SID 422 is blocking SID 479. SID 422 corresponds to Session 1 in our example, and SID 479 is our blocked Session 2.

To avoid having to stare at the table and cross-compare ID1's and ID2's, put this in a query:

SQL> select l1.sid, ' IS BLOCKING ', l2.sid
  2  from v$lock l1, v$lock l2
  3  where l1.block =1 and l2.request > 0
  4  and l1.id1=l2.id1
  5  and l1.id2=l2.id2
SQL> /

       SID 'ISBLOCKING'         SID
---------- ------------- ----------
       422  IS BLOCKING         479

1 row selected.

Even better, if we throw a little v$session into the mix, the results are highly readable:

SQL> select s1.username || '@' || s1.machine
  2  || ' ( SID=' || s1.sid || ' )  is blocking '
  3  || s2.username || '@' || s2.machine || ' ( SID=' || s2.sid || ' ) ' AS blocking_status
  4  from v$lock l1, v$session s1, v$lock l2, v$session s2
  5  where s1.sid=l1.sid and s2.sid=l2.sid
  6  and l1.BLOCK=1 and l2.request > 0
  7  and l1.id1 = l2.id1
  8  and l2.id2 = l2.id2 ;


BLOCKING_STATUS
----------------------------------------------------------------------------------------------------
BULKLOAD@yttrium ( SID=422 )  is blocking BULKLOAD@yttrium ( SID=479 )

1 row selected.

There's still more information in the v$lock table, but in order to read that information, we need to understand a bit more about lock types and the cryptically-named ID1 and ID2 columns.

Lock type and the ID1 / ID2 columns

In this case, we already know that the blocking lock is an exclusive DML lock, since we're the ones who issued the locking statement. But most of the time, you won't be so lucky. Fortunately, you can read this information from the v$lock table with little effort.

The first place to look is the TYPE column. There are dozens of lock types, but the vast majority are system types. System locks are normally only held for a very brief amount of time, and it's not generally helpful to try to tune your library cache, undo logs, etc. by looking in v$lock! (See the V$LOCK chapter in the Oracle Database Reference for a list of system lock types.)

There are only three types of user locks, TX, TM and UL. UL is a user-defined lock -- a lock defined with the DBMS_LOCK package. The TX lock is a row transaction lock; it's acquired once for every transaction that changes data, no matter how many objects you change in that transaction. The ID1 and ID2 columns point to the rollback segment and transaction table entries for that transaction.

The TM lock is a DML lock. It's acquired once for each object that's being changed. The ID1 column identifies the object being modified.

Lock Modes

You can see more information on TM and TX locks just by looking at the lock modes. The LMODE and REQUEST columns both use the same numbering for lock modes, in order of increasing exclusivity: from 0 for no lock, to 6 for exclusive lock. A session must obtain an exclusive TX lock in order to change data; LMODE will be 6. If it can't obtain an exclusive lock because some of the rows it wants to change are locked by another session, then it will request a TX in exclusive mode; LMODE will be 0 since it does not have the lock, and REQUEST will be 6. You can see this interaction in the rows we selected earlier from v$lock:

ADDR     KADDR           SID TY        ID1        ID2      LMODE    REQUEST      CTIME      BLOCK
-------- -------- ---------- -- ---------- ---------- ---------- ---------- ---------- ----------
AF9E2C4C AF9E2C60        479 TX     131078      16739          0          6        685          0
ADEBEA20 ADEBEB3C        422 TX     131078      16739          6          0        697          1

Note that ID1 and ID2 in Session 2, which is requesting the TX lock (LMODE=0, REQUEST=6), point back to the rollback and transaction entries for Session 1. That's what lets us determine the blocking session for Session 2.

You may also see TX locks in mode 4, Shared mode. If a block containing rows to be changed doesn't have any interested transaction list (ITL) entries left, then the session acquires a TX lock in mode 4 while waiting for an ITL entry. If you see contention for TX-4 locks on an object, you probably need to increase INITRANS for the object.

TM locks are generally requested and acquired in modes 3, aka Shared-Row Exclusive, and 6. DDL requires a TM Exclusive lock. (Note that CREATE TABLE doesn't require a TM lock -- it doesn't need to lock any objects, because the object in question doesn't exist yet!) DML requires a Shared-Row Exclusive lock. So, in the rows we selected earlier from v$lock, you can see from the TM locking levels that these are DML locks:

ADDR     KADDR           SID TY        ID1        ID2      LMODE    REQUEST      CTIME      BLOCK
-------- -------- ---------- -- ---------- ---------- ---------- ---------- ---------- ----------
ADDF7EC8 ADDF7EE0        422 TM      88519          0          3          0        697          0
ADDF7F74 ADDF7F8C        479 TM      88519          0          3          0        685          0

Identifying the locked object

Now that we know that each TM row points to a locked object, we can use ID1 to identify the object.

SQL> select object_name from dba_objects where object_id=88519 ;

OBJECT_NAME
--------------
TSTLOCK

Sometimes just knowing the object is enough information; but we can dig even deeper. We can identify not just the object, but the block and even the row in the block that Session 2 is waiting on.

Identifying the locked row

We can get this information from v$session by looking at the v$session entry for the blocked session:

SQL> select row_wait_obj#, row_wait_file#, row_wait_block#, row_wait_row#
  2* from v$session where sid=479 ;

ROW_WAIT_OBJ# ROW_WAIT_FILE# ROW_WAIT_BLOCK# ROW_WAIT_ROW#
------------- -------------- --------------- -------------
        88519             16          171309             0

This gives us the object ID, the relative file number, the block in the datafile, and the row in the block that the session is waiting on. If that list of data sounds familiar, it's because those are the four components of an extended ROWID. We can build the row's actual extended ROWID from these components using the DBMS_ROWID package. The ROWID_CREATE function takes these arguments and returns the ROWID:

SQL> select do.object_name,
  2  row_wait_obj#, row_wait_file#, row_wait_block#, row_wait_row#,
  3  dbms_rowid.rowid_create ( 1, ROW_WAIT_OBJ#, ROW_WAIT_FILE#, ROW_WAIT_BLOCK#, ROW_WAIT_ROW# )
  4  from v$session s, dba_objects do
  5  where sid=543
  6  and s.ROW_WAIT_OBJ# = do.OBJECT_ID ;

OBJECT_NAME     ROW_WAIT_OBJ# ROW_WAIT_FILE# ROW_WAIT_BLOCK# ROW_WAIT_ROW# DBMS_ROWID.ROWID_C
--------------- ------------- -------------- --------------- ------------- ------------------
TSTLOCK                 88519             16          171309             0 AAAVnHAAQAAAp0tAAA

And, of course, this lets us inspect the row directly.

SQL> select * from tstlock where rowid='AAAVnHAAQAAAp0tAAA' ;

FOO BAR
--- ---
1   a

Conclusion

We've seen how to identify a blocking session, and how to inspect the very row that the waiting session is waiting for. And, I hope, learned a bit about v$lock in the process.

About the author
Source: http://toolkit.rdbms-insight.com/ .

Regards
Manoj

All About Oracle Database Latches


All About Latches

1. What are Oracle latches?
Latches are Oracle-internal low-level locks that protect the memory structures of the system global area (SGA) against simultaneous accesses. Depending on the memory range, there is either a single parent latch or several child latches that each protect subareas of the memory.

2. How does latch allocation work?
There are two different methods for requesting a latch: "Willing to Wait" and "Immediate", where most latch requests are based on "Willing to Wait":

Willing to Wait mode

  •  If a latch is currently in use, the system checks repeatedly in a loop whether the latch has become available ("spinning"). CPU is used in this loop. At the same time, there are NO active Wait events (not even "latch free" events). The number of loops is defined by the internal _SPIN_COUNT Oracle parameter. If only one CPU is available on the system, this step is skipped. Spinning is useful because, in general, latches are only held for a very short time and the request can be fulfilled quickly. In this case, spinning can prevent a context switch, which also consumes a large amount of resources.
  •  If the latch could not be allocated during the entire loop, the process assumes a "sleep" status for a certain period of time. This period is 0.01 seconds for the first sleep. During this sleep, the "latch free" wait event is activated. As of Oracle 10g "important" latches have to be specified in the form "latch: <latch_name>" whereas the less relevant latches will still be logged as "latch free".
  •  The two steps above are repeated until the latch is allocated successfully. The sleep time doubles with every second program run. The maximum sleep time is 2 seconds if another latch is not held, or 0.04 seconds if the process already holds another latch. 


Immediate mode

 
If the requested latch is already in use, the system immediately tries all the other child latches. If none of the child latches can be allocated, the system switches to Willing to Wait mode. 

3. How can I access latch information on the Oracle system?
The following V$ views contain latch information:

V$LATCH: Provides an overview of the latch waits since the system was started.


  •     NAME: The name of the latch.
  •     GETS: The number of "Willing to Wait" requests.
  •     MISSES: The number of "Willing to Wait" requests that could not allocate the latch in the first attempt.
  •     SPIN_GETS: The number of "Willing to Wait" requests that could allocate the latch in the first spinning without sleep periods.
  •     SLEEPS: The number of "Willing to Wait" requests where the process has entered a sleep period at least once.
  •     SLEEP1: The number of "Willing to Wait" requests with exactly one sleep.
  •     SLEEP2: The number of "Willing to Wait" requests with exactly two sleeps.
  •     SLEEP3: The number of "Willing to Wait" requests with exactly three sleeps.
  •     SLEEP4: The number of "Willing to Wait" requests with four or more sleeps.
  •     IMMEDIATE_GETS: The number of "Immediate" requests.
  •     IMMEDIATE_MISSES: The number of "Immediate" requests where the latch could not be allocated on the first attempt.
  •     WAIT_TIME: The combined sleep times of the latch (as of Oracle 9i). 

V$LATCHHOLDER: Provides an overview over the currently held latches.

  •    PID     : Oracle PID <opid> of the process that holds the latch.
  •    SID: Oracle SID of the session that holds the latch.
  •    NAME: The name of the held latch. 

V$LATCHNAME: Provides an overview of the names of all latches.

  •    LATCH#: The number of the latch.
  •    NAME: The name of the latch. 

V$LATCH_MISSES: The number of sleeps and immediate misses, including the Oracle kernel area.


  •    NWFAIL_COUNT: The number of immediate misses.
  •     SLEEP_COUNT: The number of sleeps.
  •     LOCATION: The Oracle kernel area that holds the requested latch. 


V$LATCH_PARENT: Provides an overview of parent latch waits since the system was started.

    This contains the same fields as V$LATCH.

V$LATCH_CHILDREN: Provides an overview of child latch waits since the system was started.

  •    CHILD#: The number of the child latch.
  •     All other fields are the same as in V$LATCH. 


4. How can I access latch information on the R/3 system?
Note the fundamentals for the Oracle performance analysis contained in Note 618868.

5. How I can recognize latch problems?
A latch problem usually exists when there are long "latch free" wait times. Therefore if, when you analyze the wait events in accordance with Note 619188,

you notice that either the entire system or individual transactions are impaired by "latch free" or "latch: <latch_name>" waits, it is worthwhile analyzing and optimizing the latch waits.

6. How can I determine the latches for which the system is currently waiting?
Use the following command to determine which sessions are currently waiting for which latch:

SELECT
   W.SID,
   L.NAME
FROM
   V$SESSION_WAIT W,
   V$LATCHNAME L
WHERE
   W.EVENT LIKE 'latch%' AND
   W.P2 = L.LATCH# AND
   W.STATE = 'WAITING';

7. How can I determine the current latch holders?
Note 20071 describes how you can use the V$LATCHHOLDER view or the BLOCKING_SESSION column from V$SESSION (Oracle 10g or higher) to determine the current

latch holder.

8. How can I determine the most critical latches?
The most critical latches can be determined based on the time spent waiting fr a latch. This information is contained in the WAIT_TIME column of the V$LATCH view. Use the following statement to retrieve the ten latches with the longest wait times since the system was started:

SELECT * FROM (SELECT NAME, WAIT_TIME FROM V$LATCH
ORDER BY WAIT_TIME DESC) WHERE ROWNUM <= 10;

The WAIT_TIME column is only available in Oracle versions after Oracle 8i. In earlier versions, you must use the SLEEPS column for this purpose.It is only useful to determine and tune the most critical latches if an actual latch problem exists. It is completely normal that certain latches such as "shared pool" or "library cache" have significant wait times and are listed at the top of the list.

9. How can I determine objects that are linked to latch waits?
As of Oracle 10g, the V$ACTIVE_SESSION_HISTORY view provides information about the last active wait situations and the affected objects. See Note 619188 for further information. Frequently, latch waits are the essential concurrency waits. Therefore, candidates for latch problems as of Oracle 10g can be determined using the following 

query:

SELECT * FROM
(SELECT
     ROUND(CONCURRENCY_WAIT_TIME / 1000000)
       "CONCURRENCY WAIT TIME (S)",
     EXECUTIONS
     SQL_ID,
     SQL_TEXT
   FROM
     V$SQLSTATS
   ORDER BY CONCURRENCY_WAIT_TIME DESC )
WHERE ROWNUM <=10;

10. What are the general reasons and possible solutions for long latch wait times?
The following are typical reasons for long latch wait times:

Very high access rates to certain memory resources
Reduce the load of these resources depending on the latch wait times that occur as described below.


CPU bottleneck

A CPU bottleneck on the database server may cause extremely long latch waits if processes that hold critical latches are pushed out of the CPU (context switch). In addition, a CPU bottleneck is intensified by the spinning process. Therefore, you should check at operating system level, or by using transactions ST06 or OS07, that there is no CPU bottleneck on the database server (see the CPU guidelines described in Note 618868).

Large-scale parallel processing

On R/3, if an action is parallel-processed too intensively and a lot of processes therefore access the same memory area at the same time, latch waits are very likely. The spinning causes the processes waiting for a latch to consume a lot of CPU memory, which means that the processes that have the latch are pushed from the CPU more quickly. As a result, the latch is kept longer than necessary and the situation deteriorates. Therefore check whether reducing the parallel processing of processes with similar database accesses would reduce the latch waits and improve performance.

Oracle bugs

           Some Oracle bugs may cause long latch wait times. Some of the bugs of which we are aware are listed below in the tuning tips for actual latch waits. However, it is always useful to check for other possible bugs in each case.

Interrupted network connection

           Read Note 20071 and ensure that the latch problem is not caused by an interrupted network connection.

Events and underscore parameters

           In individual cases, Oracle events or underscore parameters may be responsible for increased latch times. For example, setting the 10501 event may cause massive problems due to "shared pool" latches.

           Therefore, check whether there are settings that are not recommended by SAP or are no longer required with the database release that you use, and

remove these.

Oversized shared pool

  In some cases, an oversized shared pool can cause latch wait situations on the shared pool (for example, "library cache" or "row cache objects" latch) since the Oracle-internal administrative structure can by overloaded by the amount of simultaneously retained information. Check whether the configuration of the shared pool is significantly larger than Note 789011 recommends. If this is the case, you should consider a reduction of the SHARED_POOL_SIZE. As a quick solution you can use

ALTER SYSTEM FLUSH SHARED_POOL;

Paging

Increased paging may also lead to latch problems. If a process has allocated a latch, and must retrieve the relevant memory area from the disk, it may take longer until the latch is released again. Therefore, latch wait situations are more likely.

HP-UX: Process scheduling

When you use HP-UX, critical latch situations may be made worse by the default process scheduling mechanism, if processes in critical sections (in other words, with a held latch) are displaced from the CPU. In this case, you can reconsider using the HPUX_SCHED_NOAGE Oracle parameter in accordance with 

metalink document 217990.1 to reduce these displacements.

Error ORA-04031:

In individual cases, ORA-04031 error situations can lead to increased latch waits. Therefore, check if ORA-04031 errors were logged in critical latch periods, and see Note 869006 if this is the case.

11. How can I tune actual latch waits?
Depending on which latch the system is waiting for, you have the following options:

library cache / library cache pin

           Wait event > = 10g: "latch: library cache" / "latch: library cache pin"

Wait situations on the "library cache" latch and "library cache pin" latch usually occur in the SAP environment, if you execute a large number of identical SQL statements in parallel (with relation to bind variables). Therefore, avoid the parallel execution of a large number of similar SQL statements that only differ in the content of their bind variables. To determine which SQL statements are responsible for the latch problems, first determine the child latches:

SELECT NAME, CHILD#, WAIT_TIME
FROM V$LATCH_CHILDREN
WHERE NAME LIKE 'library cache%'
ORDER BY WAIT_TIME DESC;

           You can then start a query on V$SQL for the child latches that have the longest waiting period:

SELECT * FROM
( SELECT EXECUTIONS, PARSE_CALLS, ADDRESS, SQL_TEXT
   FROM V$SQL
   WHERE CHILD_LATCH = <child#>
   ORDER BY EXECUTIONS DESC )
WHERE ROWNUM <=10;

The system returns the 10 SQL statements that are protected by the child latch specified, and that are executed most frequently. In certain cases it may be recommended to increased the number of latches using the Oracle parameter _KGL_LATCH_COUNT. Depending on this parameter, the number of library cache" latches, "library cache pin" latches and "library cache pin allocation" latches is determined using the following 

formula:

#Latches = MIN(67, next_larger_prime_number(_KGL_LATCH_COUNT))

As a last solution, you may consider using SQL statements that have similar meaning but are different from a parse point of view (for example, by specifying a different comment or pseudo hint). By this, the load is distributed more evenly on different child latches. Wait situations for the "library cache" latch occur if the system must parse a large number of SQL statements. Therefore, you should check the 

following points:


  •     Check, as described in Note 618868, whether the shared pool size is sufficient.
  •     Avoid the large-scale use of REPARSE or SUBSTITUTE VALUES hints according to Note 129385, as these hints mean that significantly more statements must  be parsed.
  •    The creation of statistics, shared pool flushes and DDL statements (for example, TRUNCATE) also require additional parsing of statements. Therefore, 


you should also check to what extent these actions occur on a large scale.

shared pool

           Wait event >= 10g: "latch: shared pool"
           Refer to the information about the "library cache" latch above.

cache buffers chains

           Wait event >= 10g: "latch: cache buffer chains"
           "Cache buffers chains" latch waits are usually caused by hot blocks, that is, blocks that are accessed frequently. Hot blocks can be identified as  follows:

Execute the following statement repeatedly to determine which "cache buffers chains" child latch is responsible for the highest number of sleeps:

      SELECT
      *
      FROM
      (SELECT
      CHILD#,
      ADDR,
      WAIT_TIME
      FROM
      V$LATCH_CHILDREN
      WHERE
      NAME = 'cache buffers chains'
      ORDER BY
      WAIT_TIME DESC)
      WHERE
      ROWNUM < 10;


Now execute the following query for X$BH with the ADDR value of the most expensive child latch to determine which blocks protected by the child latch 

have the highest touchcount:

      SELECT /*+ RULE */
      SUBSTR(E.OWNER, 1, 15) OWNER,
      SUBSTR(E.SEGMENT_NAME, 1, 20) SEGMENT_NAME,
      X.FILE# "FILE",
      X.DBABLK "BLOCK",
      DECODE(X.DBABLK - BLOCK_ID + EXTENT_ID, 0, 'YES', 'NO') HEADER,
      SUM(X.TCH) "TOUCHCOUNT"
      FROM V$LATCH_CHILDREN L, X$BH X, DBA_EXTENTS E
      WHERE X.HLADDR = '<addr>' AND
      E.FILE_ID = X.FILE# AND
      X.HLADDR = L.ADDR AND
      X.DBABLK BETWEEN
      E.BLOCK_ID AND E.BLOCK_ID + E.BLOCKS - 1
      GROUP BY E.OWNER, E.SEGMENT_NAME, X.FILE#, X.DBABLK,
      DECODE(X.DBABLK - BLOCK_ID + EXTENT_ID, 0, 'YES', 'NO'),
      X.TCH
      ORDER BY SUM(X.TCH) ASC;
   
The touchcount is only a rough measurement for using individual blocks - even if a block is used repeatedly within a very short time, the touchcount is only increased once. Nevertheless, combined with the executed SQL statements, it may be a useful indication of the trigger of "cache buffers chains" latches.

By optimizing the accesses to the relevant objects, you can also reduce the number of "cache buffers chains" latches. On Oracle 8.1. 7, the "cache buffers chains" latches may be triggered by the Oracle bugs described in Notes 449136 and 488583. The number of "cache buffers chains" latches depends on the size of the buffer pool and can be approximated using the following formula:

#Latches =
   Next largest power of 2 (Size of the buffer pool/1048576).

The exact calculation formula depends on the use of DB_BLOCK_BUFFERS vs. DB_CACHE_SIZE, since block header information is also stored in the  granules when DB_CACHE_SIZE is used. Also, the size of the granules is important for DB_CACHE_SIZE. The following default values should in any case return 

the larger number of latches:

    * Buffer Pool < 1124073472 Byte -> 1024 Latches
    * Buffer Pool >= 1124073472 Byte -> 2048 Latches
    * Buffer Pool >= 2231369728 Byte -> 4096 Latches
    * Buffer Pool >= 4445962240 Byte -> 8192 Latches
    * Buffer Pool >= 8875147264 Byte -> 16384 Latches
    * Buffer Pool >= 17733517312 Byte -> 32768 Latches
    * Buffer Pool >= 35500000000 Byte -> 65536 Latches

If you have problems with "cache buffers chains" latches, and have defined an Oracle buffer pool just below one of the threshold values described above and have enough memory available to increase the size of the buffer pool, it may be useful to increase the buffer pool size to the next threshold value.

Alternatively, you can use the _DB_BLOCK_HASH_LATCHES parameter to define the number of "cache buffers chains" latches. However, you should only explicitly set this parameter in individual cases that warrant this setting.  If "cache buffers chains" latches occur in Oracle 10.2.0. 2, see Note 1020225.

cache buffers lru chain

         Wait event >= 10g: "latch: cache buffers lru chain"
          They are usually triggered by expensive SQL statements. Perform an SQL optimization as described in Note 766349.

 In addition, check whether the DBWR performs poorly when you save dirty blocks (for example, using a wait event analysis as described in Note 619188). You should also ensure that the Oracle buffer pool size is sufficient (see the information in Note 618868). Alternatively, you can use the _DB_BLOCK_LRU_LATCHES parameter to adjust the number of "cache buffers lru chain" latches. However, you should only explicitly set this parameter in individual cases that warrant this setting.

cache buffer handles

           Wait event >= 10g: "latch: cache buffer handles"

In Oracle 8.1. 7, the bug described in Note 400698 may be responsible for serializations of the "cache buffer handles" latch. enqueue hash chains

           Wait event >= 10g: "latch: enqueue hash chains"

If wait times for "enqueue hash chains" latches occur together with deadlock dumps, see Note 596420 and ensure that bottlenecks do not occur when dump files are created (I/O, mount options of the file system, and so on). archive control Wait situations on the "archive control" latch are generally a follow-on problem of archiver stuck situations. You should therefore check whether an archiver stuck situation has occurred, as described in Note 391.

undo global data

The "undo global data" latch is required for accessing undo data. Increased waiting imes on this latch are usually due to expensive SQL statements that access consistent read images due to the data in the undo segments. In this case, optimize the expensive SQL statements and make sure that there is no large number of open changes (also see Note 913247). 

query server process

The "query server process" latch is retained if new slaves are generated during parallel execution. Refer to the corresponding information in Note 651060.

simulator lru latch

Significant wait times for the "simulator lru latch" are often a result of processing-intensive SQL statements that execute a large number of buffer gets. Therefore, you must first check if these accesses exist and whether they can be optimized. Long waiting times for the "simulator lru latch" may also occur when you create fixed object statistics using DBMS_STATS.GATHER_FIXED_OBJECTS_STATS (or "brconnect -f oradict_stats"). This affects mainly systems with a large buffer pool, as in these cases, the table X$KCBSH becomes quite large. Therefore, the statistics creation on this table takes a long time. During the statistics creations, problems with the "simulator lru latch" may occur.

As a workaround, you can set the parameter  DB_CACHE_ADVICE to OFF, which means that the LRU simulation is deactivated in the buffer pool. Note that if you perform this task, you can no longer collect data in V$DB_CACHE_ADVICE (Note 617416).

12. Will latch deadlocks occur?
Generally, the Oracle implementation ensures that no latch deadlocks can occur. However, in the case of bugs, deadlocks may occur. In this case, the transaction terminates with ORA-00600 [504]. If you encounter this error and you cannot find a suitable note, you should create a customer message.

13. Where can I find more information about latches?
Oracle documentation:

Oracle9i Performance Tuning Guide and Reference
22 Instance Tuning
-> Wait Events
-> latch free

Oracle 9i Reference
-> Dynamic Performance Views
-> V$LATCH

Oracle 10g Performance Tuning Guide and Reference
10 Instance Tuning Using Performance Views
-> Wait Events Statistics

Oracle 10g Reference
-> 4 Dynamic Performance Views
-> V$LATCH


Regards
Manoj

Oracle E-business suite logs clean up

 Oracle E-business suite logs clean up #!/bin/bash cd $EBS_DOMAIN_HOME find $EBS_DOMAIN_HOME -type f -path "*/logs/*.log?*" -mtime...