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

Automatic Shared Memory Management in Oracle 10g ( ASMM)

OVERVIEW:


It used to be a challenge to size the various memory pools that comprise the Oracle system global area (SGA) for optimal performance. In real world most of the Oracle Databases are of Hybrid type. They are OLTP in day time when the accessibility is high and in the night time, many batch jobs run on the same database to extract data or to run big reports. This will be a combination of the OLTP, OLAP, DSS and HYBRID type of database. Since various types of applications require the underlined memory pools differently, and since the workload can vary minute by minute, manually resizing the SGA components could feel like a never-ending task.
If there is not enough free SGA to allocate for a specific pool when needed, the database will give out-of-memory error, such as

ORA-04031: unable to allocate …

The requirement for the database varies from time to time. During OLTP operation (when most of the users accessing the data) the response time should be minimum. During night time the turn around time should be short when response time is not so important.

The combination of these kinds of requirement makes the task of the DBA a little bit tougher. DBA needs to set the SGA in such a way that demands meet in a balance. But this is tough job. To ease such issue, Oracle has come up with Automatic Shared Memory Management feature in Oracle 10g which will adjust the requirement of the memory component as per demand of the system.

Advantage of ASMM:

Oracle Database 10g, ASMM automatically sizes many of the memory pools while the database is running, allocating and de-allocating memory as needed. As the workload composition changes, Oracle Database 10g enlarges the appropriate pools and reduces the sizes of other automatically sized pools accordingly. In short, ASMM can save the DBA a lot of trouble—and improve overall performance as well.


The main advantage ASMM is that Oracle Database server itself will adjust the following SGA parameters as per the requirement of the system.

·         DB_CACHE_SIZE
·         JAVA_POOL_SIZE
·         LARGE_POOL_SIZE
·         SHARED_POOL_SIZE

Remaining components of the SGA are not adjustable by this method. They need to be manually adjusted. They are
  • LOG_BUFFER
  • DB_KEEP_CACHE_SIZE
  • DB_RECYCLE_CACHE_SIZE
  • DB_nK_CACHE_SIZE (n = 2, 4, 8, 16, 32, and nk is non-standard Data block size.))
  • STREAMS_POOL_SIZE (In Oracle 10g Release 2. STEAMS_POOL_SIZE can be automatically managed.)  

The ASSM feature will lessen the involvement of DBA to set the different SGA components from time to time based on the demand of the workload. It will improve the performance of the database also reduce the cost factor by elimination of adding additional System resource (Memory, etc).

How to setup ASMM:
The STATISTICS_LEVEL initialization parameter must be set to TYPICAL (the default) or ALL. That sets the statistics collection level of the database. (The other value of this parameter is BASIC, which will not allow changing the memory pools automatically.)



Oracle 10g has introduced a new parameter by name SGA_TARGET.

DBA has to set up the SGA_TARGET to a non-zero value that will enable the automatic memory allocation. The SGA_TARGET can be configured dynamically by issuing “Alter system” command or by setting that in Parameter file.

DBA needs to set the below mentioned memory parameters to 0 in the parameter file or remove them completely from the parameter file.

DB_CACHE_SIZE = 0
JAVA_POOL_SIZE = 0
LARGE_POOL_SIZE = 0
SHARED_POOL_SIZE =0

DBA can also do resizing of the autotuned pools to 0, as follows:

SQL> alter system set sga_target=160M scope=both;
System altered.

SQL> alter system set db_cache_size=0;
System altered.

SQL> alter system set shared_pool_size=0;
System altered.
……..

The ORACLE database will share that memory into separate component as mentioned below. The individual pools within the SGA will be dynamically configured based on the workload.  From time to time, based on the composition of the work load, the pools will expand to accommodate the increase in demand or shrink to accommodate the expansion in another pool. This expansion or contraction occurs automatically without the DBA's intervention. 

·         DB_CACHE_SIZE
·         JAVA_POOL_SIZE
·         LARGE_POOL_SIZE
·         SHARED_POOL_SIZE

There are few components of SGA that can’t be automatically tuned; those components need to be set manually.  Manually sized components consume memory from the target value first, and then the remainder of SGA memory is spread across the various auto sized pools. In other words, if DBA sets parameter values for any of these below mentioned manually tuned pools, Oracle Database 10g subtracts their sizes from SGA_TARGET first, before allocating memory to the automatically allocated pools.
  • DB_KEEP_CACHE_SIZE
  • DB_RECYCLE_CACHE_SIZE
  • DB_nK_CACHE_SIZE (n = 2, 4, 8, 16, 32 and nk is non-standard Data block size)
  • LOG_BUFFER
  • STREAMS_POOL_SIZE (In Oracle 10g Release 2. STEAMS_POOL_SIZE can be automatically managed.) 
The SGA_TARGET can’t cross the size of SGA_MAX_SIZE. SGA_MAX_SIZE can’t be resized dynamically. To reset the SGA_MAX_SIZE, the Oracle Instance needs to be renounced.

Setting a Minimum Value for variable pools:

If DBA doesn't set the values for each of the automatically tuned pools to zero after switching to ASMM, whatever value DBA had set for a parameter will function as a lower threshold value for that pool—ASMM won't go below a nonzero value, even if it needs the memory for another automatically tuned pool.
Suppose, DBA has set up the following parameters in parameter file after switching to ASSM feature.

LARGE_POOL_SIZE = 16M
JAVA_POOL_SIZE = 8 M

In that case, LARGE_POOL_SIZE will never go below 16 MB and JAVA_POOL_SIZE will never go below 8MB.

DBA can also do that by dynamically using ALTER SYSTEM as shown below.
alter system set large_pool_size = 16M; 
alter system set java_pool_size = 8M;
Of course, these pools are still governed by Automatic Shared Memory Management—their sizes will shrink or expand based on demand. The values DBA has specified explicitly put a lower limit on the pool size; they will never sink below this limit.

Oracle DBA FAQs - 2

Differentiate between TRUNCATE and DELETE.


The Delete command will log the data changes in the log file where as the truncate will simply remove the data without it. Hence Data removed by Delete command can be rolled back but not the data removed by TRUNCATE. Truncate is a DDL statement whereas DELETE is a DML statement.

What is the maximum buffer size that can be specified using the DBMS_OUTPUT.ENABLE function?

1000000

Can you use a commit statement within a database trigger?

Yes, if you are using autonomous transactions in the Database triggers.

What is an UTL_FILE? What are different procedures and functions associated with it?

The UTL_FILE package lets your PL/SQL programs read and write operating system (OS) text files. It provides a restricted version of standard OS stream file input/output (I/O).
Subprogram -Description
FOPEN function-Opens a file for input or output with the default line size.
IS_OPEN function -Determines if a file handle refers to an open file.
FCLOSE procedure -Closes a file.
FCLOSE_ALL procedure -Closes all open file handles.
GET_LINE procedure -Reads a line of text from an open file.
PUT procedure-Writes a line to a file. This does not append a line terminator.
NEW_LINE procedure-Writes one or more OS-specific line terminators to a file.
PUT_LINE procedure -Writes a line to a file. This appends an OS-specific line terminator.
PUTF procedure -A PUT procedure with formatting.
FFLUSH procedure-Physically writes all pending output to a file.
FOPEN function -Opens a file with the maximum line size specified.

Difference between database triggers and form triggers?

Database triggers are fired whenever any database action like INSERT, UPATE, DELETE, LOGON LOGOFF etc occurs. Form triggers on the other hand are fired in response to any event that takes place while working with the forms, say like navigating from one field to another or one block to another and so on.

What is OCI. What are its uses?

OCI is Oracle Call Interface. When applications developers demand the most powerful interface to the Oracle Database Server, they call upon the Oracle Call Interface (OCI). OCI provides the most comprehensive access to all of the Oracle Database functionality. The newest performance, scalability, and security features appear first in the OCI API. If you write applications for the Oracle Database, you likely already depend on OCI. Some types of applications that depend upon OCI are:

· PL/SQL applications executing SQL
· C++ applications using OCCI
· Java applications using the OCI-based JDBC driver
· C applications using the ODBC driver
· VB applications using the OLEDB driver
· Pro*C applications
· Distributed SQL

What are ORACLE PRECOMPILERS?

A precompiler is a tool that allows programmers to embed SQL statements in high-level source programs like C, C++, COBOL, etc. The precompiler accepts the source program as input, translates the embedded SQL statements into standard Oracle runtime library calls, and generates a modified source program that one can compile, link, and execute in the usual way. Examples are the Pro*C Precompiler for C, Pro*Cobol for Cobol, SQLJ for Java etc.

What is syntax for dropping a procedure and a function? Are these operations possible?

Drop Procedure/Function ; yes, if they are standalone procedures or functions. If they are a part of a package then one have to remove it from the package definition and body and recompile the package.


How to check if Apps 11i System is Autoconfig enabled ?

Under $AD_TOP/bin check for file adcfginfo.sh and if this exists use adcfginfo.sh contextfile= show=enabled

If this file is not there , look for any configuration file under APPL_TOP if system is Autoconfig enabled then you will see entry like


How to check if Oracle Apps 11i System is Rapid Clone enabled ?

For syetem to be Rapid Clone enabled , it should be Autoconfig enabled (Check above How to confirm if Apps 11i is Autoconfig enabled). You should have Rapid Clone Patches applied , Rapid Clone is part of Rapid Install Product whose Family Pack Name is ADX. By default all Apps 11i Instances 11.5.9 and above are Autoconfig and Rapid Clone enabled.

Whats is difference between two env files in .env and APPS.env under $APPL_TOP ?

APPS.env is main environment file which inturn calls other environment files like .env under $APPL_TOP, .env under 806 ORACLE_HOME and custom.env for any Customized environment files.

Whats main concurrent Manager types.

# ICM - Internal Concurrent Manager which manages concurrent Managers
# Standard Managers - Which Manage processesing of requests.
# CRM - Conflict Resolution Managers , resolve conflicts in case of incompatibility.

Whats US directory in $AD_TOP or under various product TOP's .


US directory is defauly language directory in Oracle Applications. If you have multiple languages Installed in your Applications then you will see other languages directories besides US, that directory will contain reports, fmx and other code in that respective directory like FR for France, AR for arabic, simplifies chinese or spanish.

Where is Concurrent Manager log file location.

By default standard location is $APPLCSF/$APPLLOG , in some cases it can go to $FND_TOP/log as well.

Where would i find .rf9 file, and what execatly it dose ?

These files are used during restart of patch in case of patch failure because of some reason.

Where is appsweb.cfg or appsweb_$CONTEXT.cfg stored and why its used ?

This file is defined by environment variable FORMS60_WEB_CONFIG_FILE This is usually in directory $OA_HTML/bin on forms tier.

This file is used by any forms client session. When a user try to access forms , f60webmx picks up this file and based on this configuration file creates a forms session to user/client.

What is Multi Node System ?

Multi Node System in Oracle Applications 11i means you have Applications 11i Component on more than one system. Typical example is Database, Concurrent Manager on one machine and forms, Web Server on second machine is example of Two Node System.


Can a function take OUT parameters. If not why?

yes, IN, OUT or IN OUT.

Can the default values be assigned to actual parameters?

Yes. In such case you don’t need to specify any value and the actual parameter will take the default value provided in the function definition.

What is difference between a formal and an actual parameter?

The formal parameters are the names that are declared in the parameter list of the header of a module. The actual parameters are the values or expressions placed in the parameter list of the actual call to the module.

What are different modes of parameters used in functions and procedures?

There are three different modes of parameters: IN, OUT, and IN OUT.

IN - The IN parameter allows you to pass values in to the module, but will not pass anything out of the module and back to the calling PL/SQL block. In other words, for the purposes of the program, its IN parameters function like constants. Just like constants, the value of the formal IN parameter cannot be changed within the program. You cannot assign values to the IN parameter or in any other way modify its value.

IN is the default mode for parameters. IN parameters can be given default values in the program header.

OUT - An OUT parameter is the opposite of the IN parameter. Use the OUT parameter to pass a value back from the program to the calling PL/SQL block. An OUT parameter is like the return value for a function, but it appears in the parameter list and you can, of course, have as many OUT parameters as you like.

Inside the program, an OUT parameter acts like a variable that has not been initialised. In fact, the OUT parameter has no value at all until the program terminates successfully (without raising an exception, that is). During the execution of the program, any assignments to an OUT parameter are actually made to an internal copy of the OUT parameter. When the program terminates successfully and returns control to the calling block, the value in that local copy is then transferred to the actual OUT parameter. That value is then available in the calling PL/SQL block.

IN OUT - With an IN OUT parameter, you can pass values into the program and return a value back to the calling program (either the original, unchanged value or a new value set within the program). The IN OUT parameter shares two restrictions with the OUT parameter:

An IN OUT parameter cannot have a default value.

An IN OUT actual parameter or argument must be a variable. It cannot be a constant, literal, or expression, since these formats do not provide a receptacle in which PL/SQL can place the outgoing value.

Locks Script in ORACLE

LOCKS:

Locks are mechanisms that prevent destructive interaction between transactions accessing the same resource.
Oracle has several views for showing lock status, some of which show the username:
  • DBA_BLOCKERS – Shows non-waiting sessions holding locks being waited-on
  • DBA_DDL_LOCKS – Shows all DDL locks held or being requested
  • DBA_DML_LOCKS  - Shows all DML locks held or being requested
  • DBA_LOCK_INTERNAL – Displays 1 row for every lock or latch held or being requested with the username of who is holding the lock 
  • DBA_LOCKS  - Shows all locks or latches held or being requested
  • DBA_WAITERS  - Shows all sessions waiting on, but not holding waited for locks
The following script is commonly used by Oracle professionals who need to quickly find out all database objects that are locked within their system.
Most Oracle professionals use of the v$locked_object view in order to gather information about objects that are locked within the Oracle database.  The v$locked_object view can also be joined into the v$session view in order to gather session level information (SID, PID, status, machine) , and also joined into the dba_objects view in order to get the owner, the object name, and the type of objects that is currently being locked within the database.
The following script can be used in order quickly identify all lock objects within your Oracle system.

select
   c.owner,
   c.object_name,
   c.object_type,
   b.sid,
   b.serial#,
   b.status,
   b.osuser,
   b.machine
from
   v$locked_object a ,
   v$session b,
   dba_objects c
where
   b.sid = a.session_id
and
   a.object_id = c.object_id;


DEADLOCK:

Oracle automatically detects deadlock situations and resolves them by rolling back one of the statements involved in the deadlock.  This releases one set of the conflicting row locks. A corresponding message also is returned to the transaction that undergoes the rollback.

Below the script is useful for identify  – “ Who is blocking to whom ”

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

below script is useful  for  “who’s Holder and Who’s Waiter” to query.

SELECT  /*+ FIRST_ROWS ORDERED */ DECODE(request,0,'Holder: ','Waiter: ')||sid sess,
         id1, id2, lmode, request, type
    FROM V$LOCK
   WHERE (id1, id2, type) IN
             (SELECT id1, id2, type FROM V$LOCK WHERE request>0)
   ORDER BY id1, request;


Below the scriprt is Useful for identify Database level locks.

select    nvl(S.USERNAME,'Internal') username,
                nvl(S.TERMINAL,'None') terminal,
                L.SID||','||S.SERIAL# Kill, b.spid,
                U1.NAME||'.'||substr(T1.NAME,1,20) tab,
                decode(L.LMODE,1,'No Lock',
                                2,'Row Share',
                                3,'Row Exclusive',
                                4,'Share',
                                5,'Share Row Exclusive',
                                6,'Exclusive',null) lmode,
                decode(L.REQUEST,1,'No Lock',
                                2,'Row Share',
                                3,'Row Exclusive',
                                4,'Share',
                                5,'Share Row Exclusive',
                                6,'Exclusive',null) request
from      V$LOCK L, 
                V$SESSION S,
                SYS.USER$ U1,
                SYS.OBJ$ T1 ,
                v$process b
where   L.SID = S.SID 
and        T1.OBJ# = decode(L.ID2,0,L.ID1,L.ID2) 
and        U1.USER# = T1.OWNER#
and        S.TYPE != 'BACKGROUND'
and        s.paddr = b.addr    order by 1,2,5 ;

Oracle DBA FAQs - 1

What Is Oracle?
Oracle is a company. Oracle is also a database server, which manages data in a very structured way. It allows users to store and retrieve related data in a multiuser environment so that many users can concurrently access the same data. All this is accomplished while delivering high performance. A database server also prevents unauthorized access and provides efficient solutions for failure recovery.
What Is an Oracle Database?
An Oracle database is a collection of data treated as a big unit in the database server.
What Is an Oracle Instance?
Every running Oracle database is associated with an Oracle instance. When a database is started on a database server (regardless of the type of computer), Oracle allocates a memory area called the System Global Area (SGA) and starts one or more Oracle processes. This combination of the SGA and the Oracle processes is called an Oracle instance. The memory and processes of an instance manage the associated database's data efficiently and serve the one or multiple users of the database.
What Is a Parameter File?
A parameter file is a file that contains a list of initialization parameters and a value for each parameter. You specify initialization parameters in a parameter file that reflect your particular installation. Oracle supports the following two types of parameter files:
  • Server Parameter Files - Binary version. Persistent.
  • Initialization Parameter Files - Text version. Not persistent.
What Is a Server Parameter File?
A server parameter file is a binary file that acts as a repository for initialization parameters. The server parameter file can reside on the machine where the Oracle database server executes. Initialization parameters stored in a server parameter file are persistent, in that any changes made to the parameters while an instance is running can persist across instance shutdown and startup.
What Is a Initialization Parameter File?
An initialization parameter file is a text file that contains a list of initialization parameters. The file should be written in the client's default character set. Sample initialization parameter files are provided on the Oracle distribution medium for each operating system. A sample file is sufficient for initial use, but you will probably want to modify the file to tune the database for best performance. Any changes will take effect after you completely shut down and restart the instance.
What is System Global Area (SGA)?
The System Global Area (SGA) is a memory area that contains data shared between all database users such as buffer cache and a shared pool of SQL statements. The SGA is allocated in memory when an Oracle database instance is started, and any change in the value will take effect at the next startup.
What is Program Global Area (PGA)?
A Program Global Area (PGA) is a memory buffer that is allocated for each individual database session and it contains session specific information such as SQL statement data or buffers used for sorting. The value specifies the total memory allocated by all sessions, and changes will take effect as new sessions are started.
What Is a User Account?
A user account is identified by a user name and defines the user's attributes, including the following:
  • Password for database authentication
  • Privileges and roles
  • Default tablespace for database objects
  • Default temporary tablespace for query processing work space
What Is the Relation of a User Account and a Schema?
User accounts and schemas have a one-to-one relation. When you create a user, you are also implicitly creating a schema for that user. A schema is a logical container for the database objects (such as tables, views, triggers, and so on) that the user creates. The schema name is the same as the user name, and can be used to unambiguously refer to objects owned by the user.
What Is a User Role?
A user role is a group of privileges. Privileges are assigned to users through user roles. You create new roles, grant privileges to the roles, and then grant roles to users.
What is a Database Schema?
A schema is a collection of logical structures of data, or schema objects. A schema is owned by a database user and has the same name as that user. Each user owns a single schema. Schema objects can be created and manipulated with SQL and include: tables, views, and other types of data objects.
What Is a Database Table?
A database table is a basic unit of data logical storage in an Oracle database. Data is stored in rows and columns. You define a table with a table name, such as employees, and a set of columns. You give each column a column name, such as employee_id, last_name, and job_id; a datatype, such as VARCHAR2, DATE, or NUMBER; and a width. The width can be predetermined by the datatype, as in DATE. If columns are of the NUMBER datatype, define precision and scale instead of width. A row is a collection of column information corresponding to a single record.
What Is a Table Index?
Index is an optional structure associated with a table that allow SQL statements to execute more quickly against a table. Just as the index in this manual helps you locate information faster than if there were no index, an Oracle Database index provides a faster access path to table data. You can use indexes without rewriting any queries. Your results are the same, but you see them more quickly.
What Is an Oracle Tablespace?
An Oracle tablespace is a big unit of logical storage in an Oracle database. It is managed and used by the Oracle server to store structures data objects, like tables and indexes.
Each tablespace in an Oracle database consists of one or more files called datafiles, which are physical structures that conform to the operating system in which Oracle is running.
What Is an Oracle Data File?
An Oracle data file is a big unit of physical storage in the OS file system. One or many Oracle data files are organized together to provide physical storage to a single Oracle tablespace.
What Is a Static Data Dictionary?
Data dictionary tables are not directly accessible, but you can access information in them through data dictionary views. To list the data dictionary views available to you, query the view DICTIONARY. Many data dictionary tables have three corresponding views:
  • An ALL_ view displays all the information accessible to the current user, including information from the current user's schema as well as information from objects in other schemas, if the current user has access to those objects by way of grants of privileges or roles.
  • A DBA_ view displays all relevant information in the entire database. DBA_ views are intended only for administrators. They can be accessed only by users with the SELECT ANY TABLE privilege. This privilege is assigned to the DBA role when the system is initially installed.
  • A USER_ view displays all the information from the schema of the current user. No special privileges are required to query these views.
What Is a Dynamic Performance View?
Oracle contains a set of underlying views that are maintained by the database server and accessible to the database administrator user SYS. These views are called dynamic performance views because they are continuously updated while a database is open and in use, and their contents relate primarily to performance. Although these views appear to be regular database tables, they are not. These views provide data on internal disk structures and memory structures. You can select from these views, but you can never update or alter them.

SCRIPT TO MONITOR MEMORY USAGE BY DATABASE SESSIONS

=============================================================================
SCRIPT TO MONITOR MEMORY USAGE BY DATABASE SESSIONS
=============================================================================
REM Created: 21/march/2003
REM Last update: 28/may/2003
REM
REM NAME
REM ====
REM MEMORY.sql
REM
REM
REM DISCLAIMER
REM ==========
REM This script is provided for educational purposes only. It is NOT supported by
REM Oracle World Wide Technical Support. The script has been tested and appears
REM to work as intended. However, you should always test any script before
REM relying on it.
REM
REM PURPOSE
REM =======
REM Retrieves PGA and UGA statistics for users and background processes sessions.
REM
REM EXECUTION ENVIRONMENT
REM =====================
REM SQL*Plus
REM
REM ACCESS PRIVILEGES
REM =================
REM Select on V$SESSTAT, V$SESSION, V$BGPROCESS, V$PROCESS and V$INSTANCE.
REM
REM USAGE
REM =====
REM $ sqlplus "/ as sysdba" @MEMORY
REM
REM INSTRUCTIONS
REM ============
REM Call MEMORY.sql from SQL*Plus, connected as any DBA user.
REM Press whenever you want to refresh information.
REM You can change the ordered column and the statistics shown by choosing from the menu.
REM Spool files named MEMORY_YYYYMMDD_HH24MISS.lst will be generated in the current directory.
REM Every time you refresh screen, a new spool file is created, with a snapshot of the statistics shown.
REM These snapshot files may be uploaded to Oracle Support Services for future reference, if needed.
REM
REM REFERENCES
REM ==========
REM "Oracle Reference" - Online Documentation
REM
REM SAMPLE OUTPUT
REM =============
REM :::::::::::::::::::::::::::::::::: PROGRAM GLOBAL AREA statistics :::::::::::::::::::::::::::::::::
REM
REM SESSION PID/THREAD CURRENT SIZE MAXIMUM SIZE
REM -------------------------------------------------- ---------- ------------------ ------------------
REM 9 - SYS: myworkstation 2258 10.59 MB 10.59 MB
REM 3 - LGWR: testserver 2246 5.71 MB 5.71 MB
REM 2 - DBW0: testserver 2244 2.67 MB 2.67 MB
REM ...
REM
REM :::::::::::::::::::::::::::::::::::: USER GLOBAL AREA statistics ::::::::::::::::::::::::::::::::::
REM
REM SESSION PID/THREAD CURRENT SIZE MAXIMUM SIZE
REM -------------------------------------------------- ---------- ------------------ ------------------
REM 9 - SYS: myworkstation 2258 0.29 MB 0.30 MB
REM 5 - SMON: testserver 2250 0.06 MB 0.06 MB
REM 4 - CKPT: testserver 2248 0.05 MB 0.05 MB
REM ...
REM
REM SCRIPT BODY
REM ===========


spool MEMORY_YYYYMMDD_HH24MISS.log

REM Starting script execution
CLE SCR
PROMPT .
PROMPT . ======== SCRIPT TO MONITOR MEMORY USAGE BY DATABASE SESSIONS ========
PROMPT .

REM Setting environment variables
SET LINESIZE 200
SET PAGESIZE 500
SET FEEDBACK OFF
SET VERIFY OFF
SET SERVEROUTPUT ON
SET TRIMSPOOL ON
COL "SESSION" FORMAT A50
COL "PID/THREAD" FORMAT A10
COL " CURRENT SIZE" FORMAT A18
COL " MAXIMUM SIZE" FORMAT A18

REM Setting user variables values
SET TERMOUT OFF
DEFINE sort_order = 3
DEFINE show_pga = 'ON'
DEFINE show_uga = 'ON'
COL sort_column NEW_VALUE sort_order
COL pga_column NEW_VALUE show_pga
COL uga_column NEW_VALUE show_uga
COL snap_column NEW_VALUE snap_time
SELECT nvl(:sort_choice, 3) "SORT_COLUMN"
FROM dual
/
SELECT nvl(:pga_choice, 'ON') "PGA_COLUMN"
FROM dual
/
SELECT nvl(:uga_choice, 'ON') "UGA_COLUMN"
FROM dual
/
SELECT to_char(sysdate, 'YYYYMMDD_HH24MISS') "SNAP_COLUMN"
FROM dual
/

REM Creating new snapshot spool file
SPOOL MEMORY_&snap_time

REM Showing PGA statistics for each session and background process
SET TERMOUT &show_pga
PROMPT
PROMPT :::::::::::::::::::::::::::::::::: PROGRAM GLOBAL AREA statistics :::::::::::::::::::::::::::::::::
SELECT to_char(ssn.sid, '9999') || ' - ' || nvl(ssn.username, nvl(bgp.name, 'background')) ||
nvl(lower(ssn.machine), ins.host_name) "SESSION",
to_char(prc.spid, '999999999') "PID/THREAD",
to_char((se1.value/1024)/1024, '999G999G990D00') || ' MB' " CURRENT SIZE",
to_char((se2.value/1024)/1024, '999G999G990D00') || ' MB' " MAXIMUM SIZE"
FROM v$sesstat se1, v$sesstat se2, v$session ssn, v$bgprocess bgp, v$process prc,
v$instance ins, v$statname stat1, v$statname stat2
WHERE se1.statistic# = stat1.statistic# and stat1.name = 'session pga memory'
AND se2.statistic# = stat2.statistic# and stat2.name = 'session pga memory max'
AND se1.sid = ssn.sid
AND se2.sid = ssn.sid
AND ssn.paddr = bgp.paddr (+)
AND ssn.paddr = prc.addr (+)
ORDER BY &sort_order DESC
/

REM Showing UGA statistics for each session and background process
SET TERMOUT &show_uga
PROMPT
PROMPT :::::::::::::::::::::::::::::::::::: USER GLOBAL AREA statistics ::::::::::::::::::::::::::::::::::
SELECT to_char(ssn.sid, '9999') || ' - ' || nvl(ssn.username, nvl(bgp.name, 'background')) ||
nvl(lower(ssn.machine), ins.host_name) "SESSION",
to_char(prc.spid, '999999999') "PID/THREAD",
to_char((se1.value/1024)/1024, '999G999G990D00') || ' MB' " CURRENT SIZE",
to_char((se2.value/1024)/1024, '999G999G990D00') || ' MB' " MAXIMUM SIZE"
FROM v$sesstat se1, v$sesstat se2, v$session ssn, v$bgprocess bgp, v$process prc,
v$instance ins, v$statname stat1, v$statname stat2
WHERE se1.statistic# = stat1.statistic# and stat1.name = 'session uga memory'
AND se2.statistic# = stat2.statistic# and stat2.name = 'session uga memory max'
AND se1.sid = ssn.sid
AND se2.sid = ssn.sid
AND ssn.paddr = bgp.paddr (+)
AND ssn.paddr = prc.addr (+)
ORDER BY &sort_order DESC
/

REM Showing sort information
SET TERMOUT ON
PROMPT
BEGIN
IF (&sort_order = 1) THEN
dbms_output.put_line('Ordered by SESSION');
ELSIF (&sort_order = 2) THEN
dbms_output.put_line('Ordered by PID/THREAD');
ELSIF (&sort_order = 3) THEN
dbms_output.put_line('Ordered by CURRENT SIZE');
ELSIF (&sort_order = 4) THEN
dbms_output.put_line('Ordered by MAXIMUM SIZE');
END IF;
END;
/

REM Closing current snapshot spool file
SPOOL OFF

REM Showing the menu and getting sort order and information viewing choice
PROMPT
PROMPT Choose the column you want to sort: == OR == You can choose which information to see:
PROMPT ... 1. Order by SESSION ... 5. PGA and UGA statistics (default)
PROMPT ... 2. Order by PID/THREAD ... 6. PGA statistics only
PROMPT ... 3. Order by CURRENT SIZE (default) ... 7. UGA statistics only
PROMPT ... 4. Order by MAXIMUM SIZE
PROMPT
ACCEPT choice NUMBER PROMPT 'Enter the number of your choice or press to refresh information: '
VAR sort_choice NUMBER
VAR pga_choice CHAR(3)
VAR uga_choice CHAR(3)
BEGIN
IF (&choice = 1 OR &choice = 2 OR &choice = 3 OR &choice = 4) THEN
:sort_choice := &choice;
:pga_choice := '&show_pga';
:uga_choice := '&show_uga';
ELSIF (&choice = 5) THEN
:sort_choice := &sort_order;
:pga_choice := 'ON';
:uga_choice := 'ON';
ELSIF (&choice = 6) THEN
:sort_choice := &sort_order;
:pga_choice := 'ON';
:uga_choice := 'OFF';
ELSIF (&choice = 7) THEN
:sort_choice := &sort_order;
:pga_choice := 'OFF';
:uga_choice := 'ON';
ELSE
:sort_choice := &sort_order;
:pga_choice := '&show_pga';
:uga_choice := '&show_uga';
END IF;
END;
/

REM Finishing script execution
PROMPT Type "@MEMORY" and press
SET FEEDBACK ON
SET VERIFY ON
SET SERVEROUTPUT OFF
SET TRIMSPOOL OFF

spool off

REM =============
REM END OF SCRIPT
REM =============

Database Health Monitoring Scripts in Oracle.

#################################################################################
---------------------- Database health Monitor ---------------------------------
#################################################################################

break on today
column today noprint new_value tdate
select substr(to_char(sysdate,'fmMonth DD, YYYY HH:MI:SS P.M.'),1,35) today from dual;
column name noprint new_value DB
select name from v$database;

set heading on
set feedback off

spool health.lst
--spool Windows Path or Unix Path\health.lst

prompt **********************************************************
prompt ***** Database Information *****
prompt **********************************************************
ttitle left "DATABASE: "DB" (AS OF: "tdate")"
select name, created, log_mode from v$database;
prompt
prompt **********************************************************
ttitle off

rem -------------------------------------------------------------
rem DB Block Buffer - Hit Ratio
rem -------------------------------------------------------------

clear breaks
clear computes

set heading off
set feedback off
set termout off

create table dbbb (
PR number,
CG number,
dbbg number);

insert into DBBB values (0,0,0);
UPDATE dbbb
set dbbg =
(SELECT VALUE FROM V$SYSSTAT WHERE NAME = 'db block gets');
UPDATE dbbb
set cg =
(SELECT VALUE FROM V$SYSSTAT WHERE NAME = 'consistent gets');
UPDATE dbbb
set pr =
(SELECT VALUE FROM V$SYSSTAT WHERE NAME = 'physical reads');

set heading on
set termout on

column "Physical Reads" format 99,999,999,999
column "Consistent Gets" format 99,999,999,999
column "DB Block Gets" format 99,999,999,999
column "Percent (Above 70% ?)" format 999.99

TTitle left "***** Database: "db", DB Block Buffers ( As of: "tdate" ) *****" skip 1 - left "Percent = (100*(1-(Physical Reads/(Consistent Gets + DB Block Gets))))" skip 2
SELECT pr "Physical Reads",
cg "Consistent Gets",
dbbg "DB Block Gets",
(100*(1-(PR/(CG+dbbg)))) "Percent (Above 70% ?)"
from dbbb;

set heading off
set termout off
drop table dbbb;
ttitle off
clear breaks
clear computes
set heading on
set termout on

rem -------------------------------------------------------------
rem Shared Pool Size - Gets and Misses
rem -------------------------------------------------------------

set line 150

column "Executions" format 999,999,990
column "Cache Misses Executing" format 999,999,990
column "Data Dictionary Gets" format 999,999,999
column "Get Misses" format 999,999,999

ttitle left skip 1 - left "********** Shared Pool Size (Execution Misses) **********" skip 1

select sum(pins) "Executions",
sum(reloads) "Cache Misses Executing",
(sum(reloads)/sum(pins)*100) "% Ratio (STAY UNDER 1%)"
from v$librarycache;

ttitle left "********** Shared Pool Size (Dictionary Gets) **********" skip 1

select sum(gets) "Data Dictionary Gets",
sum(getmisses) "Get Misses",
100*(sum(getmisses)/sum(gets)) "% Ratio (STAY UNDER 12%)"
from v$rowcache;

ttitle off


rem -------------------------------------------------------------
rem Log Buffer
rem -------------------------------------------------------------

ttitle left "********** Log Buffers **********" skip 1

select substr(name,1,25) Name,
substr(value,1,15) "VALUE (Near 0?)"
from v$sysstat
where name = 'redo log space requests';

ttitle off


rem -------------------------------------------------------------
rem Latch Contention
rem -------------------------------------------------------------

ttitle left "********** Latch Information **********" skip 1

select substr(l.name,1,25) Name,
l.gets, l.misses,
l.immediate_gets, l.immediate_misses
from v$latch l, v$latchname ln
where ln.name in ('redo allocation', 'redo copy')
and ln.latch# = l.latch#;

ttitle off


rem -------------------------------------------------------------
rem Reinstates the xdbname parameter
rem -------------------------------------------------------------

column name noprint new_value xdbname
select name from v$database;


rem -------------------------------------------------------------
rem Tablespace Usage
rem -------------------------------------------------------------

set pagesize 66
set line 132

clear breaks
clear computes

column "Total Bytes" format 9,999,999,999
column "SQL Blocks" format 999,999,999
column "VMS Blocks" format 999,999,999
column "Bytes Free" format 9,999,999,999
column "Bytes Used" format 9,999,999,999
column "% Free" format 9999.999
column "% Used" format 9999.999
break on report
compute sum of "Total Bytes" on report
compute sum of "SQL Blocks" on report
compute sum of "VMS Blocks" on report
compute sum of "Bytes Free" on report
compute sum of "Bytes Used" on report
compute avg of "% Free" on report
compute avg of "% Used" on report

TTitle left "******* Database: "db", Current Tablespace Usage ( As of: "tdate" ) *******" skip 1

select substr(fs.FILE_ID,1,3) "ID#",
fs.tablespace_name,
df.bytes "Total Bytes",
df.blocks "SQL Blocks",
df.bytes/512 "VMS Blocks",
sum(fs.bytes) "Bytes Free",
(100*((sum(fs.bytes))/df.bytes)) "% Free",
df.bytes-sum(fs.bytes) "Bytes Used",
(100*((df.bytes-sum(fs.bytes))/df.bytes)) "% Used"
from sys.dba_data_files df, sys.dba_free_space fs
where df.file_id(+) = fs.file_id
group by fs.FILE_ID, fs.tablespace_name, df.bytes, df.blocks
order by fs.tablespace_name;

ttitle off

rem -------------------------------------------------------------
rem Disk Activity
rem -------------------------------------------------------------

column "File Total" format 99,999,990

set line 132
set pagesize 33

ttitle " ***** Database: "db", DataFile's Disk Activity (As of:" tdate " ) *****"

select substr(df.file#,1,2) "ID",
rpad(substr(name,1,52),52,'.') "File Name",
rpad(substr(phyrds,1,10),10,'.') "Phy Reads",
rpad(substr(phywrts,1,10),10,'.') "Phy Writes",
rpad(substr(phyblkrd,1,10),10,'.') "Blk Reads",
rpad(substr(phyblkwrt,1,10),10,'.') "Blk Writes",
rpad(substr(readtim,1,9),9,'.') "Read Time",
rpad(substr(writetim,1,10),10,'.') "Write Time",
(sum(phyrds+phywrts+phyblkrd+phyblkwrt+readtim)) "File Total"
from v$filestat fs, v$datafile df
where fs.file# = df.file#
group by df.file#, df.name, phyrds, phywrts, phyblkrd,
phyblkwrt, readtim, writetim
order by sum(phyrds+phywrts+phyblkrd+phyblkwrt+readtim) desc, df.name;

ttitle off


rem -------------------------------------------------------------
rem Fragmentation Need
rem -------------------------------------------------------------

set heading on
set termout on
set pagesize 66
set line 132

ttitle left " ***** Database: "db", DEFRAGMENTATION NEED, AS OF: " tdate " *****"

select substr(de.owner,1,8) "Owner",
substr(de.segment_type,1,8) "Seg Type",
substr(de.segment_name,1,35) "Table Name (Segment)",
substr(de.tablespace_name,1,20) "Tablespace Name",
count(*) "Frag NEED",
substr(df.name,1,40) "DataFile Name"
from sys.dba_extents de, v$datafile df
where de.owner <> 'SYS'
and de.file_id = df.file#
and de.segment_type = 'TABLE'
group by de.owner, de.segment_name, de.segment_type, de.tablespace_name,
df.name
having count(*) > 1
order by count(*) desc;

ttitle off


rem -------------------------------------------------------------
rem Rollback Information
rem -------------------------------------------------------------

set pagesize 66
set line 132

TTitle left "*** Database: "db", Rollback Information ( As of: " tdate " ) ***" skip 2

select substr(sys.dba_rollback_segs.SEGMENT_ID,1,5) "ID#",
substr(sys.dba_segments.OWNER,1,8) "Owner",
substr(sys.dba_segments.TABLESPACE_NAME,1,17) "Tablespace Name",
substr(sys.dba_segments.SEGMENT_NAME,1,17) "Rollback Name",
substr(sys.dba_rollback_segs.INITIAL_EXTENT,1,10) "INI_Extent",
substr(sys.dba_rollback_segs.NEXT_EXTENT,1,10) "Next Exts",
substr(sys.dba_segments.MIN_EXTENTS,1,5) "MinEx",
substr(sys.dba_segments.MAX_EXTENTS,1,5) "MaxEx",
substr(sys.dba_segments.PCT_INCREASE,1,5) "%Incr",
substr(sys.dba_segments.BYTES,1,15) "Size (Bytes)",
substr(sys.dba_segments.EXTENTS,1,6) "Extent#",
substr(sys.dba_rollback_segs.STATUS,1,10) "Status"
from sys.dba_segments, sys.dba_rollback_segs
where sys.dba_segments.segment_name = sys.dba_rollback_segs.segment_name and
sys.dba_segments.segment_type = 'ROLLBACK'
order by sys.dba_rollback_segs.segment_id;

ttitle off

TTitle left " " skip 2 - left "*** Database: "db", Rollback Status ( As of: " tdate " ) ***" skip 2

select substr(V$rollname.NAME,1,20) "Rollback_Name",
substr(V$rollstat.EXTENTS,1,6) "EXTENT",
v$rollstat.RSSIZE, v$rollstat.WRITES,
substr(v$rollstat.XACTS,1,6) "XACTS",
v$rollstat.GETS,
substr(v$rollstat.WAITS,1,6) "WAITS",
v$rollstat.HWMSIZE, v$rollstat.SHRINKS,
substr(v$rollstat.WRAPS,1,6) "WRAPS",
substr(v$rollstat.EXTENDS,1,6) "EXTEND",
v$rollstat.AVESHRINK,
v$rollstat.AVEACTIVE
from v$rollname, v$rollstat
where v$rollname.USN = v$rollstat.USN
order by v$rollname.USN;

ttitle off

TTitle left " " skip 2 - left "*** Database: "db", Rollback Segment Mapping ( As of: " tdate " ) ***" skip 2

select r.name Rollback_Name,
p.pid Oracle_PID,
p.spid VMS_PID,
nvl(p.username,'NO TRANSACTION') Transaction,
p.terminal Terminal
from v$lock l, v$process p, v$rollname r
where l.addr = p.addr(+)
and trunc(l.id1(+)/65536)=r.usn
and l.type(+) = 'TX'
and l.lmode(+) = 6
order by r.name;

ttitle off


rem -------------------------------------------------------------
rem Current Users
rem -------------------------------------------------------------

set line 132
set pagesize 66

TTitle left "*** Database: "db", Current User Info (As of: "tdate") ***" skip 1

select substr(s.username,1,15) "DB UserName",
s.osuser "OS UserName",
substr(a.object,1,25) Object,
a.type , s.command,
substr(s.machine,1,15) Machine,
substr(s.terminal,1,15) Terminal, s.process, s.status
from v$access a, v$session s
where a.sid = s.sid
order by username;

TTitle left "*** Database: "db", Current Sessions (As of: "tdate") ***" skip 1

select substr(username,1,15) "DB UserName",
substr(osuser,1,15) "OS UserName",
substr(command,1,3) CMD,
substr(machine,1,10) Machine,
terminal, process, status,
substr(program,1,50) "OS Program Name"
from v$session
where type = 'USER'
order by username;

TTitle left "*** Database: "db", Current Access (As of: "tdate") ***" skip 1

select sid,
substr(owner,1,15) Owner,
substr(object,1,25) Object,
type
from v$access
order by owner;


rem -------------------------------------------------------------
rem -------------------------------------------------------------

spool off
set feedback on
Powered by Blogger