oracle concepts

30
Oracle Concepts - Oracle shutdown commands Oracle Tips by Burleson Consulting Oracle shutdown command Concepts You might take the database down to make configuration changes, for a backup or to upgrade Oracle software. When it’s time to bring your database down, we use the shutdown command. As you might guess, the shutdown command comes in many forms. Oracle has three shutdown modes: * Normal (default) - waits for in-flight work to complete * Immediate - terminates all sessions and does a rollback on all uncommitted transactions * Abort - aborts all sessions, leaving current DML in need of rollback, de-allocates the SGA and terminates the background processes. The "normal" and "immediate" modes can take a long time in you have in-flight transactions, and many Oracle DBA's ensure a swift clean shutdown this way, aborting the sessions, re-starting to allow warmstart rollback of the aborted transactions, and a shutdown immediate to close cleanly: SQL> shutdown abort SQL> startup SQL> shutdown immediate Oracle Normal Shutdown A normal shutdown of an Oracle database is actually rarely used. This is because the normal shutdown waits for everyone to

Upload: spudbunny1

Post on 06-Mar-2015

84 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Oracle Concepts

Oracle Concepts - Oracle shutdown commandsOracle Tips by Burleson Consulting

Oracle shutdown command Concepts

You might take the database down to make configuration changes, for a backup or to upgrade Oracle software. When it’s time to bring your database down, we use the shutdown command.

As you might guess, the shutdown command comes in many forms.  Oracle has three shutdown modes:

* Normal (default) - waits for in-flight work to complete

* Immediate - terminates all sessions and does a rollback on all

uncommitted transactions

* Abort - aborts all sessions, leaving current DML in need of rollback, de-allocates the SGA and terminates the background processes.

The "normal" and "immediate" modes can take a long time in you have in-flight transactions, and many Oracle DBA's ensure a swift clean shutdown this way, aborting the sessions, re-starting to allow warmstart rollback of the aborted transactions, and a shutdown immediate to close cleanly:

SQL> shutdown abort

SQL> startup

SQL> shutdown immediate

Oracle Normal Shutdown

A normal shutdown of an Oracle database is actually rarely used. This is because the normal shutdown waits for everyone to complete their work and then logoff in an orderly fashion. When a normal shutdown occurs, the database is closed in a normal manner, and all changes made in the database are flushed to the database datafiles.  This is known as a “clean shutdown”.

Most of the time this is not practical… there always seems to be someone who has left for vacation and who forgot to log out, or there are times that Oracle processes become “zombied” (this is where Oracle thinks someone is connected to the database but they really are not). In these cases, the database will never come down.

Page 2: Oracle Concepts

It will simply wait forever until you manually kill those sessions. Because of this, we often recommend the shutdown immediate or shutdown abort commands, which we will discuss in the next sections. Here is an example of the use of the normal shutdown command.

SQL> shutdown

When you execute a shutdown, Oracle will flush all the changes in memory out to the database datafiles. This makes database startup quicker because the database is in a consistent state.

Think of it this way: if you jump into the air and land on your feet, you have landed in a way that prepares you to make another jump.  If, instead, you jump and land on your back, you are in no position to make another jump; instead, you must perform a recovery by taking the actions required to stand again.  A clean shutdown is one that is prepared to come back up without delay.  A dirty shutdown is one that lands on its back; it can not come back up without first recovering itself.

Oracle Shutdown Immediate

Perhaps the best way to initially shutdown the database is the shutdown immediate command. This command will prevent any new logins, then rollback any uncommitted transactions, and then bring down the database. In the process of bringing down the database, Oracle will flush all the changes in memory out to the database datafiles too, just like a regular shutdown does. This makes database startup quicker. Here is an example of shutting down a database with the shutdown immediate command:

SQL> shutdown immediate

The shutdown immediate command will work most of the time, but there are times when it can hang and fail to shutdown the database. In these cases, the shutdown abort command is called for.

Oracle Shutdown Abort Command

The shutdown abort command is pretty much a guaranteed way to get your database to shutdown. It’s a “hard crash” of the database, and this can result in a longer time to start the database back up. Still, you can’t really hurt the database using the shutdown abort command, and during your DBA years you will find more than a few occasions to use the shutdown abort command.

A shutdown abort should not be your first shutdown method of choice, there may be times when you must force the database down. Here is an example using the shutdown abort command:

SQL> shutdown abort

Next, let’s change topics and examine the Oracle data dictionary where information about our database resides.

Page 3: Oracle Concepts

How does one create a new database?

One can create and modify Oracle databases using the Oracle DBCA (Database

Configuration Assistant) utility. The dbca utility is located in the

$ORACLE_HOME/bin directory. The Oracle Universal Installer (oui) normally starts

it after installing the database server software to create the starter database.

One can also create databases manually using scripts. This option, however, is

falling out of fashion as it is quite involved and error prone. Look at this example for

creating an Oracle 9i or higher database:

CONNECT SYS AS SYSDBAALTER SYSTEM SET DB_CREATE_FILE_DEST='/u01/oradata/';ALTER SYSTEM SET DB_CREATE_ONLINE_LOG_DEST_1='/u02/oradata/';ALTER SYSTEM SET DB_CREATE_ONLINE_LOG_DEST_2='/u03/oradata/';CREATE DATABASE;

Also see Creating a New Database.

[edit] What database block size should I use?

Oracle recommends that your database block size match, or be multiples of your

operating system block size. One can use smaller block sizes, but the performance

cost is significant. Your choice should depend on the type of application you are

running. If you have many small transactions as with OLTP, use a smaller block

size. With fewer but larger transactions, as with a DSS application, use a larger

block size.

If you are using a volume manager, consider your "operating system block size" to

be 8K. This is because volume manager products use 8K blocks (and this is not

configurable).

[edit] What database aspects should be monitored?

One should implement a monitoring system to constantly monitor the following

aspects of a database. This can be achieved by writing custom scripts,

implementing Oracle's Enterprise Manager, or buying a third-party monitoring

product. If an alarm is triggered, the system should automatically notify the DBA (e-

mail, text, etc.) to take appropriate action.

Infrastructure availability:

Page 4: Oracle Concepts

← Is the database up and responding to requests

← Are the listeners up and responding to requests

← Are the Oracle Names and LDAP Servers up and responding to requests

← Are the Application Servers up and responding to requests

← Etc.

Things that can cause service outages:

← Is the archive log destination filling up?

← Objects getting close to their max extents

← Tablespaces running low on free space / Objects that would not be able to

extend

← User and process limits reached

← Etc.

[edit] How does one rename a database?

Follow these steps to rename a database:

← Start by making a full database backup of your database (in case you need to

restore if this procedure is not working).

← Execute this command from sqlplus while connected to 'SYS AS SYSDBA':

ALTER DATABASE BACKUP CONTROLFILE TO TRACE RESETLOGS;

← Locate the latest dump file in your USER_DUMP_DEST directory (show

parameter USER_DUMP_DEST) - rename it to something like dbrename.sql.

← Edit dbrename.sql, remove all headers and comments, and change the

database's name. Also change "CREATE CONTROLFILE REUSE ..." to

"CREATE CONTROLFILE SET ...".

Page 5: Oracle Concepts

← Shutdown the database (use SHUTDOWN NORMAL or IMMEDIATE, don't

ABORT!) and run dbrename.sql.

← Rename the database's global name:

ALTER DATABASE RENAME GLOBAL_NAME TO new_db_name;

[edit] Can one rename a database user (schema)?

No, this is listed as Enhancement Request 158508. Workaround:

← Do a user-level export of user A

← create new user B

← import system/manager fromuser=A touser=B

← drop user A

[edit] Can one rename a tablespace?

From Oracle 10g Release 1, users can rename tablespaces. Example:

ALTER TABLESPACE ts1 RENAME TO ts2;

However, you must adhere to the following restrictions:

← COMPATIBILITY must be set to at least 10.0.1

← Cannot rename SYSTEM or SYSAUX

← Cannot rename an offline tablespace

← Cannot rename a tablespace that contains offline datafiles

For older releases, use the following workaround:

← Export all of the objects from the tablespace

← Drop the tablespace including contents

← Recreate the tablespace

Page 6: Oracle Concepts

← Import the objects

[edit] How does one see the uptime for a database?

Look at the following SQL query:

SELECT to_char(startup_time,'DD-MON-YYYY HH24:MI:SS') "DB Startup Time"FROM sys.v_$instance;

[edit] Can one resize tablespaces and data files?

Add more files to tablespaces

To add more space to a tablespace, one can simply add another file to it. Example:

ALTER TABLESPACE USERS ADD DATAFILE '/oradata/orcl/users1.dbf' SIZE 100M;

Resize datafiles

One can manually increase or decrease the size of a datafile from Oracle 7.2 using

the following command:

ALTER DATABASE DATAFILE 'filename2' RESIZE 100M;

Because you can change the sizes of datafiles, you can add more space to your

database without adding more datafiles. This is beneficial if you are concerned

about reaching the maximum number of datafiles allowed in your database.

Manually reducing the sizes of datafiles allows you to reclaim unused space in the

database. This is useful for correcting errors in estimations of space requirements.

Extend datafiles

Also, datafiles can be allowed to automatically extend if more space is required.

Look at the following commands:

CREATE TABLESPACE pcs_data_ts DATAFILE 'c:ora_appspcspcsdata1.dbf' SIZE 3M AUTOEXTEND ON NEXT 1M MAXSIZE UNLIMITED DEFAULT STORAGE ( INITIAL 10240 NEXT 10240 MINEXTENTS 1

Page 7: Oracle Concepts

MAXEXTENTS UNLIMITED PCTINCREASE 0) ONLINE PERMANENT;ALTER DATABASE DATAFILE 1 AUTOEXTEND ON NEXT 1M MAXSIZE UNLIMITED;

[edit] How do I find the overall database size?

The biggest portion of a database's size comes from the datafiles. To find out how

many megabytes are allocated to ALL datafiles:

select sum(bytes)/1024/1024 "Meg" from dba_data_files;

To get the size of all TEMP files:

select nvl(sum(bytes),0)/1024/1024 "Meg" from dba_temp_files;

To get the size of the on-line redo-logs:

select sum(bytes)/1024/1024 "Meg" from sys.v_$log;

Putting it all together into a single query:

select a.data_size+b.temp_size+c.redo_size "total_size"from ( select sum(bytes) data_size from dba_data_files ) a, ( select nvl(sum(bytes),0) temp_size from dba_temp_files ) b, ( select sum(bytes) redo_size from sys.v_$log ) c;

Another query ("Free space" reports data files free space):

col "Database Size" format a20 col "Free space" format a20 select round(sum(used.bytes) / 1024 / 1024 ) || ' MB' "Database Size" , round(free.p / 1024 / 1024) || ' MB' "Free space" from (select bytes from v$datafile union all select bytes from v$tempfile union all

Page 8: Oracle Concepts

select bytes from v$log) used , (select sum(bytes) as p from dba_free_space) free group by free.p /

[edit] How do I find the used space within the database size?

Select from the DBA_SEGMENTS or DBA_EXTENTS views to find the used space

of a database. Example:

SELECT SUM(bytes)/1024/1024 "Meg" FROM dba_segments;

[edit] Where can one find the high water mark for a table?

There is no single system table which contains the high water mark (HWM) for a

table. A table's HWM can be calculated using the results from the following SQL

statements:

SELECT BLOCKSFROM DBA_SEGMENTSWHERE OWNER=UPPER(owner) AND SEGMENT_NAME = UPPER(table);

ANALYZE TABLE owner.table ESTIMATE STATISTICS;

SELECT EMPTY_BLOCKSFROM DBA_TABLESWHERE OWNER=UPPER(owner) AND TABLE_NAME = UPPER(table);

Thus, the tables' HWM = (query result 1) - (query result 2) - 1

NOTE: You can also use the DBMS_SPACE package and calculate the HWM =

TOTAL_BLOCKS - UNUSED_BLOCKS - 1.

[edit] How do I find used/free space in a TEMPORARY tablespace?

Unlike normal tablespaces, true temporary tablespace information is not listed in

DBA_FREE_SPACE. Instead use the V$TEMP_SPACE_HEADER view:

Page 9: Oracle Concepts

SELECT tablespace_name, SUM(bytes_used), SUM(bytes_free)FROM V$temp_space_headerGROUP BY tablespace_name;

To report true free space within the used portion of the TEMPFILE:

SELECT A.tablespace_name tablespace, D.mb_total, SUM (A.used_blocks * D.block_size) / 1024 / 1024 mb_used, D.mb_total - SUM (A.used_blocks * D.block_size) / 1024 / 1024 mb_freeFROM v$sort_segment A, ( SELECT B.name, C.block_size, SUM (C.bytes) / 1024 / 1024 mb_total FROM v$tablespace B, v$tempfile C WHERE B.ts#= C.ts# GROUP BY B.name, C.block_size ) DWHERE A.tablespace_name = D.nameGROUP by A.tablespace_name, D.mb_total;

[edit] How can one see who is using a temporary segment?

For every user using temporary space, there is an entry in SYS.V_$LOCK with type

'TS'.

All temporary segments are named 'ffff.bbbb' where 'ffff' is the file it is in and 'bbbb'

is first block of the segment.

If your temporary tablespace is set to TEMPORARY, all sorts are done in one large

temporary segment. For usage stats, see SYS.V_$SORT_SEGMENT

From Oracle 8, one can just query SYS.v$sort_usage. Look at these examples:

select s.username, u."USER", u.tablespace, u.contents, u.extents, u.blocksfrom sys.v_$session s, sys.v_$sort_usage uwhere s.saddr = u.session_addr/

select s.osuser, s.process, s.username, s.serial#, sum(u.blocks)*vp.value/1024 sort_sizefrom sys.v_$session s, sys.v_$sort_usage u, sys.v_$parameter vpwhere s.saddr = u.session_addr and vp.name = 'db_block_size'

Page 10: Oracle Concepts

and s.osuser like '&1'group by s.osuser, s.process, s.username, s.serial#, vp.value/

[edit] Who is using which UNDO or TEMP segment?

Execute the following query to determine who is using a particular UNDO or

Rollback Segment:

SQL> SELECT TO_CHAR(s.sid)||','||TO_CHAR(s.serial#) sid_serial, 2 NVL(s.username, 'None') orauser, 3 s.program, 4 r.name undoseg, 5 t.used_ublk * TO_NUMBER(x.value)/1024||'K' "Undo" 6 FROM sys.v_$rollname r, 7 sys.v_$session s, 8 sys.v_$transaction t, 9 sys.v_$parameter x 10 WHERE s.taddr = t.addr 11 AND r.usn = t.xidusn(+) 12 AND x.name = 'db_block_size'

SID_SERIAL ORAUSER PROGRAM UNDOSEG Undo---------- ---------- ------------------------------ --------------- -------260,7 SCOTT [email protected] _SYSSMU4$ 8K (TNS V1-V3)

Execute the following query to determine who is using a TEMP Segment:

SQL> SELECT b.tablespace, 2 ROUND(((b.blocks*p.value)/1024/1024),2)||'M' "SIZE", 3 a.sid||','||a.serial# SID_SERIAL, 4 a.username, 5 a.program 6 FROM sys.v_$session a, 7 sys.v_$sort_usage b, 8 sys.v_$parameter p 9 WHERE p.name = 'db_block_size' 10 AND a.saddr = b.session_addr 11 ORDER BY b.tablespace, b.blocks;

TABLESPACE SIZE SID_SERIAL USERNAME PROGRAM---------- ------- ---------- -------- ------------------------------TEMP 24M 260,7 SCOTT [email protected]

Page 11: Oracle Concepts

(TNS V1-V3)

[edit] How does one get the view definition of fixed views/tables?

Query v$fixed_view_definition. Example:

SELECT * FROM v$fixed_view_definition WHERE view_name='V$SESSION';

[edit] How full is the current redo log file?

Here is a query that can tell you how full the current redo log file is. Handy for when

you need to predict when the next log file will be archived out.

SQL> SELECT le.leseq "Current log sequence No", 2 100*cp.cpodr_bno/le.lesiz "Percent Full", 3 cp.cpodr_bno "Current Block No", 4 le.lesiz "Size of Log in Blocks" 5 FROM x$kcccp cp, x$kccle le 6 WHERE le.leseq =CP.cpodr_seq 7 AND bitand(le.leflg,24) = 8 8 /Current log sequence No Percent Full Current Block No Size of Log in Blocks----------------------- ------------ ---------------- --------------------- 416 48.6669922 49835 102400

[edit] Tired of typing sqlplus '/as sysdba' every time you want to do something?

If you are tired of typing sqlplus "/as sysdba" every time you want to perform some

DBA task, implement the following shortcut:

On Unix/Linux systems:

Add the following alias to your .profile or .bash_profile file:

alias sss='sqlplus "/as sysdba"'

On Windows systems:

Page 12: Oracle Concepts

Create a batch file, sss.bat, add the command to it, and place it somewhere in your

PATH. Whenever you now want to start sqlplus as sysdba, just type "sss". Much

less typing for ya lazy DBA's.

Note: From Oracle 10g you don't need to put the "/AS SYSDBA" in quotes anymore.

[edit] What patches are installed within an Oracle Home?

DBA's often do not document the patches they install. This may lead to situations

where a feature works on machine X, but not on machine Y. This FAQ will show how

you can list and compare the patches installed within your Oracle Homes.

All patches that are installed with Oracle's OPatch Utility (Oracle's Interim Patch

Installer) can be listed by invoking the opatch command with the lsinventory option.

Here is an example:

$ cd $ORACLE_HOME/OPatch

$ opatch lsinventoryInvoking OPatch 10.2.0.1.0

Oracle interim Patch Installer version 10.2.0.1.0Copyright (c) 2005, Oracle Corporation. All rights reserved.....Installed Top-level Products (1):

Oracle Database 10g 10.2.0.1.0There are 1 products installed in this Oracle Home.There are no Interim patches installed in this Oracle Home.

OPatch succeeded.

NOTE: If OPatch is not installed into your Oracle Home

($ORACLE_HOME/OPatch), you may need to download it from Metalink and install

it yourself.

[edit] How does one give developers access to trace files (required as input to tkprof)?

The alter session set sql_trace=true command generates trace files in

USER_DUMP_DEST that can be used by developers as input to tkprof. On Unix the

default file mask for these files are "rwx r-- ---".

Page 13: Oracle Concepts

There is an undocumented INIT.ORA parameter that will allow everyone to read

(rwx r-- r--) these trace files:

_trace_files_public = true

Include this in your INIT.ORA file and bounce your database for it to take effect.

The rules for identification of candidates for index coalescing/rebuilding depend on your specific index state. See MOSC notes 989186.1, 122008.1, 989093.1 for Oracle’s suggestions on when to coalesce/rebuild indexes. Also see my updated notes on index coalesce or rebuilding and note this demonstration of an index that benefits from scheduled oracle index rebuilding.

 Also, please see my updates and other notes on index rebuilding strategies, and my complete notes are found in my book "Oracle Tuning: The Definitive Reference".

Some people suggest that indexes require rebuilding when deleted leaf rows appear or when the index has a suboptimal number of block gets per access. While it is tempting to write a script that rebuilds every index in the schema, bear in mind that your schema may contain many thousands of indexes, and a complete rebuild can be very time consuming.

Hence, we need to develop a method to identify those indexes that will get improved performance with a rebuild. Let’s look at one method for accomplishing this task.

How rare are "bad" indexes? 

You cannot generalize to say that index rebuilding for performance is rare, or even medium rare, it depends on many factors, most importantly the characteristics of the application.

In scientific applications (clinical, laboratory) where large datasets are added and removed, the need to rebuild indexes is "common".

Conversely, in system that never update or delete rows, index rebuilding rarely improves performance.

Page 14: Oracle Concepts

In systems that do batch DML jobs, index rebuilding "often" improves SQL performance.

Oracle MOSC note 122008.1 has the officially authorized script to detect indexes that benefit from rebuilding. This script detects indexes for rebuilding using these rules: Rebuild the index when these conditions are true:

- deleted entries represent 20% or more of the current entries.- the index depth is more then 4 levels.

Oracle's index rebuilding guidelines appear in MOSC note 77574.1 (dated April 2007) recommends that indexes be periodically examined to see if they are candidates for an index rebuild:

“When an index is skewed, parts of an index are accessed more frequently than others. As a result, disk contention may occur, creating a bottleneck in performance.

It is important to periodically examine your indexes to determine if they have become skewed and might need to be rebuilt.”

Oracle index nodes are not physically deleted when table rows are deleted, nor are the entries removed from the index. Rather, Oracle "logically" deletes the index entry and leaves "dead" nodes in the index tree where that may be re-used if another adjacent entry is required.

However, when large numbers of adjacent rows are deleted, it is highly unlikely that Oracle will have an opportunity to re-use the deleted leaf rows, and these represent wasted space in the index. In addition to wasting space, large volumes of deleted leaf nodes will make index fast-full scans run for longer periods.

These deleted leaf nodes can be easily identified by running the IDL.SQL script.

The number of deleted leaf rows

The term "deleted leaf node" refers to the number of index inodes that have been logically deleted as a result of row deletes. Remember that Oracle leaves "dead" index nodes in the index when rows are deleted. This is done to speed up SQL deletes, since Oracle does not have to allocate resources to rebalance the index tree when rows are deleted.

Index height

Page 15: Oracle Concepts

The height of the index refers to the number of levels that are spawned by the index as a result in row inserts. When a large amount of rows are added to a table, Oracle may spawn additional levels of an index to accommodate the new rows.

Oracle indexes can support many millions of entries in three levels. Any Oracle index that has spawned to a 4th level followed by a large delete job might benefit from rebuilding to restore the index to it's pristine state.

Gets per index access

The number of "gets" per access refers to the amount of logical I/O that is required to fetch a row with the index. As you may know, a logical "get" is not necessarily a physical I/O since much of the index may reside in the Oracle buffer cache.

Unfortunately, Oracle does not make it easy to capture this information. In Oracle we must issue these commands to populate the statistics in dba_indexes and related dictionary tables:

ANALYZE INDEX index_name COMPUTE STATISTICSANALYZE INDEX index_name VALIDATE STRUCTURE

We might want to rebuild an index if the “block gets” per access is excessive. This happens when an index becomes "sparse" after high delete activity, making full-index scans requires unnecessary I/O. Another rebuild condition would be cases where deleted leaf nodes comprise more than 20% of the index nodes.

As you may know, you can easily rebuild an Oracle index with the command:

ALTER INDEX index_name REBUILD tablespace FLOP;

Done properly during scheduled downtime, rebuilding an index is 100% safe. Note the use of the tablespace option. When rebuilding multi-gigabyte indexes, many DBA's will rebuild partitioned indexes into a fresh, empty tablespace for greater manageability. ( I use the convention ts_ndexname_flip, and ts_indexname_flop)

Page 16: Oracle Concepts

The ALTER INDEX index_name REBUILD command is very safe way to rebuild indexes. Here is the syntax of the command:

alter index index_namerebuildtablespace tablespace_namestorage (initial new_initial next new_next freelists new_freelist_number )

Unlike the traditional method where we drop the index and recreate it, the REBUILD command does not require a full table scan of the table, and the subsequent sorting of the keys and rowids. Rather, the REBUILD command will perform the following steps:

1. Walk the existing index to get the index keys. 2. Populate temporary segments with the new tree structure. 3. Once the operation has completed successfully, drop the old tree, and rename the temporary

segments to the new index. As you can see from the steps, you can rebuild indexes without worrying that you will accidentally lose the index. If the index cannot be rebuilt for any reason, Oracle will abort the operation and leave the existing index intact. Only after the entire index has been rebuilt does Oracle transfer the index to the new b-tree.

Most Oracle administrators run this script, and then select the index that they would like to rebuild. Note that the TABLESPACE clause should always be used with the ALTER INDEX REBUILD command to ensure that the index is not rebuilt within the default tablespace (usually SYS).

Be aware that it's always a good idea to move an index into another tablespace and you must have enough room in that tablespace to hold all of the temporary segments required for the index rebuild, so most Oracle administrators will double-size index tablespaces with enough space for two full index trees.

Update:

When can we "prove" a benefit from an index rebuild?  Here, Robin Schumacher proves that an index that is rebuilt in a larger tablespace will contain more index entries be block, and have a flatter structure:

"As you can see, the amount of logical reads has been reduced in half simply by using the new 16K tablespace and accompanying 16K data cache."

In an OracleWorld 2003 presentation titled “Oracle Database 10g: The Self-Managing Database” by Sushil Kumar of Oracle Corporation, Kumar states that the new Automatic

Page 17: Oracle Concepts

Maintenance Tasks (AMT) Oracle10g feature will "automatically detect and re-build sub-optimal indexes.“

This Kim Floss article shows the Oracle 10g segment advisor recommending a rebuild of an index: 

“The page lists all the segments (table, index, and so on) that constitute the object under review. The default view ("View Segments Recommended to Shrink") lists any segments that have free space you can reclaim.”

Killing Runaway Oracle Processes on Windows with OraKill

by Jeff Hunter, Sr. Database Administrator

Contents

1. Overview 2. Shadow Processes in UNIX

3. Using OraKill

4. Why OraKill?

Overview

This article provides details on how to kill runaway Oracle processes in Microsoft Windows using the orakill.exe command-line utility. The OraKill utility is included with the Oracle database on all Windows platforms. It allows the DBA to kill an Oracle session directly from an MS-DOS command-line without requiring any login connection to the database.

Shadow Processes in UNIX

If you have ever worked with Oracle in a UNIX environment, you should already be familiar with killing an Oracle session (actually the Oracle shadow process) using the kill -9 command. Under the UNIX

Page 18: Oracle Concepts

operating environment, the shadow process is forked from the Oracle client application (i.e. sqlplus). You would use the UNIX ps command to list all processes you are interested in as in the following example:

% ps -ef | grep TARGDB

oracle 4407 1 0 19:23:25 ? 0:01 ora_smon_TARGDB oracle 4415 1 0 19:23:25 ? 0:00 ora_arc0_TARGDB oracle 4403 1 0 19:23:24 ? 0:02 ora_lgwr_TARGDB oracle 4405 1 0 19:23:25 ? 0:00 ora_ckpt_TARGDB oracle 4525 1 2 22:48:29 ? 0:00 oracleTARGDB (DESCRIPTION=(LOCAL=YES)(ADDRESS=(PROTOCOL=beq))) oracle 4439 1 0 19:31:50 ? 0:20 ora_qmn0_TARGDB oracle 4417 1 0 19:23:25 ? 0:00 ora_arc1_TARGDB oracle 4401 1 0 19:23:24 ? 0:00 ora_dbw0_TARGDB oracle 4409 1 0 19:23:25 ? 0:00 ora_reco_TARGDB oracle 4399 1 0 19:23:23 ? 0:02 ora_pmon_TARGDB oracle 4411 1 0 19:23:25 ? 0:00 ora_cjq0_TARGDB root 4419 1 0 19:23:26 ? 0:00 ora_dism_TARGDB

If I know that I have a runaway process (let's say process ID 4525), I could kill it from the UNIX command-line using the following:

% kill -9 4525

Unlike the UNIX operating environment, Microsoft Windows is completely thread-based. For each Oracle instance, all background processes and user sessions are contained within the the oracle.exe executable. These threads are not listed in the Processes tab under the Windows Task Manager application. Each user session will create its own thread within the running oracle.exe process and is not easily visible to the Windows DBA. If you were to try to kill the oracle.exe process, you would take down (crash) the entire Oracle instance.

As you will see in this article, the OraKill utility can be used much in the same way as kill -9 would be used in a UNIX environment.

Using OraKill

To get started, let's simply type in the OraKill utility at the command prompt:

Page 19: Oracle Concepts

C:\> orakill

Usage: orakill sid thread

where sid = the Oracle instance to target thread = the thread id of the thread to kill

The thread id should be retrieved from the spid column of a query such as:

select spid, osuser, s.program from v$process p, v$session s where p.addr=s.paddr

The OraKill utility requires two parameters:

Oracle Instance (SID) SPID of the thread to kill

Now, let's work through a simple example of how to kill an Oracle session using the OraKill utility. First, we take a look at several sessions:

SELECT a.username, a.osuser, b.spidFROM v$session a, v$process bWHERE a.paddr = b.addr AND a.username IS NOT null;

USERNAME OSUSER SPID---------------- ---------------------- ----OEM SYSTEM 2964OEM SYSTEM 3072OEM SYSTEM 3116OEM SYSTEM 3124OEM SYSTEM 3144OEM SYSTEM 3156OEM SYSTEM 3180OEM SYSTEM 3188OEM SYSTEM 3196OEM SYSTEM 3204OEM SYSTEM 3216SYS SYSTEM 3740SYSTEM MELODY\jhunter 1116SCOTT MELODY\jhunter 1384

Page 20: Oracle Concepts

14 rows selected.

Now that we have the user sessions (and their SPIDs) let's kill the SCOTT session using OraKill:

C:\> orakill JEFFDB 1384

Kill of thread id 1384 in instance JEFFDB successfully signalled.

When we go back to query all user sessions, we can see that the SCOTT user session has been killed:

SELECT a.username, a.osuser, b.spidFROM v$session a, v$process bWHERE a.paddr = b.addr AND a.username IS NOT null;

USERNAME OSUSER SPID---------------- ---------------------- ----OEM SYSTEM 2964OEM SYSTEM 3072OEM SYSTEM 3116OEM SYSTEM 3124OEM SYSTEM 3144OEM SYSTEM 3156OEM SYSTEM 3180OEM SYSTEM 3188OEM SYSTEM 3196OEM SYSTEM 3204OEM SYSTEM 3216SYS SYSTEM 3740SYSTEM MELODY\jhunter 1116

13 rows selected.

Page 21: Oracle Concepts

Why OraKill?

Why would Oracle provide a command-line utility to kill Oracle user sessions when the option already exists to kill sessions within Oracle. For example, we could have simply determined the SID and Serial# for the user session, logged into the database and used the following command:

SQL> alter system kill session SID, Serial#;

The DBA would be able to query the SID and Serial# for the user session from the v$session dynamic view. There are several reasons why the DBA would want to use OraKill from the command-line rather than using alter system kill session... command:

Clearing Locks - Using alter system kill session... will not clear any locks that may exist. Oracle will keep the session connected until the user session times out. It is only then that Oracle releases any locks. With OraKill, the thread will be killed and all locks held by that thread released.

Unable to Connect to Oracle - It may be that the DBA cannot gain access to the database to obtain the SID and Serial# for the user session. It may be because a runaway process is consuming all available resources (CPU, memory, I/O). With OraKill, if the DBA knows the SPID, they can simply kill the user session from the command-line. But how does the DBA find the SPID if he cannot log into the database. This is where another Microsoft Utility comes in handy -

QuickSlice.

As mentioned above, it may not be possible for the DBA to login to the database to obtain the SPID value for the user session. This is needed to kill the user session using OraKill. A free utility named QuickSlice can be used to look into the individual threads created by each process - namely the oracle.exe process. QuickSlice can be downloaded using the following link:

QuickSliceqslice_setup.exe

641 KB file3 min @ 28.8 Kbps

After downloading, installing and running the QuickSlice utility, you will have a screen similar to the following:

Page 22: Oracle Concepts

Let's now run through a quick example of how to use QuickSlice to find the SPID for a user session. We can start by creating a small runaway process. Type in the following anonymous PL/SQL block and run it:

beginloopnull;end loop;end;/

After kicking off the above code, we now have a runaway process. This can be seen in QuickSlice:

Page 23: Oracle Concepts

OK, we know that Oracle is consuming a tremendous amount of CPU, but which thread (user session) is taking all of the CPU? Simply double-click the oracle.exe process in QuickSlice. This will bring up the following window:

Page 24: Oracle Concepts

We can see from the window (above) that Thread ID "7e8" is consuming all of the CPU. This is the thread (SPID) we want to kill. Notice that QuickSlice displays the Thead ID in HEX. You will need to convert this to a decimal number in order to use it as a parameter to OraKill:

7e8 (Hex) ==> 2024 (Dec)

We now have all of the information we need to kill our runaway user session using OraKill:

Page 25: Oracle Concepts

C:\> orakill JEFFDB 2024

Kill of thread id 2024 in instance JEFFDB successfully signalled.

That's all there is to it. Our runaway process is immediately killed as seen below:

SQL> begin 2 loop 3 null; 4 end loop; 5 end; 6 /begin*ERROR at line 1:ORA-03113: end-of-file on communication channel

SQL>

Page 26: Oracle Concepts