0% found this document useful (0 votes)
384 views

DBA Sheet v5.8

This document contains sections on hardware, operating system details, processes, memory, disks, CPU, compression, finding and replacing files, networking, and other topics. It provides commands to get hardware details, operating system version, memory and disk usage, CPU usage and processes, compressing files, finding and replacing text, network configuration, and more system troubleshooting and monitoring tasks.

Uploaded by

a singh
Copyright
© © All Rights Reserved
Available Formats
Download as XLS, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
384 views

DBA Sheet v5.8

This document contains sections on hardware, operating system details, processes, memory, disks, CPU, compression, finding and replacing files, networking, and other topics. It provides commands to get hardware details, operating system version, memory and disk usage, CPU usage and processes, compressing files, finding and replacing text, network configuration, and more system troubleshooting and monitoring tasks.

Uploaded by

a singh
Copyright
© © All Rights Reserved
Available Formats
Download as XLS, PDF, TXT or read online on Scribd
You are on page 1/ 419

Hardware

Hardware type

OS
OS version

OS 32 bit or 64bit
who command alternative
server reboot time

Tracing
Tracing system calls
How to Trace Unix System Calls (Doc ID 110888.1)

identifiy zombie process


Full details abou a PID
Memory

RAM SIZE

Real Memory used by a Oracle


Virtual memory usage
Top Memory Users

Clear cache memory in Linux

Disks
sort by file size
List Disks
Disk size
Disk Cloning between two servers
Create a dummy disk in solaris = 1GB
copying the disks
Disk Hardware errors

os space not release after deletion

Device statistics
freespace in zpool
Os used disks

CPU

Number of CPU's

CPU Usage
TOP CPU Users
Top 10 CPU consuming process
CPU & Memory used by a PID
top CPU Usage

SAR

CPU:

Memory:

Disk:

Network:

ZIP
Zipping a folder in solaris
Compress old files
compressing the folder
Reading files under .gz without uncompress
FIND/Replace
Display above & below 2 lines on grep
Finding a file

Find

Remove Old files

Replace a word in all the files under a directory

MAIL

Sending a File through mail


sending mail from a server
Network
No of open connection to db from a server
Unplumb the network interface

MTU value

Enable remote desktop in linux

vncserver
SCP @ background
rsync the files between servers
scp faster file transfer method (ssh pwd required)
file copy to remote server without pwd
identify who occupied the port
Check the physical status of a NIC card
Others

iostat

Error log
^M Error
Tree command in solaris'

History

History command
who logged in

Timing at unix prompt

Time taken for a execution of a command


Check the package installed or not
Installation of rpm without dependency

How to check server is a global or local zone

To check the HBA ports are online or offline

" Tmp file too larg" error in vi command

C program
c program to execute a shell script

display two files in parallel

difference of two files ( indicated with '|' symbol )


uname -M / prtconf
cat /sys/devices/virtual/dmi/id/*
uname -a

oslevel -r
cat /etc/release
cat /etc/redhat-release

uname -m
x86_64 ==> 64-bit kernel
i686 ==> 32-bit kernel
pinky
who -b

truss -p <spid> (or) truss -aedfo sqlplus.trc sqlplus /nolog


strace -p <spid> -o output.txt
trace -p <spid>
ps -ecl |grep "Z"
pargs 11637

/usr/sbin/prtconf | grep Mem


dmesg
vmstat 5 5
swapinfo -tam
glance and m
lsdev -C | grep mem
lsattr -El mem0 ( output from previous command)
free -h, cat /proc/meminfo, dmesg | grep Memory
uerf -r 300 | grep -I mem
prstat -a
vmstat 1 5
/usr/ucb/ps vax |head

sync; echo 1> /proc/sys/vm/drop_caches

du -sh * | sort -h
iostat -IEn (or) echo|format
fdisk -l | egrep 'Disk.*bytes' | awk '{ sub(/,/,""); sum +=$3; print $2" "$3" "$4 } END { print "—————–"; print "total: " sum " GB
http://serverfault.com/questions/4906/using-dd-for-disk-cloning
dd if=/dev/zero of=test.img bs=1024k count=1000
dd if=test.img of=test.img.bkp bs=1024000k
root@server # iostat -IEn|grep c0t600507680181050F20000000000009F2d0
c0t600507680181050F20000000000009F2d0 Soft Errors: 0 Hard Errors: 770 Transport Errors: 698
root@server #

$ /usr/sbin/lsof | grep deleted


ora 25575 data 33u REG 65,65 4294983680 31014933 /oradata/dbname/something.dbf (deleted)
$ file /proc/25575/fd/33
/proc/25575/fd/33: broken symbolic link to `/oradata/DATAPRE/UNDOTBS009.dbf (deleted)'
$ echo > /proc/25575/fd/33
$ df -h .

iostat -xnp
zpool list
zpool status

Solaris --suppose virtual CPU


lscpu (or) cat /proc/cpuinfo|grep processor|wc -l
psrinfo -v|grep "Status of processor"|wc -l
lsdev -C|grep Process|wc -l
ioscan -C processor | grep processor | wc -l
kstat | grep -i core_id | uniq
#psrinfo -p
1
#psrinfo |wc -l
64
So here is the complete picture, T5220, has one socket, 8 cores, 8 threads per core which equates to 64 virtual CPU’s.
sar -u 1 10
/usr/ucb/ps uax |head
date ; ps auwx | sort -r +2 | head -10
/usr/ucb/ps auxvv 11637
ps -eo pcpu,pid,user,args | sort -k 1 -r | head -10

Basic CPU: sar [-u] [interval [count]]


Load Average: sar -q [interval [count]]
Kernel Paging: sar -B [interval [count]]
Unused Memory: sar -r [interval [count]]
Swap Space: sar -S [interval [count]]
Average Disk I/O: sar -b [interval [count]]
Disk I/O: sar -dp [interval [count]]
Network: sar -n DEV [interval [count]]
Network Errors: sar -n EDEV [interval [count]]

zip -r archive_name.zip folder


gzip logfile.log
tar -zcvf archive.tar.gz directory/
zcat filename (or) zhead filname (or) zless filename

cat a | grep 5 -C 2
find /opt/tivoli/tsm/client -exec grep -l "servername" {} \;

find / -print | grep -i dbmspool.sql

find /opt/oracle/admin//cdmp* -mtime +1 -exec rm {} \;

#Verify it's using /home/oracle/oraInventory


find oraInventory -type f -exec grep oraInventory {} \; | head
#Replace old oraInventory strings in all files under oraInventory
find oraInventory -type f -exec perl -pi -e 's#/home/oracle/oraInventory#/u01/app/oracle/oraInventory#g' {} \;
#Verify it's using /u01/app/oracle/oraInventory
find oraInventory -type f -exec grep oraInventory {} \; | head

uuencode file.txt file.txt | mailx [email protected]


uuencode file.txt file.txt | mailx -s "this mail has attachments" [email protected]
mailx -s "Test email `hostname`" [email protected] < /dev/null

lsof -i:1521 | grep ESTABLISHED | grep db_name| wc -l


ifconfig nxge2:2 unplumb

Ping all public and private nodename or IP of all nodes with corresponding MTU:
/usr/sbin/ping -s nodename mtu 2
Example in three node environment
/usr/sbin/ping -s node1-pub 1500 2
/usr/sbin/ping -s node2-pub 1500 2
/usr/sbin/ping -s node3-pub 1500 2
/usr/sbin/ping -s node1-priv 9000 2
/usr/sbin/ping -s node2-priv 9000 2
/usr/sbin/ping -s node3-priv 9000 2

Enable
------
gconftool-2 -s -t bool /desktop/gnome/remote_access/enabled true
gconftool-2 -s -t bool /desktop/gnome/remote_access/prompt_enabled false
Diable
-------
gconftool-2 -s -t bool /desktop/gnome/remote_access/enabled false

Then edit /opt/oracle/admin/.vnc/xstartup & uncomment the two lines


export PATH=/:/bin:/usr/local/bin:/usr/ucb:/etc:/usr/sbin:/sbin:/usr/X11/bin:/usr/openwin/bin:/opt/sfw/bin:/bin:/OPatch:$PATH
vncserver
ps -ef | grep vnc
vncserver -kill :4
nohup scp -P 223 /tmp/myfile.dat user@server:/tmp &
rsync -avz --progress username@sourceserver:/path/to/file.dmp .
scp -c arcfour -r username@sourceserver:/path/to/file.dmp .
# SOURCE:
follow same as below - dont add ___location directly to dumpfile

cd /___location
tar -cf - expdpmyfile.dmp | gzip -1 | nc -l 9999

# TARGET:
cd /thelocation/u/need
nc Sourceserver 9999 | gzip -d | tar xf - -C .
netstat -anlp | grep 1587
/sbin/ip link show

prstat -n 5 -s cpu
iostat -x 1 3

Linux: /var/log/messages, Solaris, HP Tru64: /var/adm/messages, HP-UX: /var/adm/syslog/syslog.log, AIX: /bin/errpt


dos2unix filename filename
ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^/ /' -e 's/-/|/'

ksh
HISTTIMEFORMAT="%d/%m/%y %T "
history
last | grep root | more

PS1="[\d \t \u@\h:\w ] $ "


Ex : $ time dd if=test.img of=test.img.bkp bs=1M
dd: bad numeric argument: "1M"
real 0m0.01s
user 0m0.00s
sys 0m0.00s
pkginfo | grep xvnc
rpm -Uvh /opt/oracle/admin/redhat-release-6Server-1.noarch.rpm --nodeps

db/server: /dev/rdsk> zonename


Server1
Servernode2> zonename
global

bash-3.2# luxadm -e port


/devices/pci@0/pci@0/pci@8/pci@0/pci@8/SUNW,emlxs@0/fp@0,0:devctl NOT CONNECTED
/devices/pci@0/pci@0/pci@8/pci@0/pci@8/SUNW,emlxs@0,1/fp@0,0:devctl NOT CONNECTED
/devices/pci@0/pci@0/pci@9/SUNW,emlxs@0/fp@0,0:devctl NOT CONNECTED
/devices/pci@0/pci@0/pci@9/SUNW,emlxs@0,1/fp@0,0:devctl NOT CONNECTED
stty columns 120
vi file.log
$ cat a.c
#include <stdio.h>
#include <stdlib.h>

#define SHELLSCRIPT "\


ssh mainserver '/work/oracle/dba/bin/mygrid gridname'"

int main(void)
{
system(SHELLSCRIPT);
return 0;
}
$ cc a.c
$ ./a.out

paste c.txt d.txt | awk -F'\t' '{


if (length($1)>max1) {max1=length($1)};
col1[NR] = $1; col2[NR] = $2 }
END {for (i = 1; i<=NR; i++) {printf ("%-*s %s\n", max1, col1[i], col2[i])}
}'

diff -y -W 170 c.txt d.txt


vimdiff file1 file2
sdiff -w 250 presnap.txt postsnap.txt | more (Solaris )
AIX
Linux
Solaris

AIX
Solaris
linux

solaris,AIX
Linux
Tru 64
http://www.c0t0d0s0.org/archives/4778-Less-known-Solaris-features-Getting-rid-of-Zombies.html

Solaris

HP/UX

AIX
Linux
DEC-UNIX
To free pagecache:
Solaris
# echo 1 > /proc/sys/vm/drop_caches
To free dentries and inodes:
svmon
# echo 2 > /proc/sys/vm/drop_caches
To free pagecache, dentries and inodes:

# echo 3 > /proc/sys/vm/drop_caches

Linux
http://serverfault.com/questions/4906/using-dd-for-disk-cloning
solaris

psrinfo | wc -l
Linux
Solaris
AIX
HP/UX
Real CPU in Solaris

ps -e -o pcpu -o pid -o user -o args


topas

ps auxw | sort -r +2 |head -10


find /backup/logs/ -name daily_backup* -mtime +21 -exec rm -f {} ;

http://yong321.freeshell.org/oranotes/MoveOraInventory.txt

solaris
works only in linux

it will remove all CTRL ^ M Errors

fc -l -99

history -200

solaris

Note : if the output is global then , the server is configured


as global
if the output is same server name then , the server is
configured as local ( virtual machine)
$ cat b.c
#include <stdlib.h>

int main() {
system("/work/oracle/s/mygrid.sh");
return 0;
}
$ cc b.c
$ ./a.out

https://stackoverflow.com/questions/13341832/display-two-files-side-by-side

diff --old-group-format=$'\e[0;31m%<\e[0m' \
--new-group-format=$'\e[0;31m%>\e[0m' \
--unchanged-group-format=$'\e[0;32m%=\e[0m' \
c.txt d.txt
Solaris: truss -d -E -p 1454
Linux : strace -ttT -p 5164
HP-UX : tusc
wn-Solaris-features-Getting-rid-of-Zombies.html

prstat -a

-disk-cloning
getdev
cfgadm -la
prtconf

echo Cores = $(( $(lscpu | awk '/Socket/{ print $2 }') * $(lscpu | awk '/Core/{ print $4 }') ))

http://www.dba-oracle.com/t_tuning_cpu_usage_vmstat.htm
21 -exec rm -f {} ;
splay-two-files-side-by-side
prstat -Z
Issue

command to delete files old trace file


oracle..> rm -rf *.aud
ksh: /usr/bin/rm: arg list too long

ORA-09925: Unable to create audit trail file


Linux-x86_64 Error: 28: No space left on device (BUT SPACE Available)

Remove MGMT audit files

login to MGMT directory

ora-27102: out of memory

memory allocated to oracle user id in server

Tracing
Tracing Oracle process OS level
Tracing SQLPLUS at OS level

Others

Asking for oratab while logging in

List the databases running on server


Run Sql commands in terminal
Stopping the process
Killing clusterware processes

Killable processes

Instance-Critical: Non killable process

alias
SCRIPTS

Get the CPU/Memory Free Usage details from Database


script to extract db alias names from tnsnames.ora file

Os level scripting
Shell script to execute multiple database - 12c

cmd script for logging into multiple databases


OS prompt script

os level execute script

Profile for OS

ectract CRS_HOME from /etc/oratab

extract host/port/servicename from TNSPING

Execute the script after 4.5 hours ( execute this in sqlplus)

Server maintenance
Solution

find /opt/oracle/diag/rdbms/dbname/instance_name/trace -name "*.trc" -mtime +3 -exec rm {} \;


find /opt/oracle/diag/rdbms/dbname/instance_name/trace -name "*.trm" -mtime +3 -exec rm {} \;
find /opt/oracle/diag/rdbms/dbname/instance_name/trace -name "*.gz" -mtime +3 -exec rm {} \;
find /opt/oracle/diag/tnslsnr/hostname/listener_dbname/alert -name "log*xml" -mtime +3 -exec rm {} \;
(or)
find . -name "*.aud" -mtime +7 -exec rm -f {} \;

find . -name '*.aud' -exec rm {} +

$ df -kh /u01
Filesystem Size Used Avail Use% Mounted on
/dev/mapper/VGExaDb-LVDbOra1
99G 82G 12G 88% /u01

$ df -h -i /u01
Filesystem Inodes IUsed IFree IUse% Mounted on
/dev/mapper/VGExaDb-LVDbOra1
13M 13M 0 100% /u01

So delete old *.aud files from that ___location

rm: invalid option -- 'M'


Try `rm ./-MGMTDB_m000_10055_95.aud' to remove the file `-MGMTDB_m000_1.aud'.
Try `rm --help' for more information.
hostname$/opt/grid/12.1.0.2.PSUAPR2017/rdbms/audit>rm -- *.aud
hostname$:/opt/grid/12.1.0.2.PSUAPR2017/rdbms/audit>ls -ltr

[oracle@host01 _mgmtdb]$ cd -MGMTDB


-bash: cd: -M: invalid option
cd: usage: cd [-L|-P] [dir]
To get around that, I need to use “dot-slash” before the directory name.
[oracle@host01 _mgmtdb]$ cd ./-MGMTDB
[oracle@host01 -MGMTDB]$ cd trace

free -m

use this comman an see the cache memory .. It should be less… if it is more than 5Gb ask unix admin to lear the memory
prtconf | grep Mem
id -p
prctl -n project.max-shm-memory -i project 100

strace -fF -v -p 16311


strace /oracle/product/10.2.0.1/bin/sqlplus -V 2>&1 |less

grep "^[^#]" /var/opt/oracle/oratab | awk -F: '{printf("\t%-6s\t%-30s\n",$1,$2)}'


. Oraenv
ps -ef|grep pmon | awk '{print $8}'|grep -v "grep"| grep -v "ASM"| cut -d"_" -f3

ps -eaf | grep _pmon_ | grep -v grep | grep -v + | grep -v "^#" | awk '{print $NF}' | cut -c 10-
echo 'select count(*) from tab;' | sqlplus / as sysdba
ARCn: Redo log archivers
CJQn: Job scheduler coordinator
Dnnn: Dispatchers
DIA0: Diagnosibility process 0
ACMS: Atomic controlfile
DIAG: Diagnosibility to memory server
coordinator
CKPT: Checkpoint
FDBA: Flashback data archiver process
DBRM:
Jnnn: JobResource manager
scheduler process
processes
DBWn:
PING: Database
Interconnectwriter processes
latency measurement
ps -ef | grep ora_ | grep orcl2 | awk '{print $2}' | while read PID
LGWR:
Qnnn:
do Redo log
Queue writerprocesses
cleanup
LMDn:
QMNC: Global
kill -STOPQueue enqueue
$PIDcoordinatorservice daemons
LMON:
RECO: Global enqueue
done Distributed recovery service monitor
process
MMAN:
Snnn: Memory manager
ps -ef |Shared servers | grep -v grep | awk '{print $2}' | xargs kill -9
grep <keyword>
PMON:
SMCO: Process monitor
Space management coordinator
PSPn:
Wnnn: Process spawners processes
Space management
RMSn: RAC management server
RVWR: Recovery writer
SMON: System monitor process
VKTM: Virtual keeper of time process
MMNL: Manageability Monitor Process 2
MMON: Manageability Monitor Process
alias s="sqlplus / as sysdba"

SELECT
STAT_NAME,
DECODE(STAT_NAME,'PHYSICAL_MEMORY_BYTES',(ROUND(VALUE/1024/1024/1024,2))
|| ' GB','FREE_MEMORY_BYTES',(ROUND(VALUE /1024/1024/1024,2))
|| ' GB',VALUE ) VALUE
FROM
v$osstat
WHERE
stat_name IN ( 'FREE_MEMORY_BYTES', 'LOAD', 'NUM_CPUS', 'NUM_CPU_CORES',
'NUM_CPU_SOCKETS', 'PHYSICAL_MEMORY_BYTES' );
sort -u $TNS_ADMIN/tnsnames.ora | grep -v "^ " | grep -v "^#" | grep -v "^(" | grep -v "^)" | sed "s/ =//g" | grep -v "^$"

for i in `ps -ef|grep pmon | awk '{print $8}'|grep -v "grep"| grep -v "ASM"| cut -d"_" -f3`
do
export ORACLE_SID=$i
sqlplus -s /nolog <<EOF
set head off echo off
conn / as sysdba
SELECT comp_name, version, status FROM dba_registry where status='INVALID';
exit
EOF
done
#!/bin/ksh
rm -rf log.txt
for i in `cat a.txt`
do
echo ' ------'$i'----- ' >> /tmp/log.txt
sqlplus -L -S << EOF >> /tmp/log.txt
/ @$i
set feedback off
set lines 750 pages 0
col value for a20
select (select name from v\$database) dbname, (select NAME from v\$pdbs where con_id=(select con_id from v\$pdbs where
rownum < 2)) con,i.host_name,p.inst_id,p.name,p.value from gv\$parameter p, gv\$instance i where p.name='global_names' an
p.inst_id=i.inst_id order by p.inst_id;
exit;
EOF
done

echo off
cls
for /f "tokens=1-2 delims= " %%b in (1.txt) do (
echo.***********************************************
echo.Connect to %%b
rem echo. Password: %%c
echo.***********************************************
rem echo.sqlplus -L sys/pwd@%%b @C:\dbname.sql
sqlplus -L "sys/pwd@%%b as sysdba" @C:\dbname.sql

)
echo.
echo.DONE
echo.Press any key to exit.
pause >nul
for i in `ps -ef |grep pmon|grep -v MGMTDB|grep -v ASM|grep -v grep|cut -d"_" -f3`
do
export ORACLE_SID=$i
export ORACLE_HOME=`ps -ef |grep pmon|grep $i|awk {'print "pwdx " $2 '}|sh|awk {'print $2 '}|sed 's/....$//'`
#!/bin/ksh
export PATH=$ORACLE_HOME/bin:$ORACLE_HOME/OPatch:$PATH
# ------------------------------------------------------------------------
sqlpluskornshell
# A simple -s "/ as sysdba"
script to <<EOF
force all running instances to re-register
set lines 300
# with the remote_listener (workaround for bug 13066936)
col VALUE for a65
# ------------------------------------------------------------------------
export ORACLE_HOME=/opt/oracle/product/11.1.0/db7
select
for INST name,
in `ps -aefdb_unique_name,
| grep 'ora_pmon' open_mode,database_role
| egrep -v '(grep|sed)' | sed from v\$database;
's/^.*ora_pmon_//'`
PATH=/usr/bin:/etc:/usr/sbin:/usr/ucb:$HOME/bin:/usr/bin/X11:/sbin:.:/usr/local/bin:${ORACLE_HOME}:${ORACLE_HOME}/bin
do show parameter log_archive_config
{ORACLE_HOME}/OPatch:/oracle/dba/bin
echoEOF . Reregistering $INST with remote_listener
done
export ORAENV_ASK=NO
export PATH
. oraenv
export $INST
HISTFILE=$HOME/.histdir/$(tty|sed 's-/-_-g')
sqlplus
export -SL "/ as sysdba" <<-EOF >/dev/null
DBA_INIT_INI=/oracle/dba/funcs/dba_init.ini
col remote_val new_value remote_val
select value
# NMON remote_val
variable from v\$parameter
to stop oslevel checking where name='remote_listener';
alter system set
export NMONAIX=5.2.0.0 remote_listener='';
alter system register;
alterEDITOR=vi
export system set remote_listener='&remote_val';
alterFPATH=/oracle/dba/funcs
export system register;
EOF
export TNS_ADMIN=/var/opt/oracle
done
export ORACLE_BASE=/opt/oracle
export ORACLE_ASK=YES
export ORACLE_OWNER=oracle

export NLS_LANG=AMERICAN_AMERICA.UTF8
export NLS_DATE_FORMAT='YYYY/MM/DD HH24:MI'

nins
. .kshrc

# Set up machine independent variables


stty erase '^H' kill "^U" intr "^C" eof "^D"
umask 002
export JAVA_COMPILER=NONE
export HOST=$(uname -n)
export PWD=`pwd`
export PS1='$ORACLE_SID@$HOST: $PWD> '
if [ -s "$MAIL" ] # This is at Shell startup. In normal
then echo "$MAILMSG" # operation, the Shell checks
fi # periodically.

export ORATAB="/var/opt/oracle/oratab"
export ORA_CRS_HOME=`cat /etc/oratab|grep -i asm|awk -F: '{print $2}'`

tnsping gpo_core_u |
awk '{FS="[()]+";for(i=1;i<=NF;i++) if($i ~ /(HOST|PORT|SERVICE_NAME)/) print $i}'

script.sql which executes SQLT XTRACT with a delay of 4.5 hours


host sleep 4.5h
start run/sqltxtract.sql 51x6yr9ym5hdc sqltxplain

Presnap
fi

if [[ $(ps -ef | grep ./mgr | $GREP -vE 'grep|async' | wc -l) -ne 0 ]];
then
$ECHO ' \033[1;33m Goldengate = Running \033[0;0m '
else
echo "Goldengate = Not Running"
fi
echo ' '
echo ' '
EOF

chmod 755 osprecheck.sh

./osprecheck.sh | tee presnap.txt


Comments

https://weidongzhou.wordpress.com/2014/10/26/out-of-space-error-while-still-have-space/

for linux

Solaris

ps -eo comm| grep -v grep|grep pmon|sed s/ora_pmon_//


conn / as
sysdba
select
decode(o
pen_mod
e,'READ
WRITE','
OPEN','M
OUNT')
from v\
$databas
e;
exit
EOF
for x in
`cat
/tmp/temp
.sql |
egrep
"OPEN|
MOUNT|
ORA-
01507"|
grep -v
"^sel"|awk
{'print
$1}'`
do
if [ "$x" =
"ORA-
01507:" ]
then
for i in `ps -ef|grep pmon | awk '{print $8}'|grep -v "grep"| grep -v "ASM"| cut -d"_" -f3` echo
do "Databas
export ORACLE_SID=$i e $i in
sqlplus -s /nolog <<EOF NOMOUN
set head off echo off T stage"
conn / as sysdba else
spool $i.sql echo
--select example script sql "Databas
select 'alter materialized view '||owner||'.'||object_name||' compile;' e $i in $x
from dba_objects stage"
where status<>'VALID'; fi
spool off; done
@$i.sql; rm
exit /tmp/temp
EOF .sql
done done
#!/bin/ksh
rm -rf dbhealthoutput.txt
echo "Enter the syspassword"
stty -echo
read sys_pw
stty echo
for i in `cat dblist.txt`
do
echo '***********************************************'
echo connecting to $i
echo '***********************************************'

echo '*********************' >>dbhealthoutput.txt


echo connecting to $i >>dbhealthoutput.txt
echo '*********************' >>dbhealthoutput.txt
sqlplus -L -S sys/$sys_pw@$i as sysdba @script.sql >>dbhealthoutput.txt
echo ' ' >>dbhealthoutput.txt
echo
'*****************************************************************************************************************
****************************************************************' >>dbhealthoutput.txt
echo ' ' >>dbhealthoutput.txt
done

more dbhealthoutput.txt
postsnap
if [[ $(ps -ef | grep ./mgr | $GREP -vE 'grep|async' | wc -l) -ne 0 ]];
then
$ECHO ' \033[1;33m Goldengate = Running \033[0;0m '
else
echo "Goldengate = Not Running"
fi
echo ' '
echo ' '
EOF

chmod 755 ospostcheck.sh

./ospostcheck.sh | tee postsnap.txt

diff -y -W 250 presnap.txt postsnap.txt | more


ORACLE
_HOME=`
ps -ef |
grep
pmon|
grep $i|
awk {'print
"pwdx "
$2 '}|sh|
awk {'print
$2 '}|sed
's/....$//'`

export
PATH=$O
RACLE_H
OME/bin:
$ORACL
E_HOME/
OPatch:
$PATH

sqlplus -s
"/ as
sysdba"
<<EOF
set
lines 300
col
VALUE
for a65

select
name,
db_uniqu
e_name,
open_mo
de,databa
se_role
from v\
$databas
e;
show
parameter
log_archiv
e_config
EOF
done
Identify the Exadata Box type

cell versions

offloading saved

exadata resource manager plans


cv_cellVersion
, CAST(extract(xmltype(confval), '/cli-output/cell/flashCacheMode/text()') AS
VARCHAR2(20)) cv_flashcachemode
, CAST(extract(xmltype(confval), '/cli-output/cell/cpuCount/text()') AS VARCHAR2(10))
cpu_count
http://www.centroid.com/blog/monitoring-exadata-smart-scan
, CAST(extract(xmltype(confval), '/cli-output/cell/upTime/text()') AS VARCHAR2(20))
uptime
, CAST(extract(xmltype(confval),
grep '/cli-output/cell/kernelVersion/text()') AS VARCHAR2(30))
-i MACHINETYPES /opt/oracle.SupportTools/onecommand/databasemachine.xml
kernel_version
, CAST(extract(xmltype(confval), '/cli-output/cell/makeModel/text()') AS VARCHAR2(50))
make_model
FROM
v$cell_config -- gv$ isn't needed, all cells should be visible in all instances
WHERE
conftype = 'CELL'
ORDER BY
cv_cellname;

select name, value from v$statname join v$mystat using (statistic#)


where name in
('cell physical IO bytes eligible for predicate offload',
'cell physical IO interconnect bytes returned by smart scan',
'cell physical IO bytes saved by storage index');

Scripts and Tips for Monitoring CPU Resource Manager (Doc ID 1338988.1)
HP => High Performance
HC => High Capcity

http://oradwstories.blogspot.com/2015/02/detecting-change-in-
2015/02/detecting-change-in-execution-plan-of.html
Nice url

Disk Details

Find Available disk to add to any diskgroup

Disk Group & disks Details

Disk group freespace & mounted or not

Disk group compatability

% used

DB Each Folder Utilization in MB in asm diskgroups

Each folder size in a diskgroup


asmdu script--Unix Script

ASM backup

Recreating disk sql's from metadata

Create Diskgroup Command


Dropping the Disk Group

Adding a disk

Copy an ASM file from a local ASM instance to a remote ASM instance

Formatting ASM disk header

Adding disks to disk group

Blocker in ASM

Kill all LOCAL connections

Removing all the files in ASM


Removing all archivelog Files from ASM

Files that are not in use currently under asm disks


Identify files in ASM not known to DB

Detecting disks using kfod

Check diskgroup usign kfod

Disk Size

Troubelshooting

Resizing disks

Masternode in CRS

Checking Disks

Database Cloning using kfed

undrop the diskgroup using kfed

Check the mirrored copies of a block in asm

Repair the Disk Corruption


Check do u have the backup block in the disk

Read a disk using od command ( Alternative to strings command)

Show the dismounted diskgroups

ASM Disk I/O Time out issues

ASM diskgroup mount failure

password copy for 12c

ACFS file system not mounted

asmcmd privileged logins

ASM LIB

ASMLIB Device to disk mapping script

Oracleasm Lib diskgroup creation

unix kernal
asm module / Package

asm disks

discovery

config files

log

To Reload asm - module failure msg in /var/log/oracleasm


set lines 250
set pages 9999
http://satya-dba.blogspot.com/2010/03/automatic-storage-management-asm-10g.html
column path format a20

select path, group_number group_#, disk_number disk_#, mount_status,


header_status, state, total_mb, free_mb
set
frompagesize
v$asm_disk 100
column inst format
order by group_number; a10 heading 'Inst'
column file_type format a20 heading 'File type'
col
col PATH
column
PATH mgfor
for a55
format
a55 99,999,999
col
breakDG_NAME
select on path, for 1a15
instgroup_number
skip group_#, disk_number disk_#, mount_status,header_status, state,
col DG_STATE
compute sum
total_mb, free_mb offor
mg a10
on v$asm_disk
from inst where header_status='CANDIDATE' or
col FAILGROUP
whenever sqlerrorfor
header_status='FORMER' a20
exit 1 order by 1 ;
set pages
lines 750 0 feedpages off 9999
linesize 100 heading on
set pagesize 100
select inst, file_type,sum(mg) mg from (
column inst format
select dg.name a10 heading
dg_name, dg.state'Inst'dg_state, dg.type, d.disk_number
substr(full_alias_path,2,instr(full_alias_path,'/',2,1)-2) as INST, dsk_no,
column file_type format a20 heading
d.path,d.total_mb,d.free_mb,
file_type, 'File type'd.FAILGROUP, d.state
d.mount_status,
column mg format 99,999,999
from v$asm_diskgroup
round((szbytes)/1048576) dg,as
v$asm_disk
MG from ( d
break on inst skip 1 sys_connect_by_path(aname, '/'))) full_alias_path,
where lower(concat('',
select dg.group_number=d.group_number
compute sum of mgdsk_no;
ordersystem_created,
by dg_name, on inst
alias_directory, file_type, szbytes
from ( select b.name gname, a.parent_index pindex, a.name aname,
set pagesa.reference_index
40000 lines 120 rindex , a.system_created, a.alias_directory,
select
col NAME inst, file_type,sum(mg)
c.type
for a15file_type, c.bytes mgszbytes
from (
select
select fromsubstr(full_alias_path,2,instr(full_alias_path,'/',2,1)-2)
v$asm_alias a, v$asm_diskgroup
GROUP_NUMBER b, v$asm_file c as INST,
DG#, name, ALLOCATION_UNIT_SIZE AU_SZ, STATE,
file_type,
TYPE, where a.group_number
TOTAL_MB, FREE_MB, = b.group_number
OFFLINE_DISKS from v$asm_diskgroup;
round((szbytes)/1048576)
and a.group_number as MG from (
= c.group_number(+)
select lower(concat('',
and a.file_number sys_connect_by_path(aname,
= c.file_number(+) '/'))) full_alias_path,
select GROUP_NUMBER,NAME,COMPATIBILITY,DATABASE_COMPATIBILITY
system_created, alias_directory, file_type, szbytes from
and
v$asm_diskgroup; a.file_incarnation = c.incarnation(+)
from) ( select b.name gname, a.parent_index pindex, a.name aname,
start witha.reference_index
(mod(pindex, power(2, rindex24))), a.system_created,
=0 a.alias_directory,
COL % and c.type
FORMAT file_type,
rindex99.0 in c.bytes szbytes
SELECTfrom v$asm_alias
name,
( selectfree_mb, a, v$asm_diskgroup b, v$asm_file c
total_mb, ((total_mb-free_mb)/total_mb)*100
a.reference_index as "USED %",
where a.group_number
free_mb/total_mb*100
from v$asm_alias "FREE%"=a,b.group_number
from v$asm_diskgroup
v$asm_diskgroup b order by 1;
andwherea.group_number
a.group_number = c.group_number(+)
= b.group_number
and a.file_number = c.file_number(+)
and (mod(a.parent_index, power(2, 24))) = 0
and) a.file_incarnation = c.incarnation(+)
connect and by priorb.namerindex= UPPER('&DGNAME')
= pindex)
) szbytes is not null)
where
start
groupwith (mod(pindex,
by inst, file_type; power(2, 24))) = 0
and rindex in
( select a.reference_index
from v$asm_alias a, v$asm_diskgroup b
where a.group_number = b.group_number
and (mod(a.parent_index, power(2, 24))) = 0
)
connect by prior rindex = pindex)
where szbytes is not null)
group by inst, file_type;

asmcmd > md_backup somefilename

asmcmd > md_backup myasmdiskbackup


asmcmd > md_restore -S mymdscript.sql myasmdiskbackup

CREATE DISKGROUP DATA_TEST EXTERNAL REDUNDANCY DISK '/dev/rdsk/c4t60050768018E027998000000000010F6


CREATE DISKGROUP TEST EXTERNAL REDUNDANCY DISK '/dev/rdsk/c5t600507680181050F20000000000007D4d0s0'
column module format a50
column blocker format a7
column waiter format a7
column lmode format 9999
column request format 9999
column inst_id format 9999
column sid format 9999
DROP
col DISKGROUP
username TEST INCLUDING CONTENTS;
format a6
col sid format 9999
col osuser
ALTER format a14 DATA01 ADD DISK '/dev/oracleasm/disks/ASM_DISK01' SIZE 1000 M
DISKGROUP
col s# format
rebalance 99999
power 10;
col server format a10
select * from v$asm_operation;
col client format a10
col pname format a10

spool locking_information
cp +DATA/orcl/datafile/tbsjfv.256.123456789
select to_char(sysdate,
\sys@mydb 'DD-MON-YYYY HH24:MI:SS' ) current_time from dual
. +ASM2 : +D2/jfv/tbsjfv.dbf
/

prompt ########################
$DD if=/dev/zero skip=25 bs=4k count=2560 of=$OCRLOC
prompt # Blocking Information #
prompt ########################
select
ALTERb.inst_id||'/'||b.sid blocker,
DISKGROUP DATA_DBNAME ADD DISK
-- s.module,
'/dev/rdsk/c6t600507680180854860000000000000B2d0s0' SIZE 102400 M REBALANCE
w.inst_id||'/'||w.sid
POWER 6; waiter,
b.type,
b.id1,
b.id2,
b.lmode,
w.request
from gv$lock b,
( select inst_id, sid, type, id1, id2, lmode, request
from gv$lock where request > 0 ) w
-- gv$session s
where b.lmode > 0
and ( b.id1 = w.id1 and b.id2 = w.id2 and b.type = w.type )
--and ( b.sid = s.sid and b.inst_id = s.inst_id )
order by b.inst_id, b.sid
/

ps -eaf | grep ASM | grep beq | awk '{print "kill -9 " $2}'

SELECT 'ALTER DISKGROUP '||gname||' DROP FILE '''||full_path||''';' gsql FROM


(SELECT CONCAT('+'gname, SYS_CONNECT_BY_PATH(aname,'/')) full_path, gname FROM
(SELECT g.name gname, a.parent_index pindex, a.name aname,
a.reference_index rindex, a.ALIAS_DIRECTORY adir
FROM v$asm_alias a, v$asm_diskgroup g
WHERE a.group_number = g.group_number)
WHERE adir='N'
START WITH (MOD(pindex, POWER(2, 24))) = 0
CONNECT BY PRIOR rindex = pindex)
WHERE full_path LIKE UPPER('%&database%');
SELECT 'alter diskgroup '||dg.name||' drop file ''+'||dg.name||''||
SYS_CONNECT_BY_PATH(al.name,'/')||''';'
FROM v$asm_alias al, v$asm_file fi, v$asm_diskgroup dg
WHERE al.file_number = fi.file_number(+)
AND al.group_number = dg.group_number
AND fi.type = 'ARCHIVELOG'
START WITH alias_index = 0
CONNECT BY PRIOR al.reference_index = al.parent_index;
/*+ -----------------------------------------------------------------
1st branch returns all the files stored on ASM
-----------------------------------------------------------------*/
select x.gnum,x.filnum,x.full_alias_path,f.ftype from (
SELECT gnum,filnum,concat('+'||gname, sys_connect_by_path(aname, '/')) full_alias_path
FROM (SELECT g.name gname, a.parent_index pindex, a.name aname,
a.reference_index rindex,a.group_number gnum,a.file_number filnum
FROM v$asm_alias a, v$asm_diskgroup g
WHERE a.group_number = g.group_number)
START WITH (mod(pindex, power(2, 24))) = 0 CONNECT BY PRIOR rindex = pindex) x,
(select group_number gnum,file_number filnum, type ftype from v$asm_file order by
group_number,file_number) f
where x.filnum != 4294967295
and x.gnum=f.gnum and x.filnum=f.filnum
MINUS
/*+ --------------------------------------------------------------
2nd branch returns all the files stored on ASM
and currently opened by any database client of the diskgroups
-----------------------------------------------------------------*/
select x.gnum,x.filnum,x.full_alias_path,f.ftype
from ( select id1 gnum,id2 filnum from v$lock where type='FA' and (lmode=4 or lmode=2)) l,
(
SELECT gnum,filnum,concat('+'||gname, sys_connect_by_path(aname, '/')) full_alias_path
FROM (SELECT g.name gname, a.parent_index pindex, a.name aname,
a.reference_index rindex,a.group_number gnum,a.file_number filnum
FROM v$asm_alias a, v$asm_diskgroup g
WHERE a.group_number = g.group_number)
START WITH (mod(pindex, power(2, 24))) = 0 CONNECT BY PRIOR rindex = pindex
) x,
(select group_number gnum,file_number filnum, type ftype from v$asm_file order by
group_number,file_number) f
where x.filnum != 4294967295 and
x.gnum=l.gnum
and x.filnum=l.filnum
and x.gnum=f.gnum and x.filnum=f.filnum) q
order by q.gnum,q.ftype
;
select concat('+'||gname, sys_connect_by_path(aname, '/')) full_alias_path,
system_created, alias_directory, file_type
from ( select b.name gname, a.parent_index pindex, a.name aname,
a.reference_index rindex , a.system_created, a.alias_directory,
c.type file_type
from v$asm_alias a, v$asm_diskgroup b, v$asm_file c
where a.group_number = b.group_number
and a.group_number = c.group_number(+)
and a.file_number = c.file_number(+)
and a.file_incarnation = c.incarnation(+)
)
where alias_directory = 'N'
start with (mod(pindex, power(2, 24))) = 0
and rindex in
( select a.reference_index
from v$asm_alias a, v$asm_diskgroup b
where a.group_number = b.group_number
and (mod(a.parent_index, power(2, 24))) = 0
and a.name = '&DATABASENAME'
)
connect by prior rindex = pindex;

export ORACLE_HOME=/tmp/OraInstall2014-01-30_01-59-24AM/ext/bin
export LD_LIBRARY_PATH=/tmp/OraInstall2014-01-30_01-59-24AM/ext/bin/../lib
cd /tmp/OraInstall2014-01-30_01-59-24AM/ext/bin
./kfod.bin verbose=true, disks=all status=true op=disks

kfod ds=true disks=all

kfed read /dev/rdsk/c0d17s0 | egrep "dskname|dsksize"

truss -aefdD -o /tmp/kfod_'$hostname'.truss kfod asm_diskstring='/dev/rdsk/*'

SQL> alter diskgroup DATA resize all size 1048288 M ;

SQL> alter diskgroup DATA resize disk DATA_0004 SIZE 1048288 M;

cd /opt/oracle/product/crs/log/wpsun564/cssd ; cat ocssd.log|grep -i 'master node'|tail -1

strings /dev/rdsk/c0d17s0 | head -10

http://oraclehandson.wordpress.com/2010/08/06/cloning-oracle-asm-databases-with-kfed/

http://externaltable.blogspot.com/2013_12_01_archive.html

https://twiki.cern.ch/twiki/bin/view/PDBService/ASM_utilities

kfed repair /dev/rdsk/c0d17s0


kfed read /dev/rdsk/c6t600507680181050F2000000000000A61d0s0 aun=1 blkn=254 |grep KFBTYP

od -c -N 128 /dev/rdsk/c6t60050768018E02799800000000000FA2d0s0

ASMCMD> lsdg --discovery

alter system set "_asm_hbeatiowait"=200 scope=spfile sid='*';

And bounce the ASM instance

https://taliphakanozturken.wordpress.com/2013/03/31/mounting-asm-diskgroup-fails-with-ora-15063-error-and-resolving-with-k

ASMCMD> pwcopy +DATA1/PRIMARY/PASSWORD/pwdprimary.1758.915635849


/home/oracle/orapwstdbydb
scp /home/oracle/orapwstdbydb standbyhost:/home/oracle
ASMCMD> pwcopy /home/oracle/orapwstdbydb +DATA1/STDBYDB/orapwstdbdy
$ srvctl modify database –d STDBYDB –pwfile +DATA1/STDBYDB/orapwstdbdy
$ srvctl config database -d STDBYDB

ASMCMD> volinfo --all


/opt/grid/12.1.0.2.PSUJAN2017/bin/acfsload start
incase if kernal fails then
/opt/grid/12.1.0.2.PSUJAN2017/bin/crsctl stop crs
/opt/grid/12.1.0.2.PSUJAN2017/bin/acfsroot install
/opt/grid/12.1.0.2.PSUJAN2017/bin/crsctl start crs
then try to start the filesystem if didn’t start automatically
srvctl start filesystem -d /dev/asm/acf-somename-123

asmcmd --privilege sysdba -p

#!/bin/bash
for asmlibdisk in `ls /dev/oracleasm/disks/*`
do
echo "ASMLIB disk name: $asmlibdisk"
asmdisk=`kfed read $asmlibdisk | grep dskname | tr -s ' '| cut -f2 -d' '`
echo "ASM disk name: $asmdisk"
majorminor=`ls -l $asmlibdisk | tr -s ' ' | cut -f5,6 -d' '`
device=`ls -l /dev | tr -s ' ' | grep "$majorminor" | cut -f10 -d' '`
echo "Device path: /dev/$device"
done

/etc/init.d/oracleasm createdisk SYSTEMDG2 /dev/mapper/oradisk01p1


/etc/init.d/oracleasm createdisk DISK01 /dev/mapper/oradisk03p1
create diskgroup BKUP EXTERNAL REDUNDANCY disk 'ORCL:DISK01' SIZE 102398 M;

uname -r
lsmod | grep -i oracle
rpm -qa | grep oracleasm

ls -ltr /dev/oracleasm/disks | sort

/etc/init.d/oracleasm scandisks
/etc/init.d/oracleasm listdisks

cat /etc/sysconfig/oracleasm

tail -200f /var/log/oracleasm

/usr/sbin/oracleasm init
cat <<EOF
"ORACLE_HOME" is not set
EOF
exit 1
fi

export PATH=${ORACLE_HOME}/bin:${PATH}
col path for a35
#
colGet last applied
Diskgroup log number
for a15
$ORACLE_HOME/bin/sqlplus
col DiskName for a20 -s "/ as sysdba" <<END
col disk# for 999
set pages 0 feed
col total_mb off linesize 100 heading on
for 999,999,999
set pagesizefor
col free_mb 100999,999,999
column
computeinst sum format a10 heading
of total_mb 'Inst'
on DiskGroup
column
computefile_type format a20
sum of free_mb on heading
DiskGroup 'File type'
column
break onmg format 99,999,999
DiskGroup skip 1 on report -
break on inst skip 1
compute
set pagessum 255 of mg on inst
whenever sqlerror exit 1
select a.name DiskGroup, b.disk_number Disk#, b.name DiskName, b.total_mb,
select inst, file_type,sum(mg)
b.free_mb, b.path, b.header_statusmg from (
select substr(full_alias_path,2,instr(full_alias_path,'/',2,1)-2)
from v$asm_disk b, v$asm_diskgroup a as INST,
file_type,
where a.group_number (+) =b.group_number
round((szbytes)/1048576)
order by b.group_number, as MG from ( b.name
b.disk_number,
select
/ lower(concat('', sys_connect_by_path(aname, '/'))) full_alias_path, Good query
system_created, alias_directory, file_type, szbytes
from ( select b.name gname, a.parent_index pindex, a.name aname,
a.reference_index rindex , a.system_created, a.alias_directory,
c.type file_type, c.bytes szbytes
from v\$asm_alias a, v\$asm_diskgroup b, v\$asm_file c
where a.group_number = b.group_number
and a.group_number = c.group_number(+)
and a.file_number = c.file_number(+)
and a.file_incarnation = c.incarnation(+)
and b.name = UPPER('${DG}')
)
start with (mod(pindex, power(2, 24))) = 0
and rindex in
( select a.reference_index
from v\$asm_alias a, v\$asm_diskgroup b
where a.group_number = b.group_number
and (mod(a.parent_index, power(2, 24))) = 0
-- and a.name = 'SINGLEDBNAME'
)
connect by prior rindex = pindex)
where szbytes is not null)
group by inst, file_type
/
exit;

END
exit 0

recreating asm disk sql's are stored in mymdscript in the current directory…

60050768018E027998000000000010F6d0s0' SIZE 102400M;


680181050F20000000000007D4d0s0' SIZE 102400 M DISK '/dev/rdsk/c5t600507680181050F20000000000007D5d0s0' SIZE 102400 M D
http://edbinfo.blogspot.com/2009/0
|grep KFBTYP

ASM Disks Offline With "Waited 15

ith-ora-15063-error-and-resolving-with-kfed/

https://emilianofusaglia.net/2016/04/08/troubleshooting-not-mounting-acfs-file-system/

http://surachartopun.com/2009/09/asm-dvm-acfs-by-command-lines.html

http://www.idevelopment.info/data/Oracle/DBA_tips/Automatic_Storage_Management/AS
M_50.shtml

/etc/init.d/oracleasm querydisk -d `/etc/init.d/oracleasm listdisks -d` | \


cut -f2,10,11 -d" " | \
perl -pe 's/"(.*)".*\[(.*), *(.*)\]/$1 $2 $3/g;' | \
while read v_asmdisk v_minor v_major
do
v_device=`ls -la /dev | grep " $v_minor, *$v_major " | awk '{print $10}'`
echo "ASM disk $v_asmdisk based on /dev/$v_device [$v_minor, $v_major]"
done cat /etc/sysconfig/oracleasmhttp://a
https://ronnyegner.word
/etc/init.d/oracleasm disable
/etc/init.d/oracleasm enable
D5d0s0' SIZE 102400 M DISK '/dev/rdsk/c5t600507680181050F20000000000007D6d0s0' SIZE 102400 M
info.blogspot.com/2009/02/to-remove-asm-files.html
ks Offline With "Waited 15 secs for write IO to PST" (Doc ID 1581684.1)

https://ronnyegner.wordpress.com/?s=etc%2Finit.d%2Foracleasm
RAC Enabled in ORACLE_HOME or not

How to disable RAC on Oracle_home

Capture resource definition

Node Eviction Demo

Killing clusterware processes

Verifying the JUMBO Frames

Verify the jumbo frames using MTU 9000 Value

Network connectivity check by OSW


Tracing RAC resources

Trace troubleshoot a RAC CRS error

Modifying the cluster services

Formatting OCR/Voting Disks

Diag Collections

Verify all the setting

Kill all CRS process

Switching RAC Home/Patching/Upgrade

How to skip mgmtdb on 12.1.0.2

Tracing cluvfy
crs resource script
crs resource creation script

database running on all RAC nodes

alternative to crsstat command (only for linux)

Grid all databases list

Grid all databases list with nodename


service name for the databases

Starting ACFS File system

If root.sh fails

RAC DB Load balancing across Instances

Ignore error till empty line found (or)


print output from empty line found
print output till empty line
/usr/ccs/bin/ar -t $ORACLE_HOME/rdbms/lib/libknlopt.a|grep kcsm.o

cd $ORACLE_HOME/rdbms/lib
make -f ins_rdbms.mk rac_off --Disabling RAC binaries
make -f ins_rdbms.mk ioracle --Linking to Oracle binaries

for res in `$ORA_CRS_HOME/bin/crs_stat -p | grep "^NAME=" | cut -d


= -f 2` ; do
$ORA_CRS_HOME/bin/crs_stat -p $res
>/opt/oracle/resources/$res.cap
done

oracle@rac2:~/ [+ASM2] ps -ef | grep cssd | grep -v grep


root 3583 1 0 11:45 ? 00:00:17 /u00/app/grid/11.2.0.2/bin/cssdmonitor
root 3595 1 0 11:45 ? 00:00:16 /u00/app/grid/11.2.0.2/bin/cssdagent
oracle 3607 1 1 11:45 ? 00:04:22 /u00/app/grid/11.2.0.2/bin/ocssd.bin

oracle@rac2:~/ [+ASM2] chrt -p 3595


pid 3595's current scheduling policy: SCHED_RR
pid 3595's current scheduling priority: 99

root@rac1 ~]# kill -STOP 3595; sleep 27; kill -CONT 3814

ps -ef | grep <keyword> | grep -v grep | awk '{print $2}' | xargs kill -9

traceroute -F node02-priv 9000

/usr/sbin/traceroute -s node1-priv node2-priv 9000

traceroute -r -F 192.168.0.210
export SRVM_TRACE=true
export SRVM_TRACE=""

root> export SRVM_TRACE=true


root> cd $CRS_HOME/bin
root> ./cluvfy comp crs -n

This will generate a trace file in $CRS_HOME/cv/log

$GRID_HOME/bin/crsctl modify resource ora.net1.network -attr "USR_ORA_IF=vnet0 vnet2"

$DD if=/dev/zero skip=25 bs=4k count=2560 of=$OCRLOC

[root@server1 tmp]# cd /tmp/myfolder


[root@server1 tmp]# export GRID_HOME=/opt/crs/12.1.0/grid
[root@server1 tmp]# export ORA_CRS_HOME=/opt/crs/12.1.0/grid
[root@server1 tmp]# perl /opt/crs/12.1.0/grid/bin/diagcollection.pl
--collect -all --incidenttime 06/12/201415:00:00 --incidentduration 01:00
[root@server1 tmp]# chown oracle:dba *
$NEW_GRID_HOME/oui/bin/runInstaller -updateNodeList
[root@server1 tmp]# tar -zcvf server1038diag.tar.gz myfolder
ORACLE_HOME=<$NEW_GRID_HOME> CRS="false" –local
Make
How tosure that only
Validate the current
Network GI home
and Name in the inventory
Resolution Setup for has
the Clusterware and RAC (Doc ID 1054902.1)
“CRS=TRUE” flag on ALL nodes.
Ask OSE to run the following four command as root as given in the
ps -ef given.
order | grep <keyword> | grep -v grep | awk '{print $2}' | xargs kill -9
cp -pR $OLD_GRID_HOME/cdata $NEW_GRID_HOME (Ex. cp
-pR /opt/grid/11.2.0.4.x /cdata opt/grid/11.2.0.4.y where x<y)
cp -pR $OLD_GRID_HOME/gpnp $NEW_GRID_HOME (Ex. cp -pR
/opt/grid/11.2.0.4.x /gpnp opt/grid/11.2.0.4.y where x<y)
cp -p $OLD_GRID_HOME/crs/install/s_crsconfig_<hostname>_env.txt
$NEW_GRID_HOME/crs/install
**The following command will switch the GI home to the new home and
should not be executed before above three copy commands are
executed.
$NEW_GRID_HOME/crs/install/rootcrs.pl –verbose -patch
-destcrsHome $New_GRID_HOME
You can see the progress by tailing
$New_GRID_HOME/cfgtoollogs/crsconfig/ crspatch_<hostname>.log.

adding -J-Doracle.install.mgmtDB=false on the installer command line to

rm -rf /tmp/cvutrace
mkdir /tmp/cvutrace
export CV_TRACELOC=/tmp/cvutrace
export SRVM_TRACE=true
export SRVM_TRACE_LEVEL=1
<STAGE_AREA>/runcluvfy.sh stage -pre crsinst -n <node1>,<node2>
-verbose
for res in `/opt/crs/12.1.0/grid/bin/crs_stat -p | grep "^NAME=" | cut -d =
-f 2` ; do
/opt/crs/12.1.0/grid/bin/crs_stat -p $res >/opt/oracle/resources/$res.cap
done
http://dbaregistry.blogspot.com/search/label/How%20to%20export%20and%20import%20crs%20resources

export ORACLE_HOME=`cat /etc/oratab | grep -i +ASM | cut -d: -f2`


export ORACLE_SID=`cat /etc/oratab | grep -i +ASM | cut -d: -f1`
export PATH=$ORACLE_HOME/bin:$PATH
rm -rf /tmp/tmp.log*
for i in `olsnodes`
do
chmod 777 chek.sh > /dev/null
/usr/bin/scp -o UserKnownHostsFile=/dev/null -o
StrictHostKeyChecking=no -q chek.sh $i:/tmp > /dev/null
done

for i in `olsnodes`
do
/usr/bin/ssh -o UserKnownHostsFile=/dev/null -o
StrictHostKeyChecking=no -q $i "chmod 777 /tmp/chek.sh" > /dev/null
/usr/bin/ssh -o UserKnownHostsFile=/dev/null -o
StrictHostKeyChecking=no -q $i "/tmp/chek.sh" > /tmp/tmp.log_$i
done
paste /tmp/tmp.log* | sed -e 's/\t/ \t/g' | column -t -s$'\t'

rm -rf /tmp/tmp.log*

crsctl status res |grep -v "^$"|awk -F "=" 'BEGIN {print " "}
{printf("%s",NR%4 ? $2"|" : $2"\n")}'|sed -e 's/ *, /,/g' -e 's/, /,/g'|\
awk -F "|" 'BEGIN { printf "%-40s%-35s%-20s%-50s\n","Resource
Name","Resource Type","Target ","State" }{ split ($3,trg,",") split
($4,st,",")}{for (i in trg) {printf "%-40s%-35s%-20s%-50s\n",
$1,$2,trg[i],st[i]}}'

for i in `olsnodes` ; do /usr/bin/ssh -q $i "ps -aef | grep pmon |awk '{print $8}' | egrep -i -v 'grep' | cut -d "_" -f3" | sort > /tmp/tmp

for i in `olsnodes`
do
echo $i > /tmp/tmp.log_$i
/usr/bin/ssh -q $i " echo "================" ; ps -aef | grep pmon |
awk '{print $8}' | egrep -i -v 'grep' | cut -d "_" -f3" | sort >>
/tmp/tmp.log_$i
done

paste /tmp/tmp.log* | sed -e 's/\t/ \t/g' | column -t -s$'\t' ; rm -rf


/tmp/tmp.log*
awk -F ":" '{if ($1) print "srvctl status service -d "$1""}'
/var/opt/oracle/oratab |grep -v '#\|+' |xargs -0 bash -c |grep -v 'PRC'

As root, execute the below.

/opt/grid/12.1.0.2/bin/acfsload start

As oracle,

srvctl start filesystem -d /dev/asm/acf-somename-123


srvctl start filesystem -d /dev/asm/acf_ggtrlv1-108
srvctl start filesystem -d /dev/asm/acf_repl1-108

[root rac2] /u01/app/11.2.0.3/grid/crs/install# /usr/bin/chuser

WITH sys_time AS (
SELECT inst_id, SUM(CASE stat_name WHEN 'DB time'
THEN VALUE END) db_time,
SUM(CASE WHEN stat_name IN ('DB CPU', 'background cpu
time')
THEN VALUE END) cpu_time
FROM gv$sys_time_model
GROUP BY inst_id )
SELECT instance_name,
ROUND(db_time/1000000,2) db_time_secs,
ROUND(db_time*100/SUM(db_time) over(),2) db_time_pct,
ROUND(cpu_time/1000000,2) cpu_time_secs,
ROUND(cpu_time*100/SUM(cpu_time) over(),2) cpu_time_pct
FROM sys_time
JOIN gv$instance USING (inst_id);

olsnodes | sed -n '/^$/,/^$/p' | awk '{if (NR==1 && NF==0) next};1'


olsnodes | sed -n '/^$/,/^$/!p'
Result returns 1 then RAC enabled. If 0 then not enabled

http://www.pythian.com/blog/changing-hostnames-in-oracle-rac/

Ping: With ping we have to take into account an overhead of about 28


bytes per packet, so 8972 bytes go through with no errors, while 8973
fail, this is a correct configuration that supports a message of up to
9000 bytes with no fragmentation:
[node01]$ ping -c 2 -M do -s 8972 node02-priv
PING node02-priv (10.10.10.2) 1472(1500) bytes of data.
1480 bytes from node02-priv (10.10.10.2): icmp_seq=0 ttl=64
time=0.220 ms
1480 bytes from node02-priv (10.10.10.2): icmp_seq=1 ttl=64
time=0.197 ms

[node01]$ ping -c 2 -M do -s 8973 node02-priv


From node02-priv (10.10.10.1) icmp_seq=0 Frag needed and DF set
(mtu = 9000)
From node02-priv (10.10.10.1) icmp_seq=0 Frag needed and DF set
(mtu = 9000)
— node02-priv ping statistics —
0 packets transmitted, 0 received, +2 errors
* Note: Ping reports fragmentation errors, due to exceeding the MTU
size.
Performance http://www.vmcd.org/2012/02/recommendation-for-the
-attr "USR_ORA_IF=vnet0 vnet2"

e Clusterware and RAC (Doc ID 1054902.1)

http://www.pythian.com/blog/slimming-down-oracle-rac-12cs-resource-footprint/

(Doc ID 986822.1)
http://dbaregistry.blogspot.com/search/label/How%20to%20export%20and%20import%20crs%20resources
0export%20and%20import%20crs%20resources

n |awk '{print $8}' | egrep -i -v 'grep' | cut -d "_" -f3" | sort > /tmp/tmp.log_$i ; done ; paste /tmp/tmp.log* | column -t
crsctl status resource -t|grep -v ora.mgmtdb|grep -v grep|grep ora.*.db|
cut -f2 -d.|
while read line; do echo -e "\033[0;31mDatabase Name: \
033[0;0m"$line
echo -e "\033[0;31mServices: \033[0;0m"`srvctl config database -d
$line|grep Services|awk '{print $2}'`;
echo -e "\033[0;31mServers: \033[0;0m"`srvctl status database -d
$line|awk '{printf "%s.",$7}'`;
done

https://emilianofusaglia.net/2016/04/08/troubleshooting-not-mounting-acfs-file-system/

http://mahioracledba.blogspot.com/2014/01/rootsh-failed-when-installing-11gr2.html

useful when executing asm commands other than oracle user


/2012/02/recommendation-for-the-real-application-cluster-interconnect-and-jumbo-frames/comment-page-1/#comment-4502
s%20resources
omment-4502
Log shipping status? Errors

How much transferred & applied - GAP Detection

Gaps

General health of dataguard &errors


Last applied archive log

LAST PRODUCTION SEQUENCE GENERATED - prod

LAST SEQUENCE RECIEVED FROM PRODUCTION 


and APPLIED ON STANDBY

MRP is in WAIT_FOR_LOG in gv$managed_standby


DGMGRL

which files are applies - Max files

Equivalent Broker Commands to 'ALTER SYSTEM'

Delete OLD applied archive logs on standby database

dgmgrl logging
dgmgrl
Error: ORA-16664: unable to receive the result from a
database
DGMGRL all errors & troubleshoot
dgmgrl log ___location
dataguard switchover validation

database is primary or standby

log_archive_dest_2

is MRP waiting for something ?

MRP apply speed

How to increase MRP apply speed


how long ( Minutes ) will it take to complete the gap

Dataguard switchover :

restoring missing archive log file

OS Level DGMGRL check


OS level GAP check for all dbs in a host
DG Build

standby duplicate using RMAN backupset


select
Run thisdistinct error from gv$archive_dest ;
at Primary
-------------------
set pages 1000
set lines 120
onprimary
column DEST_NAME format a20
--------------
column DESTINATION format
col STBY_BEHIND_BY for a20a35
column ARCHIVER
select (select sysdateformat
from a10
dual)"TIMESTAMP",s.thread#,s.MAX_SEQ#, a.MAX_APP_SEQ#, (s.MAX_SEQ#-
column TARGET format
a.MAX_APP_SEQ#) a15
"Difference" from
column status format a10
( select thread#,max(sequence#) "MAX_SEQ#" from v$archived_log group by thread# ) s,
column error format a15
(select thread#,max(sequence#) "MAX_APP_SEQ#" from v$archived_log where applied='YES' group by
select DEST_ID,DEST_NAME,DESTINATION,TARGET,STATUS,ERROR
thread#) a where a.thread#=s.thread# order by s.thread#; from v$archive_dest
where DESTINATION is NOT NULL
/
select * from v$archive_gap;
select ads.dest_id,max(sequence#) "Current Sequence",
max(log_sequence) "Last Archived"
from v$archived_log al, v$archive_dest ad, v$archive_dest_status ads
where ad.dest_id=al.dest_id and al.dest_id=ads.dest_id group by ads.dest_id;

Run this at Standby


-------------------------
select max(al.sequence#) "Last Seq Recieved" from v$archived_log al
/
select max(al.sequence#) "Last Seq Applied" from v$archived_log al
where applied ='YES'
/
select process,status,sequence# from v$managed_standby
/
select thread#,max(sequence#) from v$log_history group by thread#;

select to_char(sysdate,'dd-mon-yyyy hh24:mi:ss') Date from dual;


SELECT distinct SEQUENCE# "Last Sequence Generated", THREAD# "Thread"
FROM V$ARCHIVED_LOG
WHERE (THREAD#,FIRST_TIME ) IN (SELECT THREAD#,MAX(FIRST_TIME) FROM V$ARCHIVED_LOG
GROUP BY THREAD#)
ORDER BY 1;

SELECT ARCH.THREAD# "Thread", ARCH.SEQUENCE# "Last Sequence Received", APPL.SEQUENCE#


"Last Sequence Applied", (ARCH.SEQUENCE# - APPL.SEQUENCE#) "Difference"
FROM
(SELECT THREAD# ,SEQUENCE# FROM V$ARCHIVED_LOG WHERE (THREAD#,FIRST_TIME ) IN
(SELECT THREAD#,MAX(FIRST_TIME) FROM V$ARCHIVED_LOG GROUP BY THREAD#)) ARCH,
(SELECT THREAD# ,SEQUENCE# FROM V$LOG_HISTORY WHERE (THREAD#,FIRST_TIME ) IN
(SELECT THREAD#,MAX(FIRST_TIME) FROM V$LOG_HISTORY GROUP BY THREAD#)) APPL
WHERE
ARCH.THREAD# = APPL.THREAD#
;

SQL> select * from gv$managed_standby where process like '%MRP%';


SQL> recover managed standby database cancel ;
Media recovery complete.
SQL> recover managed standby database using current logfile disconnect ;
Media recovery complete.
SQL> select * from gv$managed_standby where process like '%MRP%';
show configuration
show database verbose wdbname
show database wdbname InconsistentProperties
edit database mydbname set property LogFileNameConvert='+DATA01/dbprimary/ , +DATA01/dbstandby/' ;

Standby_Side

select max(sequence#) from v$archived_log where applied='YES';


select thread#, max(sequence#) from v$archived_log where applied='YES' group by thread#;

delete force noprompt ARCHIVELOG from sequence 17101 until sequence 20340 thread=1;
delete force noprompt ARCHIVELOG from sequence 16151 until sequence 19560 thread=2;

SQL> alter database recover managed standby database cancel;


DGMGRL> edit database 'stby_dbname' set state='LOG-APPLY-OFF';

SQL> alter database recover managed standby database disconnect;


DGMGRL> edit database 'stby_dbname' set state='ONLINE';

SQL> alter system set log_archive_max_processes=4;


DGMGRL> edit database 'dbname' set property 'LogArchiveMaxProcesses'=4;

SQL> alter system set log_archive_dest_state_2='enable' scope=both;


DGMGRL> edit database 'stby_dbname' set property 'LogShipping'='ON';

SQL> alter system set log_archive_dest_state_2='defer' scope=both;


DGMGRL> edit database 'stby_dbname' set property 'LogShipping'='OFF';

DGMGRL> edit database 'pri_dbname' set state='LOG-TRANSPORT-OFF';


This will defer all standby databases

select 'delete archivelog until sequence '||max(sequence#)||' thread '||thread#||' ; '


from gv$archived_log
where applied='YES'
group by thread#
order by 1
/

dgmgrl -logfile observer.log / "start observer"

copy the password file from prod to standby


https://www.toadworld.com/platforms/oracle/w/wiki/11143.monitoring-troubleshooting-data-guard-using-broker
same as alert log ___location --> file name drcp<sid>.log
https://www.pythian.com/blog/database-validation-in-data-guard-12c/

select database_role from v$database;

On Primary database the value of controlfile_type in V$database is “CURRENT” and standby is “STANDBY”

SQL> SELECT controlfile_type FROM V$database;

alter system set log_archive_dest_1 = '___location=use_db_recovery_file_dest valid_for=(all_logfiles, all_roles)


db_unique_name=primarydbname';
ALTER DATABASE
alter system RECOVER MANAGED STANDBY DATABASE ASYNC
set log_archive_dest_2='service="stbydbname",LGWR PARALLEL 8 DISCONNECT
NOAFFIRM FROM
delay=0 optional
SESSION;
compression=disable max_failure=0 max_connections=1 reopen=300 valid_for=(all_logfiles,primary_role)
db_unique_name="stbydbname"';
DGMGRL> show database STBY maxconnections;
MaxConnections = '8'
select
SQL> a.event, a.wait_time,
show parameter a.seconds_in_wait from gv$session_wait a, gv$session b where a.sid=b.sid and
log_archive_max_processes
b.sid=(select
NAME SID from v$session
TYPE where PADDR=(select PADDR from v$bgprocess where NAME='MRP0'))
VALUE
------------------------------------
set lines 1000 pages 9999 ----------- ------------------------------
log_archive_max_processes
select to_char(START_TIME,'DD-MON-YYYY integer 8HH24:MI:SS') "Recovery Start Time",to_char(item)||' = '||
to_char(sofar)||' '||to_char(units) "Progress"
DGMGRL> edit database STBY
from v$recovery_progress whereset property maxconnections=30;
start_time=(select max(start_time) from v$recovery_progress);
Property "maxconnections" updated

DGMGRL> show database STBY maxconnections;


MaxConnections = '30'

SQL> show parameter log_archive_max_processes


NAME TYPE VALUE
------------------------------------ ----------- ------------------------------
log_archive_max_processes integer 30

Now check the MRP Active apply speed


--------------------------------------
select to_char(START_TIME,'DD-MON-YYYY HH24:MI:SS') "Recovery Start Time",to_char(item)||' = '||
to_char(sofar)||' '||to_char(units) "Progress"
from gv$recovery_progress where start_time=(select max(start_time) from v$recovery_progress);
between (select max(sequence#) "MAX_APP_SEQ#" from v$archived_log where applied='YES' and
thread#=2 )
and (select max(sequence#) "MAX_SEQ#" from v$archived_log where thread#=2)) b ,
(select sum(round(blocks*block_size/1024/1024)) MB from v$archived_log where dest_id=1 and thread#=3
and sequence#
between (select max(sequence#) "MAX_APP_SEQ#" from v$archived_log where applied='YES' and
thread#=3 )
and (select max(sequence#) "MAX_SEQ#" from v$archived_log where thread#=3)) c ,
(select sum(round(blocks*block_size/1024/1024)) MB from v$archived_log where dest_id=1 and thread#=4
and sequence#
between (select max(sequence#) "MAX_APP_SEQ#" from v$archived_log where applied='YES' and
thread#=4 )
and (select max(sequence#) "MAX_SEQ#" from v$archived_log where thread#=4)) d;

standby ( average apply rate . EX: 4 MB/s )


------------
set lines 1000 pages 9999
select to_char(START_TIME,'DD-MON-YYYY HH24:MI:SS') "Recovery Start Time",to_char(item)||' = '||
to_char(sofar)||' '||to_char(units) "Progress"
from gv$recovery_progress where start_time=(select max(start_time) from v$recovery_progress);

so total time taken


--------------------
select totalMB/ ( Applyrate * 60 ) "Mins" from dual ;

execute this on primary


ALTER DATABASE COMMIT TO SWITCHOVER TO PHYSICAL STANDBY WITH SESSION SHUTDOWN;

run
{
set archivelog destination to '/ora_backup/rman/arch/';
restore archivelog from logseq=8619 until logseq=8632 thread=2;
}

for i in `ps -ef|grep pmon | awk '{print $8}'|grep -v "grep"| grep -v "ASM"| cut -d"_" -f3`
do
export ORACLE_SID=$i
dgmgrl -silent / "show configuration verbose" ; echo '------------------------------------'
done
for i in `ps -ef|grep pmon | awk '{print $8}'|grep -v "grep"| grep -v "ASM"| cut -d"_" -f3`
do
export ORACLE_SID=$i
sqlplus -s /nolog <<EOF
set head off echo off feedback off
conn / as sysdba
set lines 160
select instance_name,logins,(select database_role from v\$database) database from v\$instance;
select PROCESS,status from gv\$managed_standby where process like '%MRP%';
col STBY_BEHIND_BY for a20
select (select sysdate from dual)"TIMESTAMP",s.thread#,s.MAX_SEQ#, a.MAX_APP_SEQ#, (s.MAX_SEQ#-
a.MAX_APP_SEQ#) "Difference" from
( select thread#,max(sequence#) "MAX_SEQ#" from v\$archived_log group by thread# ) s,
(select thread#,max(sequence#) "MAX_APP_SEQ#" from v\$archived_log where applied='YES' group by
thread#) a where a.thread#=s.thread#;
set serveroutput on
exec dbms_output.put_line('------------------------------');
exit
EOF
done
primary
-----------

dgmgrl /
connect sys/pwd
CREATE CONFIGURATION 'DR' AS PRIMARY DATABASE IS 'india' CONNECT IDENTIFIER IS 'india';
ADD DATABASE 'america' AS CONNECT IDENTIFIER IS 'america' maintained as physical;
Enable configuration

show configuration ;
show database verbose india
show database verbose america

sid +ASM
cd $ORACLE_HOME/network/admin
cp listener.ora listener.ora.11142017

add this static entry in the listener.ora file

(SID_DESC=
(SID_NAME= america2)
(GLOBAL_DBNAME= america_dgmgrl)
(ORACLE_HOME=/ORACLE_HOME)
(ENVS="TNS_ADMIN=/ASM_HOME/network/admin")
)

else it will throw error while swithover. it will start only one instance during switover if it is not added.
please add this entry and reload the listener

dgmgrl /

connect sys/pwd
switchover to america;

connect sys/pwd
switchover to india;

RMAN>
echo set on
run {
allocate channel c1 device type disk;
allocate auxiliary channel a1 device type disk;
allocate auxiliary channel a2 device type disk;
duplicate database for standby from active database using backupset nofilenamecheck;
}
http://sanzdbaworld.blogspot.com/2012/09/how-query-dataguard-status-physical.html

onprimary
--------------
select a.thread#, (select max (sequence#) from v$archived_log where
archived='YES' and thread#=a.thread#) archived,
max(a.sequence#) applied, (select max(sequence#) from v$archived_log where
archived='YES' and thread#=a.thread#)-max(a.sequence#) gap
from v$archived_log a where a.applied='YES' group by a.thread# order by
thread#;

select sequence#,ARCHIVED AS RECEIVED,applied from v$archived_log where applied='NO' order by sequence#;

The status should be APPLYING_LOG


to check inconsistency if any errors

run{
crosscheck archivelog all;
delete noprompt expired archivelog all;
delete noprompt archivelog all completed before 'sysdate - 1/24';
}

http://www.ritzyblogs.com/OraTalk/PostID/105/How-to-setup-DGMGRL-broker-with-example

<-- execute this in RMAN


The DB_UNIQUE_NAME must be specified right after the service name:

alter system set log_archive_dest_2 = 'SERVICE="PROD_STDBY", LGWR


ASYNC VALID_FOR=(ONLINE_LOGFILES,PRIMARY_ROLE)
DB_UNIQUE_NAME=PROD_STDBY';

if you want to increase the transport speed, increase the value in primary
database also .

https://www.toadworld.com/platforms/oracle/w/wiki/11334.let-s-optimize-data-
guard-configuration-I

http://emrebaransel.blogspot.com/2008/11/dataguard-performance.html
for i in `ps -ef|grep pmon | awk '{print $9}'|grep -v "grep"| grep -v "ASM"| cut -d"_"
-f3`
do
export ORACLE_SID=$i
dgmgrl -silent / "show configuration verbose" ; echo '------------------------------------'
done
NO' order by sequence#;
Sessions

Total user count on database

Users Details Session

v$sql_monitor

Sql-Monitor report for a sql_id ( Like OEM report)

Sid Level Debug

Long Running query - long ops

Wait event for a SID

RealTime Monitoring for sid

Sql details

Currently running SQL query's


Currently running SQL query's

RealTime Monitoring for sql_id

SQL History

Identify

statistics of objects of a specific sql id

Sql id current rows, I/O , read/wrire details

Check the progress of DML statements

Detailed history of SQL_ID

Sql Hanging or not

SQL to show the full SQL executing for active sessions


wait events

Database level Wait ratios/Events

Events Drilled down %

wait event for past 5 mins / 30 mins/ 1 hour

wait events for a sql_id

Wait event for objects in active session history

Explain Plan
explain plan for manual session

explain plan for sql id present/history

Process

Finding SID for a PID

Finding OS pid for a db sid

Finding db sid from OS spid

Finding own sid & serial number

Killing Sessions

Killing Own session

kill a sid
Killing old session ( 1 day old) (or) 4 hours

OS level killing old session for database

Determine If Killed Session Is Rolling Back Transactions

Extra

CPU/REDO/PGA/READ/WRITE used by a SID

Cursor Value for a SID (All Sql query executed by SID )

Maximum no of session in the database


Cheking all sql from a user

wait event currently- ON CPU

command to purge explain plan for a specific program...

Enable Parallelism in session level

parallelism Hints

Uncommited transactions in the database

SQL Profiles & Baselines

sql patch

Sql Profiles
Sql Baselines

extract hint from all profile/baseline/patch - single script

Fixing the PLAN HASH VALUE

purge the old plan hash value from memory

Sql_doctor script
break on report
compute SUM of tot on report
set linesize
compute SUM750ofpages 9999
active9999on report
set lines
column box1000
formatpages a30
compute
column SUM
sid of inactive on report
column
col usernamespidformat
format
for
9999
a50 a10
column
column serial
usernamefor 999999
format a30
select
column status format a15
column program format a30
DECODE(username,NULL,'INTERNAL',USERNAME)
column
column username
os_user format
format a20a10
Username,
column sql_text format a80
col LOGON_TIME
count(*) TOT, for a20
column module format a30
col COUNT(DECODE(status,'ACTIVE',STATUS))
program for a30
select
ACTIVE, b.inst_id,b.sid,b.serial#,a.spid,
col SQL_EXEC_STARTbox,to_char
substr(b.machine,1,30) for a20 (b.logon_time, 'dd-
COUNT(DECODE(status,'INACTIVE',STATUS))
mon-yyyy
INACTIVE hh24:mi:ss') logon_time,
SELECT * FROM
substr(b.username,1,30) username,
from gv$session
(SELECT status,inst_id,sid,SESSION_SERIAL#
substr(b.osuser,1,20)
where os_user,
status in ('ACTIVE','INACTIVE')
as Serial,username,sql_id,SQL_PLAN_HASH_VALUE,
substr(b.program,1,30) program,status,b.last_call_et
group by username;
AS MODULE,program,
last_call_et_secs,b.sql_id set lines 1000 pages 9999
from TO_CHAR(sql_exec_start,'dd-mon-yyyy
gv$session b,gv$process a column
set pages sid50000
formatlines999932767
hh24:mi:ss')
where b.paddr AS=sql_exec_start,
a.addr column
col OPNAME serial for
for 999999
a10
ROUND(elapsed_time/1000000)
and a.inst_id = b.inst_id AS <-- For cluster
column
col SID formstatus format
9999 a15
"Elapsed (s)",
and type='USER'
ROUND(cpu_time /1000000) AS col SERIAL form 9999999a20 for standalone -->
column username format
order
set by logon_time;
linesize 750 pages 9999 column
col PROGRAMsql_text for format
a10 a80
"CPU (s)",
column box format a30 col USERNAME
col program for a33 for a10
substr(sql_text,1,30) sql_text
column spid format a10 col
col SQL_EXEC_START
SQL_TEXT for a40 for a20
FROM gv$sql_monitor where
column
column username
text_line formatformata254a20 col START_TIME for a10
status='EXECUTING' and module not like '%emagent overall -->
column
set program format a30 SELECT
col * FROM
LAST_UPDATE_TIME for a10
%' lines 750 pages 9999 set pagesize
<-- ONLY 0 echo off timing
EXECUTING off linesize 1000
column
set long os_user
20000 format a20 20000 col (SELECT
TARGET status,inst_id,sid,SESSION_SERIAL#
for a25
ORDER BYlongchunksize
sql_exec_start desc trimspool on trim on long 2000000 longchunksize
col LOGON_TIME for a20
select as
col MESSAGE for a25
2000000
);
dbms_sqltune.report_sql_monitor_list() text_line Serial,username,sql_id,SQL_PLAN_HASH_VALUE,p
alter
selectsession set nls_date_format = 'DD-MM-YYYY
select
from dual; b.inst_id,b.sid,b.serial#,a.spid, rogram,
HH24:MI:SS';
DBMS_SQLTUNE.REPORT_SQL_MONITOR(
substr(b.machine,1,30) box,to_char (b.logon_time, 'dd- SELECT TO_CHAR(sql_exec_start,'dd-mon-yyyy
inst_id,sid, serial#, sql_id, opname,
sql_id=>'&sql_id',
mon-yyyy
select hh24:mi:ss') logon_time, hh24:mi:ss')
username, AS sql_exec_start,
target,
report_level=>'ALL', sofar, totalwork,
substr(b.username,1,20)
dbms_sqltune.report_sql_monitor() username,text_line COLUMN username FORMAT A20
ROUND(elapsed_time/1000000)
start_time,last_update_time,round(time_remaining/60
type=>'TEXT')
substr(b.osuser,1,20)
from dual; os_user, COLUMN
AS
,2)
from dual; sid(s)",
"Elapsed
"REMAIN FORMAT
MINS", 9999
round(elapsed_seconds/60,2)
substr(b.program,1,30) program,status,b.last_call_et
SELECT COLUMN
"ELAPSED
SELECT serial#
ROUND(cpu_time
MINS", FORMAT
ROUND(elapsed_time 9999 /1000000) ASAS
/1000000)
gv$session gv$sql_monitor
AS last_call_et_secs,b.sql_id
a.sid,RPAD(a.opname,30),a.sofar,a.totalwork,a.ELAPS COLUMN
"CPU (s)", event FORMAT A40
round((time_remaining+elapsed_seconds)/60,2)
"Elapsed (s)",
from gv$session b,gv$process a
ED_SECONDS,ROUND(((a.sofar)*100)/a.totalwork,3) "TOTAL substr(sql_text,1,30)
MINS",
ROUND(cpu_time sql_text
/1000000,3) AS "CPU
where b.paddr
"%_COMPLETED",
SELECT * = a.addr SELECTFROM NVL(s.username,
gv$sql_monitor '(oracle)')
ROUND(SOFAR/TOTALWORK*100,2)
(s)", where moduleAS username,
not like
col
and WAIT_CLASS
a.inst_id = b.inst_id
RPAD(a.username,10)
FROM for a10 s.sid,
'%emagent%'
"%_COMPLETE", and
ROUND(queuing_time sid=&sid
message /1000000,3) AS
SELECT
and sw.inst_id,NVL(s.username,
type='USER' and b.sid=&sid '(oracle)') AS
username,a.SQL_HASH_VALUE,B.STATUS
(SELECT status, FROM s.serial#,
ORDER
"Queuing (s)",BY sql_exec_start desc
gv$session_longops
username,
order by
FROM--username,logon_time;
gV$SESSION_LONGOPS a, gv$session b WHERE se.event,
); OPNAME NOT LIKE 'RMAN%'
ROUND(user_io_wait_time AND AS
/1000000,3)
WHERE s.sid,a.sid=b.sid
sql_id, "I/O se.total_waits,
OPNAMEwait (s)",NOT LIKE '%aggregate%' AND
s.serial#,
and a.sid=&sid
sql_exec_id, se.total_timeouts,
TOTALWORK != 0 AND sofar<>totalwork AND AS
ROUND(application_wait_time/1000000,3)
--AND sw.event,
b.status='ACTIVE'
TO_CHAR(sql_exec_start,'dd-mon-yyyy se.time_waited,
time_remaining
"Appli wait (s)", > 0
ANDsw.wait_class,
a.sofar<>
hh24:mi:ss') ASa.totalwork
sql_exec_start, se.average_wait,
/ ROUND(concurrency_wait_time/1000000,3) AS
/ sw.wait_time,
ROUND(elapsed_time/1000000) AS se.max_wait,
"Concurrency wait (s)",
"Elapsedsw.seconds_in_wait,
Currently (s)",
waiting ? se.time_waited_micro
ROUND(cluster_wait_time
Overall Waits /1000000,3) AS
sw.state
ROUND(cpu_time /1000000) AS FROM
"Cluster v$session_event
wait (s)", se,
FROM
"CPU (s)", gv$session_wait sw, v$session s
ROUND(physical_read_bytes /(1024*1024)) AS
gv$session
buffer_gets, s WHERE
"Phys reads s.sid = se.sid
(MB)",
WHERE s.sid = sw.sid and s.inst_id=sw.inst_id
ROUND(physical_read_bytes and
/(1024*1024)) AS AND s.sid = &Session_ID
ROUND(physical_write_bytes /(1024*1024)) AS
s.sid=&sid
"Phys reads (MB)", ORDER
"Phys writes BY se.time_waited
(MB)", DESC
ORDER BY sw.seconds_in_wait DESC;
ROUND(physical_write_bytes/(1024*1024)) AS / buffer_gets AS "Buffer gets",
Elapsed/CPU/Read/Write
"Phys writes (MB)" MB Each Layer time spend
ROUND(plsql_exec_time/1000000,3) AS
FROM gv$sql_monitor where sid=&sid and "Plsql exec (s)",
inst_id=&inst_id ROUND(java_exec_time /1000000,3) AS
ORDER BY elapsed_time DESC "Java exec (s)"
) FROM gv$sql_monitor
WHERE rownum<=20; WHERE sid=&sid and inst_id=&inst_id;

v$sqlarea/v$sql ASH
/ 1e6, 3), '999,990.000') et_secs_per_exec, TO_CHAR(ROUND(h.clwait_total /
SECS,b.rows_processed,a.status,substr(b.sql_text,1,5
TO_CHAR(ROUND(h.cpu_time / h.executions / column my_blkr format
sql_exec_id,
h.executions_total / 1e6,9993), '999,990.000')
0) sql_text
1e6, 3), '999,990.000') cpu_secs_per_exec, select to_char(a.sample_time,
TO_CHAR(sql_exec_start,'dd-mon-yyyy
cl_secs_per_exec,
select sql_id, 'HH24:MI:SS')
fromTO_CHAR(ROUND(h.USER_IO_WAIT_TIME
gv$session a,gv$sqlarea b / MY_TIME,a.session_id
hh24:mi:ss') AS MY_SID,a.session_serial#
sql_exec_start,
TO_CHAR(ROUND(h.apwait_total
starting_time, /
where a.sql_hash_value
h.executions = b.hash_value
/ 1e6, 3), '999,990.000') MY_SER, ROUND(elapsed_time/1000000)
h.executions_total
end_time, / 1e6, 3), '999,990.000')
and a.sql_address = b.address
io_secs_per_exec, AS DECODE(a.session_state,
"Elapsed
ap_secs_per_exec,
(EXTRACT(HOUR (s)", FROM run_time) 'WAITING'
* 3600,a.event,
and TO_CHAR(ROUND(h.CLUSTER_WAIT_TIME
a.module not like '%emagent%' / a.session_state)
ROUND(cpu_time MY_STATE,a.xid,
TO_CHAR(ROUND(h.ccwait_total /1000000)
+ EXTRACT(MINUTE FROM a.sql_id,
/ run_time) AS
and a.module/ 1e6,
h.executions not like
3), '%oraagent.bin%'
'999,990.000') "CPU a.blocking_session
(s)",
h.executions_total
* 60 / 1e6, MY_BLKR
3), '999,990.000')
and sql_text not like '%b.PARSING_SCHEMA_NAME
cl_secs_per_exec, from gv$active_session_history
buffer_gets,
cc_secs_per_exec, + EXTRACT(SECOND a, dba_users
FROM u
%' pagesize
set 0 echo off timing off linesize 1000
TO_CHAR(ROUND(h.APPLICATION_WAIT_TIME where u.user_id = a.user_id
ROUND(physical_read_bytes
TO_CHAR(ROUND(h.plsexec_time_total
run_time))/60 run_time_MIN, /(1024*1024)) / AS
and a.username
trimspool
/ h.executions on trim is
/ 1e6,onnot3),null
long 2000000 longchunksize
'999,990.000') and
"Phys a.sql_id = '&sql_id'
reads (MB)",
h.executions_total
READ_IO_BYTES, / 1e6, 3), '999,990.000')
order by a.status;
2000000
ap_secs_per_exec, and a.sample_time
pl_secs_per_exec,
PGA_ALLOCATED > SYSTIMESTAMP-(2/1440);
ROUND(physical_write_bytes/(1024*1024))
PGA_ALLOCATED_BYTES, AS
select TO_CHAR(ROUND(h.CLUSTER_WAIT_TIME
Sql_monitor report / "Phys writes (MB)"
TO_CHAR(ROUND(h.javexec_time_total
Elapsed/CPU/Read/Write
TEMP_ALLOCATED MB /
DBMS_SQLTUNE.REPORT_SQL_MONITOR(
h.executions / 1e6, 3), '999,990.000') col index_name
h.executions_total for/ a50
FROM gv$sql_monitor 1e6, 3),where sql_id='&sql_id'
'999,990.000')
TEMP_ALLOCATED_BYTES
SELECT owner, index_name,
sql_id=>'&sql_id',
cc_secs_per_exec, and inst_id=&inst_id
ja_secs_per_exec
from (
report_level=>'ALL',
TO_CHAR(ROUND(h.PLSQL_EXEC_TIME / table_name,last_analyzed,
FROMORDER BY elapsed_time
dba_hist_sqlstat h, sample_size,
DESC num_rows,
select
partitioned, global_stats
type=>'TEXT')
h.executions / 1e6, 3), '999,990.000') )sql_id,
dba_hist_snapshot s
from dual;
pl_secs_per_exec, FROM WHERE
WHERE dba_indexes
rownum<=20;
h.sql_id = '&sql_id'
WHERE max(sample_time
index_name IN- (sql_exec_start) run_time,
All inTO_CHAR(ROUND(h.JAVA_EXEC_TIME
one / AWR AND h.executions_total
data
max(sample_time) >0
end_time,
h.executions / 1e6, 3), '999,990.000') select
AND distinct
s.snap_idrtrim(substr(plan_table_output,
= h.snap_id
sql_exec_start
instr(plan_table_output, starting_time,
ja_secs_per_exec AND s.dbid = h.dbid '|', 1, 3)+2,
sum(DELTA_READ_IO_BYTES)
set lines gv$sqlarea_plan_hash
FROM 300 set pages 300 h (instr(plan_table_output,
AND s.instance_number '|',=1,h.instance_number
4)-
col table_name for=a40 READ_IO_BYTES,
instr(plan_table_output, '|', 1, 3)-2)), ' ')
WHERE h.sql_id '&&sql_id' ORDER BY
sum(DELTA_PGA) PGA_ALLOCATED,
colANDowner for a30 > 0
h.executions froms.begin_interval_time,
(
set long 20000
sum(DELTA_TEMP) TEMP_ALLOCATED
select distinct
order by source owner,
; table_name, STALE_STATS, SELECT plan_table_output
set s.end_interval_time;
lines
from 750 pages 9999
last_analyzed, stattype_locked FROM
select( sql_text from dba_hist_sqltext where sql_id =
sql_id sql_text
colfrom dba_tab_statistics
exact_matching_signature for TABLE(DBMS_XPLAN.DISPLAY_CURSOR('&sql_id'
'&SQL_ID';
where (owner, table_name) in
99999999999999999999999999 , null,select sql_id,
'BASIC'))
(select distinct owner, table_name UNIONsample_time,
ALL
col sql_text for a50 set long 20000
sql_exec_start,
from dba_tables
select sql_id, exact_matching_signature, SQL_TEXT SELECT
set lines * FROM
750 pages 9999
where ( table_name) DELTA_READ_IO_BYTES,
TABLE(dbms_xplan.display_awr('&sql_id', null,
from v$sqlarea where UPPER(sql_text) like '%DUMMY selectsql_exec_id,
sql_text from gv$sqlarea where sql_id = null,
in ( select object_name 'ALL'))
%' order by UPPER(sql_text); '&SQL_ID';
col sql_textfrom for a60gv$sql_plan ) greatest(PGA_ALLOCATED -
where upper(sql_id) first_value(PGA_ALLOCATED) over (partition by
SELECT rows_processed "Total=Rows
upper('&sql_id')
Processed", and where plan_table_output like '%INDEX%'
sql_id,sql_exec_id order by sample_time rows 1
object_name is not null))
ROUND((SYSDATE - TO_DATE(first_load_time, )
--and STALE_STATS='YES' preceding),0)
ORDER BY owner, DELTA_PGA,
table_name, index_name
'yyyy-mm-dd hh24:mi:ss')) * 24 * 60, 1) "Total Time greatest(TEMP_SPACE_ALLOCATED -
/(Min)", /
select first_value(TEMP_SPACE_ALLOCATED) over
TRUNC(rows_processed /((SYSDATE - (partition by sql_id,sql_exec_id order by sample_time
SQL_ID,PLAN_HASH_VALUE,ELAPSED_TIME,PHYS
TO_DATE(first_load_time, 'yyyy-mm-dd hh24:mi:ss')) *
ICAL_READ_BYTES,PHYSICAL_WRITE_BYTES,DIS rows
select1sql_text,rows_processed
preceding),0) DELTA_TEMP from v$sql
24 * 60)) "Rows/Min",
K_READS,DIRECT_WRITES,BUFFER_GETS,ROWS
TRUNC(rows_processed /((SYSDATE - wherefrom USERS_EXECUTING>0;
_PROCESSED from v$sqlstats where sql_id='&sql_id'; dba_hist_active_sess_history
TO_DATE(first_load_time, 'yyyy-mm-dd hh24:mi:ss')) * where
24 * 60 * 60)) "Rows/Sec" , SUBSTR(sql_text, 1, 60) sample_time >= trunc(sysdate)
sql_text --and sample_time < to_date ('2013/04/16
FROM
select gv$sqlarea
sess_io.inst_id, 03:10:00','YYYY/MM/DD HH24:MI:SS')
WHERE SQL_ID='&SQL_ID'
sess_io.sid, and sql_exec_start is not null
AND open_versions
sesion.sql_id,
select instance_number >0 selectand sess_io.inst_id,
IS_SQLID_CURRENT='Y'
AND rows_processed
sess_io.block_gets, > 0;
inst_id,SESSION_ID,USER_ID,PROGRAM,sql_id,SQL sess_io.sid,
)
sess_io.consistent_gets,
_CHILD_NUMBER,sql_plan_hash_value,to_char groupsess_io.block_gets,
by sql_id,SQL_EXEC_ID,sql_exec_start
sess_io.physical_reads,
(sql_exec_start, 'dd-Mon-yyyy hh24:mi:ss') ordersess_io.consistent_gets,
by sql_id
sess_io.block_changes,
sql_exec_start from ) sess_io.physical_reads,
sess_io.consistent_changes where
dba_hist_active_sess_history wheresess_io.block_changes,
sql_id = '&sql_id'
from gv$sess_io sess_io, gv$session sesion
sql_id='&sql_id'; ordersess_io.consistent_changes
by sql_id, run_time_MIN desc;
where sesion.sid = sess_io.sid and from gv$sess_io sess_io, gv$session sesion
sess_io.inst_id
select = sesion.inst_id
sesion.sid,sql_text and
from v$sqltext sqltext, where sesion.sid = sess_io.sid and
sesion.sql_id='&sql_id'
v$session sesion where sesion.sql_hash_value = sess_io.inst_id = sesion.inst_id
and sesion.username
sqltext.hash_value andissesion.sql_address
not null ; = and sesion.username
select a.sid,b.sql_fulltextisfrom not null ;
V$Session a,
sqltext.address and sesion.username is not null V$SQLAREA b where a.sql_id=b.sql_id and
order by sqltext.piece; a.status='ACTIVE';
SELECT WAIT_CLASS,
TOTAL_WAITS,
round(100 * (TOTAL_WAITS / SUM_WAITS),2)
PCT_TOTWAITS,
ROUND((TIME_WAITED / 100),2)
TOT_TIME_WAITED,
SET lines 750
round(100 pages 10000 / SUM_TIME),2)
* (TIME_WAITED
COLUMN
PCT_TIMEwait_class format a30
COLUMN
FROM event format a60
COLUMN total_waits format 999999
(select WAIT_CLASS,
Wait Ratio COLUMN
TOTAL_WAITS,total_us%format
Wait Percentage (Only999999999
wait events-NO CPU)
COLUMN
TIME_WAITED pct_time format 99.99
SELECT METRIC_NAME, VALUE COLUMN avg_us format 999999.99
FROM V$SYSTEM_WAIT_CLASS
FROM V$SYSMETRIC SET
WHERE echoWAIT_CLASS
on != 'Idle'),
WHERE METRIC_NAME IN ('Database CPU Time (select sum(TOTAL_WAITS) SUM_WAITS,
set lines 750 pages 9999
Ratio', SELECT wait_class,SUM_TIME
sum(TIME_WAITED) event, total_waits AS waits,
col OBJECT_NAME
'Database Wait Time forRatio')
a35 AND from V$SYSTEM_WAIT_CLASS / 1000) AS
ROUND (time_waited_micro
select * from
INTSIZE_CSEC = ( total_ms,
where WAIT_CLASS != 'Idle')
SELECT
(select max(INTSIZE_CSEC) from V$SYSMETRIC); ORDER ROUND (time_waited_micro
BY PCT_TIME DESC; * 100 / SUM
A.inst_id, (time_waited_micro) OVER (),
A.CURRENT_OBJ#, 2
D.OBJECT_NAME, ) AS pct_time,
A.SQL_ID,
select ROUND ((time_waited_micro / total_waits) /
D.OBJECT_TYPE,
event, 1000, 2) AS avg_ms
A.EVENT,
time_waited "time_waited(s)", FROM v$system_event
SUM(A.WAIT_TIME
case when time_waited + A.TIME_WAITED)
= 0 then WHERE wait_class <> 'Idle'
TOTAL_WAIT_TIME
0 ORDER BY time_waited_micro DESC;
FROMelse
gV$ACTIVE_SESSION_HISTORY
SELECT round(time_waited*100
NVL(a.event, 'ON CPU') ASA,event,
/ sum(time_waited) SELECT NVL(a.event, 'ON CPU') AS event,
DBA_OBJECTS
Over(), 2)
COUNT(*) ASDtotal_wait_time COUNT(*) AS total_wait_time
WHERE
FROMend "percentage"
v$active_session_history a FROM v$active_session_history a
A.CURRENT_OBJ#
from
WHERE a.sample_time= D.OBJECT_ID
> SYSDATE - 5/(24*60) -- 5 WHERE a.sample_time > SYSDATE - 60/2880 -- 30
GROUP
mins( BY mins
A.inst_id,
GROUP select
BYevent, sum(time_waited) time_waited
a.event GROUP BY a.event
A.CURRENT_OBJ#,
ORDER fromBY v$active_session_history
total_wait_time DESC; ORDER BY total_wait_time DESC;
D.OBJECT_NAME,
where sql_id = '&SQL_ID'
A.SQL_ID,
group by event
D.OBJECT_TYPE,
) <-- shared pool (current)
A.EVENT
order by
ORDER BY
time_waited desc; From AWR -->
TOTAL_WAIT_TIME DESC
)
where rownum<=20
/
SELECT * FROM
" @?/rdbms/admin/utlxplp.sql
TABLE(DBMS_XPLAN.DISPLAY('','','ALLSTATS
(or)
LAST +OUTLINE +PEEKED_BINDS +PROJECTION
SELECT * FROM
+ALIAS +PREDICATE +COST +BYTES'));
TABLE(DBMS_XPLAN.DISPLAY('','','+COST +BYTES
-PREDICATE'));
SELECT * FROM
TABLE(DBMS_XPLAN.DISPLAY_CURSOR('&sql_id',
&childnumber,'ALLSTATS LAST +PEEKED_BINDS
+PROJECTION +ALIAS +OUTLINE +PREDICATE
+COST +BYTES'));
(OR)
select * from
table(dbms_xplan.display_cursor('&sql_id',&childnumb <-- shared pool (current)
er,'ADVANCED'));
From AWR -->
select s.sid, s.serial#, s.username,
select spid,p.pid, s.sid, s.serial#, p.program from
to_char(s.logon_time,'DD-MON
v$session HH24:MI:SS')
s, v$process p where paddr=addr and
logon_time,
p.pid=30849 order by p.pid;
p.pid oraclepid, p.spid "ServerPID", s.process
"ClientPID",
select spid "host-pid",p.pid,
s.program clientprogram,s.sid, s.serial#,
s.module, p.program,
s.machine,
s.machine
s.osuser, from gv$session s, gv$process p where
paddr=addr and s.sid=&sid
s.status, s.last_call_et order by p.pid; <-- Killing a session ( Good Query )
from gv$session s, gv$process p
where p.spid=nvl('&unix_process',' ')
and s.paddr=p.addr
order
selectby s.sid
sys_context ( 'USERENV' , 'SID' ) OwnSID from
dual;
select sys_context('USERENV','SESSION_USER')
current_user,sys_context('USERENV','SESSION_SCH
EMA') current_schema from dual; select distinct sid OwnSID from v$mystat;

alter session set events 'immediate crash';

select 'alter system kill session ' || '''' || sid || ',' || serial#
||',@'|| inst_id || '''' || ' immediate;' from gv$session
where sid='&sid';
(SELECT ROUND (VALUE / 1024 / 1024, 2)
FROM v$sesstat
WHERE STATISTIC# = 83 AND v$sesstat.SID
= v$session.sid)
AS "Physical read bytes, in MB",
(SELECT ROUND (VALUE / 1024 / 1024, 2)
FROM v$sesstat
WHERE STATISTIC# = 96 AND v$sesstat.SID
= v$session.sid)
AS "Physical write bytes, in MB",
(SELECT ROUND (VALUE / 1024 / 1024, 2)
FROM v$sesstat
WHERE STATISTIC# = 185 AND v$sesstat.SID
= v$session.sid)
AS "Redo size, in MB",
(SELECT ROUND (VALUE / 1024 / 1024, 2)
FROM v$sesstat
WHERE
select ' alter systemSTATISTIC#
kill session = 590 AND v$sesstat.SID
'''||sid||''','''|| select ' alter system kill session '''||sid||','||serial#||',@'||
= v$session.sid)
serial#||''',''@'||inst_id||''' immediate; ' inst_id||''' immediate; ' -- 4 hours
AS "Received
from gv$session where from client, ininMB",
username from gv$session where username in
(SELECT ROUND (VALUE
('SCHEMA1','SCHEMA2') and logon_time / 1024 / 1024, 2) -1
< sysdate ('SCHEMA1','SCHEMA2','SCHEMA3') and
FROM v$sesstat
and status='INACTIVE'; status='INACTIVE' and last_call_et > 4*60*60;
WHERE STATISTIC# = 589 AND v$sesstat.SID
= v$session.sid)
AS "Sent to client, in MB",
SID,
SERIAL#,
v$session.STATUS,
PROGRAM,
USER#, Then kill the old sessions using kill -9 spid
USERNAME, kill -9 `ps -ef|grep LOCAL=NO|grep oratst1|awk '{print
ps -efCOMMAND,
| grep "oracleinstname (LOCAL=NO)" $2}'`
OWNERID,
OSUSER,
PROCESS,
SELECTMACHINE,
a.sid, a.username, b.xidusn rollback_seg_no,
OBJECT_NAME
b.used_urec undo_records, b.used_ublk undo_blocks
FROMFROM v$session
gv$session a, gv$transaction b
WHERE LEFT OUTER
a.saddr JOIN
= b.ses_addr;
DBA_OBJECTS
ON v$session.ROW_WAIT_OBJ# =
dba_objects.object_ID
WHERE v$session.LOGON_TIME BETWEEN
TRUNC
SELECT(SYSDATE) AND SYSDATE
A.SNAP_ID,A.INSTANCE_NUMBER
AND v$session.sid = &sid;
"ID",B.BEGIN_INTERVAL_TIME,B.END_INTERVAL_T
IME,A.RESOURCE_NAME,
CURRENT_UTILIZATION
SELECT o.sid,
"CURRENT",MAX_UTILIZATION
o.sql_text, "MAX"
FROM WRH$_RESOURCE_LIMIT
o.address, A,
WRM$_SNAPSHOT
o.hash_value, B
WHERE A.RESOURCE_NAME LIKE '%session%'
o.user_name,
ANDs.schemaname,
A.SNAP_ID=B.SNAP_ID
ANDo.sql_id
A.INSTANCE_NUMBER=
B.INSTANCE_NUMBER
FROM v$open_cursor o, v$session s
AND
WHERE((A.INSTANCE_NUMBER=1
o.saddr = s.saddr AND o.sid = s.sid AND
AND
(O.SIDB.BEGIN_INTERVAL_TIME
= &sid) > (SELECT
STARTUP_TIME FROM GV$INSTANCE WHERE
INSTANCE_NUMBER=1)) OR
(A.INSTANCE_NUMBER=2 AND
B.BEGIN_INTERVAL_TIME >
(SELECT STARTUP_TIME FROM GV$INSTANCE
WHERE INSTANCE_NUMBER=2)))
order by A.INSTANCE_NUMBER,A.SNAP_ID;
AND status = 'ACTIVE'
GROUP BY
CASE WHEN state != 'WAITING' THEN
'WORKING'
ELSE 'WAITING'
END,
CASE WHEN state != 'WAITING' THEN 'On CPU /
SELECT SQL_ID, SQL_FULLTEXT, PLAN_HASH_VALUE, PARSING_SCHEMA_NAME, ELAPSED_TIME FROM V$SQL W
runqueue'
ELSE event
END
-- Purge explain plan from shared pool, must be done
ORDER BY
on each RAC node
1 DESC, 2 DESC
select inst_id, sql_id, address, hash_value,
/
plan_hash_value, sql_text from gv$sqlarea where
sql_text like 'SELECT COUNT(*) FROM V$SESSION
A WHERE A.AUDSID IN%';
select * from gv$sqlarea where sql_text like
'%XLA_AE_LINES_GT%';
select inst_id, sql_id, address, hash_value,
plan_hash_value, sql_text from gv$sqlarea where
sql_id = 'amd3xmgb8cnuz';
-- On each INST_ID, do these:
alter session set events '5614566 trace name context
forever';
exec
sys.dbms_shared_pool.purge('00000006999BD648,
1622326877','c');
alter session force parallel query;

alter session enable parallel DML;


/*+ PARALLEL */
/*+ PARALLEL, 8 */
/*+ NOPARALLEL */

select xidusn, xidsqn from v$transaction;

declare
v_sql CLOB;
begin
select sql_text into v_sql from dba_hist_sqltext where
sql_id='5273fz2cqkk80';
sys.dbms_sqldiag_internal.i_create_patch(
sql_text => v_sql,
hint_text => 'DYNAMIC_SAMPLING(4)',
name => '5273fz2cqkk80_patch');
end;
/ https://avdeo.com/2012/12/14/oracle-sql-patch-i/

check ENABLE/DISABLE/DROP

EXEC
DBMS_SQLTUNE.ALTER_SQL_PROFILE('coe_527
3fz2cqkk80_3455548535','STATUS','DISABLED');

exec
dbms_sqltune.drop_sql_profile('coe_5273fz2cqkk80_
select NAME,SIGNATURE ,STATUS,FORCE_MATCHING
3455548535');
check Drop
so.name
select * from plan_name,
table(dbms_xplan.display_awr('&sql_id',
NULL, null,so.signature,
'ALLSTATS LAST'));
so.category,
PROMPT so.obj_type,
================================
PROMPT so.plan_id,
Sql Profiles
PROMPT sod.comp_data
================================
from
sqlobj$9999 so, set serveroutput on
set lines 1000 pages
sqlobj$data sod DECLARE
col name for a30
select SQL_HANDLE,
where PLAN_NAME, ENABLED, i NATURAL;
col task_exec_name for a16
ACCEPTED, FIXED
col category forso.namea10 ,sql_text from
= '&m_plan_name' BEGIN
dba_sql_plan_baselines;
and
col created for a30 sod.signature = so.signature i :=
SELECT chr(9)||chr(9)||''''||
and
col sql_text for a150 sod.category = so.category dbms_spm.drop_sql_plan_baseline('SQL_b3d69637a
regexp_replace(extractvalue(value(d),
col signature andfor 9999999999999999999999999
sod.obj_type = so.obj_type a86a8ca');
'/hint'),'''','''''')||''','
select * from and sod.plan_id = so.plan_id dbms_output.put_line(i);
from
table(dbms_xplan.display_sql_plan_baseline(plan_na
order by
select sql.sql_id,sql.child_number as child , prof.name, END;
xmltable('/*/outline_data/hint'
me=>'SQL_PLAN_b7pnq6yp8da6a29d0d9b7')); /passing (
prof.category, signature, obj_type, plan_id
All in) oneprf,
script
prof.created,prof.task_exec_name,prof.FORCE_MATC Taking
select SQL HINTS from memory
table (
HING,prof.status,prof.SIGNATURE xmltype(other_xml) as xmlval
from select from
dba_sql_profiles xmlsequence(
prof, v$sql_plan
gv$sql sql To see the hints from sql_profile
where
extract(xmltype(prf.comp_data),'/outline_data/hint')
where sql.sql_id in ('&sql_id') select
sql_idhint
like from (
nvl('&sql_id',sql_id)
Resolution
-- normally,
) is to fix the execution plan in 11g
and sql.child_number=child_number select s.sql_id, sd.obj_type,
and child_number = &child_no
by
-- andrunningfrom row_number()
and other_xmlover (partition
is not null by sd.signature,
dual
sql.force_matching_signature=prof.SIGNATURE sd.category
) order by sd.signature) row_num,
variable
order) by x hntnumber extractValue(value(t),
) '/hint') hint
begin
;created; from
d; sqlobj$data sd, v$sql s,
:x := table(xmlsequence(extract(xmltype(sd.comp_data),
dbms_spm.load_plans_from_cursor_cache( '/outline_data/hint'))) t
sql_id=>'&sql_id', where sd.obj_type = 1
plan_hash_value=>&plan_hash,
PROMPT ================ and s.exact_matching_signature = sd.signature
fixed=>'YES');
PROMPT Sql Baselines and s.sql_id = '&sql_id')
end;
PROMPT ================ order by row_num
/ /

col SQL_HANDLE for a30


col origin for a16
col last_modified for a30
BEGIN
col last_verified
FOR i IN (SELECTfor a30
address, hash_value
FROM gv$sqlarea WHERE sql_id = '&sql_id.')
select
LOOPsql_handle, plan_name, origin, created,
last_modified,
SYS.DBMS_SHARED_POOL.PURGE(i.address||','||
last_verified,ENABLED,ACCEPTED,FIXED,REPRODU
i.hash_value, 'C');
CED
END LOOP;
from
END;dba_sql_plan_baselines
where
/ signature in (select force_matching_signature http://expertoracle.com/2015/07/08/flush-bad-sql-plan-from-shared-po
from gv$sql
where sql_id='&sql_id'
and inst_id=&inst_id);

undef sid
undef sql_id
undef inst_id
spool off;

"
Name ..... ......................................: '||
set pages 500 s.SCHEMANAME,
set
set lines
linesize1000750pages 9999 'Program ...............................................:
column
column box format9999
sid format a30 '||s.program,
column
column serial for 999999
spid format a10 'Module .................................................:
column
column status
username format a15 a30
format '|| s.module,
column
column username
program format formata30
a10 'Action .................................................: '||
column
column sql_text
os_user format
format a80
a20 s.action,
column module format a30 'Terminal ...............................................:
col program
select for a30
b.sid,b.serial#,a.spid, substr(b.machine,1,30) '||s.terminal,
col SQL_EXEC_START
box,b.logon_time for a20
logon_date , to_char 'Client
(b.logon_time, 'hh24:mi:ss') logon_time, Machine .........................................: '||
SELECT * FROM
substr(b.username,1,30) username, s.machine,
(SELECT status,inst_id,sid,SESSION_SERIAL#
substr(b.osuser,1,20) os_user, 'LAST_CALL_ET ......................................
as
substr(b.program,1,30) program,status,b.last_call_et .....: '||s.last_call_et,
Serial,username,sql_id,SQL_PLAN_HASH_VALUE,
AS last_call_et_secs,b.sql_id 'S.LAST_CALL_ET/3600 ..........................
MODULE,program,
from v$session b,v$process a ..........: '||s.last_call_et/3600
whereTO_CHAR(sql_exec_start,'dd-mon-yyyy from v$session s, v$process p
hh24:mi:ss')
b.paddr = a.addrAS sql_exec_start, where p.addr=s.paddr and
ROUND(elapsed_time/1000000)
and type='USER' s.sid=nvl('&sid',s.sid) and
AS "Elapsed
order by b.sid;(s)", p.spid=nvl('&spid',p.spid) and
ROUND(cpu_time /1000000) nvl(s.process,-1) =
AS "CPU (s)", nvl('&ClientPid',nvl(s.process,-1));
substr(sql_text,1,30) sql_text
FROM gv$sql_monitor where module not like
'%emagent%'
ORDER BY sql_exec_start desc
COLUMN) sid FORMAT 99999
COLUMN
WHERE serial# FORMAT 9999999
rownum<=20;
COLUMN machine FORMAT A30
COLUMN progress_pct FORMAT 99999999.00
COLUMN elapsed FORMAT A10 ALTER SESSION SET
COLUMN
Missing remaining
statements FORMAT A10 -->
in SQL Monitoring "_SQLMON_MAX_PLAN"=4020;
SELECT SID, SERIAL#,
ALTER SESSION SET OPNAME,
SELECT s.sid, TARGET, SOFAR, TOTALWORK,
"_SQLMON_MAX_PLANLINES"=4000;
s.serial#, UNITS,
s.machine, TO_CHAR(START_TIME,'DD/MON/YYY
ROUND(sl.elapsed_seconds/60) || ':' || Y HH24:MI:SS') START_TIME,
MOD(sl.elapsed_seconds,60)
col PLAN FOR a150 elapsed, TO_CHAR(LAST_UPDATE_TIME,'DD/M
SELECT ROUND(sl.time_remaining/60) || ':' || ON/YYYY HH24:MI:SS')
MOD(sl.time_remaining,60)
RPAD('(' || p.plan_line_IDremaining, || ' ' || LAST_UPDATE_TIME,
ROUND(sl.sofar/sl.totalwork*100,
NVL(p.plan_parent_id,'0') || ')',8) || '|' || 2) TIME_REMAINING,
progress_pct
RPAD(LPAD (' ', 2*p.plan_DEPTH) || ELAPSED_SECONDS, MESSAGE,
FROM gv$session
p.plan_operation || ' 's,|| p.plan_options,60,'.') || USERNAME
gv$session_longops sl
NVL2(p.plan_object_owner||p.plan_object_name, FROM V$SESSION_LONGOPS
WHERE s.sid = sl.sid '.' || p.plan_object_name || WHERE TIME_REMAINING != 0;
'(' || p.plan_object_owner||
AND
') ', '') || s.serial# = sl.serial#; /
Time NVL2(p.plan_COST,'Cost:'
model || p.plan_COST,'') || ' ' Stats
|| select vsn.name, vst.value
select stat_name, value
NVL2(p.plan_bytes||p.plan_CARDINALITY,'(' || from v$sesstat vst, v$statname vsn
from V$SESS_TIME_MODEL
p.plan_bytes || ' bytes, ' || p.plan_CARDINALITY || ' where vsn.statistic# = vst.statistic#
where sid = &sid
rows)','') || ' ' || and vst.value != 0
order by value desc;
NVL2(p.plan_partition_start || and vst.sid = &sid
p.plan_partition_stop,' PStart:' || order by vst.value;
Explain Plan waiting steps
p.plan_partition_start || ' PStop:' ||
p.plan_partition_stop,'') ||
NVL2(p.plan_time, p.plan_time || '(s)','') AS PLAN
FROM gv$sql_plan_monitor p
WHERE sid=&sid
ORDER BY p.plan_line_id, p.plan_parent_id; https://blog.yannickjaquier.com/oracle/real-time-sql-monitoring.html

AWR Time based


col avg_pio for 999,999,999 ns_total))/1e6/
dba_hist_sqlstat
col ss for a30
ROUND(concurrency_wait_time/1000000,3)
begin_interval_time AS to_date('05-nov-2017||0001','dd-mon-yyyy
p.plan_object_name ') ', '') ||
WHERE
node ss.dbid
"Concurrency
col wait (s)",= s.dbid
for 99999 hh24mi')
NVL2(p.plan_COST,'Cost:' ||
decode(SUM(px_servers_execs_total),0,
AND
break ss.instance_number
on plan_hash_value=on
ROUND(cluster_wait_time s.instance_number
/1000000,3)skip
startup_time AS1 and
p.plan_COST,'') || ' ' ||
1,SUM(px_servers_execs_total))/decode(
AND ss.snap_id
"Cluster
select = s.snap_id
wait (s)", ss.instance_number
ss.snap_id, node, to_date('05-nov-2017
NVL2(p.plan_bytes|| 2359','dd-mon-
SUM(executions_total),0,1,SUM(executio
AND ss.sql_id =sql_id,
ROUND(user_io_wait_time
begin_interval_time, nvl('&sql_id','4dqs2k5tynk61')
/1000000,3) AS
plan_hash_value, yyyy hh24mi')avg_et_secs,
p.plan_CARDINALITY,'('
ns_total)),2) || p.plan_bytes ||
/* and io
"User ss.executions_delta
wait (s)",
nvl(executions_delta,0) > 0 */
execs, 'and
bytes, ' || p.plan_CARDINALITY || '
/* check executions_delta for 1 , if /(1024*1024))
ROUND(physical_read_bytes it is 0 just
(elapsed_time_delta/decode(nvl(executions_delta,0) AS sn.snap_id=s.snap_id
rows)','') || ' ' ||
SUM(px_servers_execs_total)/decode(S
consider
"Phys only(MB)",
reads rows proceesed and
,0,1,executions_delta))/1000000 calculate total
avg_etime, group by
NVL2(p.plan_partition_start
UM(executions_total),0,1,SUM(execution ||
execution time = sum ( executions_delta
ROUND(physical_write_bytes 1+
/(1024*1024))
(buffer_gets_delta/decode(nvl(buffer_gets_delta,0),0 AS s.sql_idavg_px
p.plan_partition_stop,'
s_total)) PStart:' ||
executions_delta
"Phys writes (MB)",
,1,executions_delta))0 ) */avg_lio, order by FROM dba_hist_sqlstat
p.plan_partition_start || ' PStop:' ||
ORDER BY s.snap_id;
buffer_gets AS "Buffer gets",
ROUND(disk_reads_delta/DECODE(executions_delt difference desc;
p.plan_partition_stop,'')
WHERE ||
EachROUND(plsql_exec_time/1000000,3)
a,0,1, executions_delta),1)
Layer time spend avg_pio, AS NVL2(p.plan_time,
Explain p.plan_time
executions_total
Plan waiting steps > 0||
"Plsql exec (s)",
ROUND(rows_processed_delta/DECODE(execution '(s)','') AS PLAN
GROUP BY sql_id,
ROUND(java_exec_time
s_delta,0, 1, executions_delta), /1000000,3)
1) avg_rows, AS FROM gv$sql_plan_monitor p
plan_hash_value
"Java exec (s)"
round(px_servers_execs_delta/decode(executions_ WHERE
) t2 sql_id='&sql_id'
FROM executions_delta),
delta,0,1, gv$sql_monitor 1) avg_px WHEREORDER BY p.plan_line_id,
fromWHERE sql_id='&sql_id' and
DBA_HIST_SQLSTAT S, inst_id=&inst_id; p.plan_parent_id;
t1.sql_id = nvl(TRIM('&sql_id'),
DBA_HIST_SNAPSHOT
AWR-LIO SS t1.sql_id)
Current Memory
where sql_id = nvl('&sql_id','4dqs2k5tynk61') AND t1.depth = 0
and ss.snap_id = S.snap_id AND t1.sql_id = t2.sql_id(+)
and ss.instance_number = S.instance_number AND t1.plan_hash_value =
and executions_delta > 0 t2.plan_hash_value(+)
order by 1, 2, 3 order by avg_et_secs, cost
/ /
bind_variable

col VALUE_STRING for a50


SELECT
NAME,POSITION,DATATYPE_STRING,VALUE_ST
RING FROM gv$sql_bind_capture WHERE
select s.sid, s.serial#, p.spid, s.username,
sql_id='&sql_id';
s.program,
t.xidusn, t.used_ublk, t.used_urec, sa.sql_text from
v$process p,v$session s, v$sqlarea sa,
v$transaction t exec
where s.paddr=p.addr dbms_stats.flush_database_monitoring_i
and s.taddr=t.addr nfo;
and s.sql_address=sa.address(+)
and s.sql_hash_value=sa.hash_value(+) select inserts,updates,deletes from
order by s.sid user_tab_modifications where
/ table_name = '&table_name';
SELECT wait_class time_cat, ROUND((time_secs),
2) time_secs,
ROUND((time_secs) * 100 / SUM(time_secs)
OVER (), 2) pct
FROM (SELECT wait_class wait_class,
SUM(time_waited_micro) / 1000000
time_secs
FROM gv$system_event
WHERE wait_class <> 'Idle' AND time_waited >
0
WaitGROUP
PercentageBY wait_class
% (Only wait events-WITH CPU)
SELECTUNIONevent, total_waits,
ROUND'CPU',
SELECT (time_waited_micro / 1000000)
ROUND((SUM(VALUE) / AS
time_waited_secs,
1000000), 2) time_secs
ROUND
FROM (time_waited_micro * 100 /
gv$sys_time_model
SUM (time_waited_micro)
WHERE stat_name IN ('background OVERcpu(),2)time',
AS
pct_time
'DB CPU'))
FROMBY
ORDER (SELECT
time_secs event, total_waits,
DESC; select * from (
time_waited_micro select EVENT, WAIT_CLASS,
http://guyharrison.squarespace.com/opsgsamples/
FROM v$system_event SUM(TOTAL_WAITS),round
WHERE wait_class <> 'Idle' (sum(TIME_WAITED_micro)/1000000,0)
UNION as time_waited_secs from
select
set lines 750 pages
SELECT 9999 NULL, VALUE
stat_name, V$SYSTEM_EVENT
event,
select * FROM
from ( v$sys_time_model where wait_class != 'Idle' group by
time_waited
select WHERE"time_waited(s)",
stat_name IN ('DB CPU', EVENT, WAIT_CLASS
case whencpu
WAIT_CLASS
'background time_waited
,time')) = 0 then order by time_waited_secs desc ) where
ORDER 0 BY 3 DESC;
EVENT, rownum < 21;
else
count(sample_time) as EST_SECS_IN_WAIT
fromround(time_waited*100
v$active_session_history / sum(time_waited)
Over(), 2)
where sample_time between sysdate - interval '1'
hourend "percentage"
and sysdate
from
group by WAIT_CLASS,EVENT
( by count(sample_time) desc
order
) select event, sum(time_waited) time_waited
wherefromrownumdba_hist_active_sess_history
<6;
where sql_id = '&SQL_ID'
group by event
)
order by
time_waited desc;
select expl.*
from
gv$sql sql, v$session ses,
TABLE(dbms_xplan.display_cursor(sql.sql_id,
sql.child_number,format=>'typical +predicate')) expl http://www.centroid.com/blog/monitoring-exadata-smart-scan
where ses.sql_address = sql.address and ses.sid
= &&1
and sql.optimizer_cost is not null
/

select * from
table(dbms_xplan.display_awr('&sql_id', null, null,
'ALLSTATS LAST'));
https://hoopercharles.wordpress.com/2010/03/01/dbms_xplan-format-pa

select vs.sid, vs.username, vs.osuser, vs.process


fg_pid,
vp.spid bg_pid
from v$session vs, v$process vp
where vs.paddr = vp.addr;

select sys_context('USERENV', 'IP_ADDRESS')


from dual;
begin
for x in (select
SID,Serial#,status,last_call_et,username from
v$session
where type='USER'
and status='INACTIVE' set pagesize 0
and username = 'TESTER' set linesize 30
and last_call_et > 1200 spool kill_old_sess.sh
) loop select '#!/bin/ksh' from dual;
execute 'Alter System Kill Session '''|| x.Sid select 'kill -9 ' || spid
|| ',' || x.Serial# || ''''; selectv$process
from 'ALTER SYSTEM KILL SESSION
p, v$SESSTAT
end loop; '''||SID||','||SERIAL#||'''IMMEDIATE;'
t,v$sess_io i ,v$session s from
end; v$session where
where i.sid=s.sid username = 'A' and
/ STATUS = 'ACTIVE';
and p.addr=paddr(+)
and s.sid=t.sid
and t.statistic#=12
and s.program like 'oraagent%'
and logon_time < sysdate-1
for i in `ps -ef |grep "oracledb10g1 (LOCAL=NO)" | and status <> 'ACTIVE'
grep -v grep | awk '{print $2}'` order by logon_time desc
do /
echo kill -9 $i spool off
done
DBMS_LOB.WRITEAPPEND(sql_txt,
LENGTH(p_line), p_line);
END wa;
BEGIN
DBMS_LOB.CREATETEMPORARY(sql_txt, TRUE);
DBMS_LOB.OPEN(sql_txt,
DBMS_LOB.LOB_READWRITE);
wa(q'[SELECT
ED_TIME FROM V$SQL WHERE/*+ PARALLEL(12) */ YOUR]');
UPPER(PARSING_SCHEMA_NAME) ='SYS' ORDER BY ELAPSED_TIME DESC
wa(q'[FULL SQL TEXT ]');
wa(q'[HERE ]');
DBMS_LOB.CLOSE(sql_txt);
h := SYS.SQLPROF_ATTR(
q'[BEGIN_OUTLINE_DATA]',
q'[IGNORE_OPTIM_EMBEDDED_HINTS]',
q'[OPTIMIZER_FEATURES_ENABLE('11.2.0.4')]',
q'[DB_VERSION('11.2.0.4')]',
q'[OPT_PARAM('optimizer_dynamic_sampling' 6)]',
q'[ALL_ROWS]',
q'[PARALLEL(12)]',

q'[END_OUTLINE_DATA]');
:signature :=
DBMS_SQLTUNE.SQLTEXT_TO_SIGNATURE(sql
_txt);
:signaturef :=
DBMS_SQLTUNE.SQLTEXT_TO_SIGNATURE(sql
_txt, TRUE);

output :=
SYS.DBMS_SQLTUNE_INTERNAL.I_CREATE_SQ
L_PROFILE(
SQL_TEXT => sql_txt,
PROFILE_XML =>
DBMS_SMB_INTERNAL.VARR_TO_HINTS_XML(h
),
name =>
'coe_5273fz2cqkk80_3455548535',
description => 'coe 5273fz2cqkk80
3455548535 '||:signature||' '||:signaturef||'',
CATEGORY => 'DEFAULT',
CREATOR => 'SYS',
VALIDATE
set lines => TRUE,
1000 pages 9999
TYPE =>
col name for a30 'PATCH',
FORCE_MATCH for
col task_exec_name => a16
TRUE,
IS_PATCH
col category for=> TRUE);
a10
DBMS_LOB.FREETEMPORARY(sql_txt);
col created for a30
coldbms_output.put_line(output);
sql_text for a150
colEND;
signature for 9999999999999999999999999
/ <= My own sql Patch
select sql.sql_id,sql.child_number as child ,
prof.name,
sql Profilesprof.category,
for a sql_id prof.created,
prof.task_exec_name,prof.FORCE_MATCHING,
prof.status, prof.SIGNATURE,prof.SQL_TEXT
from
dba_sql_profiles prof,
gv$sql sql
where sql.sql_id in ('&sql_id')
order by
created;
load from cursor Enable/disable
DECLARE
l_plans_altered PLS_INTEGER;
BEGIN
l_plans_altered :=
DBMS_SPM.alter_sql_plan_baseline(
sql_handle =>
'SQL_b3d69637aa86a8ca',
plan_name =>
'SQL_PLAN_b7pnq6yp8da6a29d0d9b7',
attribute_name => 'FIXED',
attribute_value
select => 'YES');
hint as outline_hints
variable chr(9)||chr(9)||''''||
SELECT sqlid number; from (select p.name, p.signature,
execute :sqlid
regexp_replace(extractvalue(value(d), DBMS_OUTPUT.put_line('Plans
p.category, row_number() Altered:
:=DBMS_SPM.LOAD_PLANS_FROM_CURSOR_C
'/hint'),'''','''''')||''',' ' || l_plans_altered);
over (partition by sd.signature,
ACHE(sql_id=>'5qbbnv0abm2vx',
from END;
sd.category order by sd.signature)
PLAN_HASH_VALUE=>
xmltable('/*/outline_data/hint' 4197102931, /row_num,
SQL_HANDLE
passing ( => 'SQL_d3318f33dfac7bc2'); extractValue(value(t), '/hint') hint
Taking
select SQL HINTS from AWR Taking SQL HINTSsd,
from sqlobj$data from PROFILES p,
dba_sql_profiles
xmltype(other_xml) as xmlval
from table(xmlsequence(extract(xmltype(sd.co
-- v$sql_plan mp_data),
dba_hist_sql_plan '/outline_data/hint')))
where t
sql_id like nvl('&sql_id',sql_id) where sd.obj_type = 1
and other_xml is not null and p.signature = sd.signature
) and p.category = sd.category
) and p.name like ('&profile_name'))
d; order by row_num;

http://intermediatesql.com/oracle/what-are-sql-profiles-and-why-do-we-need-them/
http://www.alfredokriegdba.com/2015/02/

bad-sql-plan-from-shared-pool/
, px_servers_allocated path
'px_servers_allocated'
, duration path
'stats/stat[@name="duration"]'
, elapsed_time path
'stats/stat[@name="elapsed_time"]'
, cpu_time path
'stats/stat[@name="cpu_time"]'
, user_io_wait_time path
'stats/stat[@name="user_io_wait_time"]'
, application_wait_time path
'stats/stat[@name="application_wait_tim
e"]'
, concurrency_wait_time path https://ma
'stats/stat[@name="concurrency_wait_ti uro-
me"]' pagano.c
, cluster_wait_time path SELECT om/2015/
'stats/stat[@name="cluster_wait_time"]' report_id, 05/04/hist
, plsql_exec_time path key1 orical-sql-
'stats/stat[@name="plsql_exec_time"]' sql_id, monitor-
, other_wait_time path key2 reports-
'stats/stat[@name="other_wait_time"]' sql_exec in-12c/
http://allappsdba.blogspot.com/2012/04/queries-to-get-session-information.html
, buffer_gets path _id, key3
'stats/stat[@name="buffer_gets"]' sql_exec http://ww
, read_reqs path _start w.toadwo
'stats/stat[@name="read_reqs"]' FROM rld.com/pl
, read_bytes path dba_hist_ atforms/o
'stats/stat[@name="read_bytes"]' reports racle/w/wi
) x1 WHERE ki/11372.r
where x1.elapsed_time/1000000 > 200 compone eal-time-
and t.COMPONENT_NAME = nt_name sql-
'sqlmonitor' = monitorin
order by 5 'sqlmonito g-12c-
column
/ username format a20 r'; part-ii
Select s.username, s.Sid, s.serial#,
S.Sql_Id, round((Sysdate-
Sql_Exec_Start)*24*60*60/60,0)
MINUTES, Sql_Text
From V$Session S, V$Sqltext T
Where S.Sql_Id = T.Sql_Id
And Sql_Exec_Start Is Not Null And
Piece = 0
And (Sysdate-Sql_Exec_Start)*24*60 >
1
order by MINUTES desc
;
group by
sql_id,
sql_plan_hash_value,
event,sql_exec_id,
sql_exec_start,
current_obj#,
sql_plan_line_id,
sql_plan_operation,
sql_plan_options
)
order by count_1 desc;

https://blog.yannickjaquier.com/oracle/real-time-sql-monitoring.html
http://www.tek-tips.com/viewthread.cfm?qid=1572803
PSED_TIME DESC

Fix baseline of one sql_id to another


execute :sqlid
:=DBMS_SPM.LOAD_PLANS_FROM_
CURSOR_CACHE(sql_id=>'5qbbnv0ab
m2vx', PLAN_HASH_VALUE=>
4197102931, SQL_HANDLE =>
'SQL_d3318f33dfac7bc2');

SELECT * FROM
TABLE(DBMS_XPLAN.DISPLAY_CUR
SOR('5qbbnv0abm2vx',&childnumber,'A
LLSTATS LAST +PEEKED_BINDS
SELECT
+PROJECTION +ALIAS +OUTLINE
regexp_replace(extractvalue(value(d),
+PREDICATE
'/hint'),'''','''''') plan_hint +BYTES'));
+COST
from
xmltable('/*/outline_data/hint'
4197102931 passing (
Taking SQL HINTS selectfrom PLAN_TABLE
xmltype(other_xml)
as xmlval
from plan_table
where other_xml is not
null
and plan_id = (select
max(plan_id) from plan_table)
and rownum=1
)
) d; https://jonathanlewis.wordpress.com/2017/06/12/dbms_sqldiag/
Capacity Planning

SGA Allocation
1 lakh records table with 5 column

Generate DB Load

No of logons to database per hour

No of logons to database per minute

DOP for parallel session

Maximum no of sessions in the database


Cpu Demand

Tuning

CPU wait time

Format the Explain plan


Finding Current trace file

DB Sequential read / Contention problem

Size of the Shared Pool

Sharable memory Used by database

Library cahe hit ratio

Clearing Invalidation

SHARED_POOL_RESERVED_SIZE
Keeping Large Objects in SGA

Tuning the Data Dictionary Cache

Sizing the User Global Area


TUNING DB BUFFER CACHE

how many blocks are used by each object


Calculating the Hit Ratio for Multiple Pools

Sizing the Redo Log Buffer


Sizing the SGA For Java

Multiple I/O Slaves

Multiple DBWR Processes

I/O tuning
SORTING

Diagnosing Contention for Latches

Diagnosing Contention for Manual Rollback Segment Header

Sizing Transaction Rollback Data


Space Requirement For Undo Retention

Monitoring and detecting lock contention

dispatcher processes
INDEX
Using Oracle Blocks Efficiently

Space Recover & performance due to defragmentation

Explain Plan

SQL Trace
Locking the Memory

Get top 10 hot segment

See hot data files (from a single block read time judge)

View pga proposed


Seesion Based Hit Ratio

FREE Buffer Waits

Top 10 CPU users

Top 10 users reading Data


enq: TX - row lock contention

ORA-10631: SHRINK clause should not be specified for this obj

Top 10 CPU consumers in last 5 minutes


Top 10 waiting sessions in last 5 minutes

CPU Cores value from db

CPU Time + wait time = Total Time


CPU by OS/DB/Demand

Sid waiting for ?

Sql statement running by SID

Current sessions problem

Where the particular SID was


spending time when executing

What Class is Causing


Waits

system statistics

Metric values by %
AWR Snapshot list

Checking i/o Latency

Response time analysis

CPU Time + wait Time

Create manual awr snapshot


Cmd line sql monitor

top 100 sql queries based on CPU, elapsed time for the past 7
days in Oracle

Do we have multiple plan hash values for the same SQL ID

Oracle cost calculations for sql query

Monitoring Disk activity


Wait event for the sessions

oracle_which_sql_caused_wait_event

Single block read time

Performance tuning
Reading tkprof output

Wait event solution & concept

tools

sql profiles related to sql_id

STATISTICS

Table statistics
Index statistics
schema Statistics
Database statistics

When was last analyzed

Statistics collection for all schema

Statistics collection for Dictionary

Stale statistics

automatic stats collection enabled or not

History of rowcount in table


Collecting historgram for a table

statistics collection for schema including histogram

optimizer fraud- Manual stats setting

statistics of objects of a specific sql id

sql_profile details

sql base lines details

Top 10 statements
Top 10 sql by elapsed time

TOP 10 BY BUFFER GETS:

TOP 10 BY PHYSICAL READS:


TOP 10 BY EXECUTIONS:

TOP 10 BY PARSE CALLS:

TOP 10 BY SHARABLE MEMORY

TOP 10 BY VERSION COUNT:

ASH Check for current issue

everything about last 1 hour


SQL Tuning Advisor

CPU usage debugging

Does DB looking for More CPU's

Optimizer
optimizer override

Optimizer Evolution - CERN

Manual Creation of sql profile &


sqlpatch(Manual hint for apps sql statements who cant change
the code)

Advisors
advisor recommendation for a taskid
Automatic sql tuning advisor recommendation summary

Table Fragmentation
Here is a technique I use when troubleshooting runaway query. It is based on data from v$sql_plan_statistics already mention
tremendous value and potentially a good alternative to 10046 traces. The biggest obstacle to a wide adoption is the horr
“statistics_level=all” mode. But it is OK to do that at session level, even in production system. So, the execution of the query
statistics_level=all and recreate run environment. Here is the full sequence of a

– Find SQL_ID / Child_number of runway SQL from v$session;


– Find plan_hash_value from v$sql using SQL_ID and CHILD_NUMBER;
– Assuming the query is using bind variables, capture bind variables from v$sql_bind_capture. There can be problems captur
bind variables, skip this step;
– In a separate session “alter session set statistics_level=all”;
– Start executing SQL in this session. If there were bind variables, set same values and, even more importantly
– If the query is absolutely hopeless, cancel execution (send break) after some time, even 10-15 s
– Find SQL_ID of just executed query by looking in v$session.prev_sql_id. If sql text was not changed, the SQL_ID should b
same Plan_hash_value, otherwise revise previous steps;
– Examine plan statistics from v$sql_plan_statistics. The beauty of plan statistics is that it provides data even on partial exe
interpreting plan statistics. Once becoming familiar with them and having a decent viewer, one should be able to see absolute
in numbers. 10-15 seconds of execution should be enough for the query to get to the steps where it will be running fo

This recipe looks rather tedious, and it really is, unless the tool is used that does all that things. The point is, once I was free
only runaway queries (which are rare anyway) but simply expensive queries with a lot of gets/execution. I should add tha
complicated cases or when in doubts. Most often, problems are simple and a quick look at the execution p

45% of ram size

EXAMPLE:
---------

RAM SIZE = 484 MB

So 45 % should be = 216 MB

split the 216 MM for SGA,PGA,BACKGROUNG PROCESSES

Fixed background process requires = 40 MB

SGA = 160 MB

PGA = 16 MB
PRAGMA EXCEPTION_INIT(table_nonexistent, -942);
BEGIN
BEGIN
execute immediate 'drop table sh.sales_copy';
EXCEPTION
WHEN table_nonexistent THEN
NULL;
END;
Table size May be 100 MB
execute immediate 'create table sh.sales_copy as select * from sh.sales';
FOR i IN 1..25 LOOP
execute immediate 'select * from sh.sales_copy';
execute immediate 'delete from sh.sales_copy';
execute immediate 'commit';
execute immediate 'insert into sh.sales_copy select * from sh.sales';
execute immediate 'commit';
END LOOP;
END;
/

fgrep "14-MAR-2014" listener.log | fgrep "establish" | \


awk '{print $1 " " $2 }' | awk -F: '{print $1 }' | \
sort | uniq -c

fgrep "14-MAR-2014 03:" listener.log | fgrep "establish" | \


SELECT
awk '{printA.SNAP_ID,A.INSTANCE_NUMBER
$1 " " $2 }' | awk -F: '{print $1 ":" $2 }' | \
"ID",B.BEGIN_INTERVAL_TIME,B.END_INTERVAL_TIME,A.RESOURCE_NA
sort | uniq -c
ME,
CURRENT_UTILIZATION
PRALLEL_THREADS_PER_CPU "CURRENT",MAX_UTILIZATION
* CPU_COUNT (number of"MAX"
CPU cores) * ACTIVE_INSTANCE_COUNT (number of active in
FROM WRH$_RESOURCE_LIMIT A, WRM$_SNAPSHOT B
WHERE A.RESOURCE_NAME LIKE '%session%'
AND A.SNAP_ID=B.SNAP_ID
AND A.INSTANCE_NUMBER= B.INSTANCE_NUMBER
AND ((A.INSTANCE_NUMBER=1
AND B.BEGIN_INTERVAL_TIME > (SELECT STARTUP_TIME FROM
GV$INSTANCE WHERE INSTANCE_NUMBER=1)) OR
(A.INSTANCE_NUMBER=2 AND B.BEGIN_INTERVAL_TIME >
(SELECT STARTUP_TIME FROM GV$INSTANCE WHERE
INSTANCE_NUMBER=2)))
order by A.INSTANCE_NUMBER,A.SNAP_ID;
http://datavirtualizer.com/oracle-cpu-time/

select metric_name,
COLUMN QUERY_PLANround(value,2)
FORMAT from
A60 v$sysmetric
where
SELECT metric_name
LPAD ('in',('Database
2 * LEVEL)CPU Time Ratio', 'Database Wait Time Ratio')
and intsize_csec
|| operation= (select max(INTSIZE_CSEC) FROM V$SYSMETRIC);
|| ' '
|| options
|| ' '
|| object_name query_plan
FROM plan_table
CONNECT BY PRIOR id = parent_id
START WITH id = 1
ORDER BY id;
3
SETwhere table_name
LINESIZE 100 = 'BIG1';
COLUMN trace_file FORMAT A60
TABLE_NAME size
------------------------------
SELECT s.sid, ------------------------------------------
BIG1s.serial#,
85536kb
pa.value || '/' || LOWER(SYS_CONTEXT('userenv','instance_name')) ||
SQL> select|| table_name,round((num_rows*avg_row_len/1024),2)||'kb'
'_ora_' p.spid || '.trc' AS trace_file "size"
2 from user_tables
FROM v$session s,
3 where table_name
v$process p, = 'BIG1';
v$parameter pa
TABLE_NAME
WHERE pa.name size= 'user_dump_dest'
------------------------------
AND s.paddr = p.addr------------------------------------------
BIG1
AND 68986.97kb
s.audsid = SYS_CONTEXT('USERENV', 'SESSIONID');
SQL> select status from user_indexes
2 where table_name = 'BIG1';

no rows selected

You set the size of the shared pool with the SHARED_POOL_SIZE initialization
parameter.
It defaults to 8,388,608 bytes (8 MB).
SELECT SUM(250 * users_opening) FROM v$sqlarea;

SQL> SELECT 250 * value bytes_per_user


FROM v$sesstat s, v$statname n
WHERE s.statistic# = n.statistic#
AND n.name = 'opened cursors current'
AND s.sid = 15

select sum(pins) "Executions", sum(reloads)


"Cache Misses", sum(reloads)/sum(pins)
from v$librarycache;

SQL> select count(*) from hr.employees;


SQL> select namespace,pins,reloads,invalidations from v$librarycache;
SQL> ANALYZE TABLE hr.employees COMPUTE STATISTICS;

SQL> select count(*) from hr.employees;


SQL> select namespace,pins,reloads,invalidations from v$librarycache;
• Find those PL/SQL objects that are not kept in the
library cache:

select * from v$db_object_cache


where sharable_mem > 10000
and (type='PACKAGE' or type='PACKAGE BODY' or
type='FUNCTION' or type='PROCEDURE')
and KEPT='NO';

• Pin large packages in the library cache:


SQL> EXECUTE dbms_shared_pool.keep(‘package_name');

Keep the ratio of the sum of GETMISSES to the sum of GETS less than 15%:

SQL> select parameter, gets, getmisses from v$rowcache;

UGA space used by your connection:


SQL> select SUM(value) ||'bytes' "Total session memory"
from V$MYSTAT, V$STATNAME
where name = 'session uga memory'
and v$mystat.statistic# = v$statname.statistic#;

UGA space used by all Oracle Shared Server users:

SQL> select SUM(value) ||'bytes' "Total session memory"


from V$SESSTAT, V$STATNAME
where name = 'session uga memory'
and v$sesstat.statistic# = v$statname.statistic#;

Maximum UGA space used by all users:

SQL> select SUM(value) ||'bytes' "Total max memory"


from V$SESSTAT, V$STATNAME
where name = 'session uga memory max'
and v$sesstat.statistic# = v$statname.statistic#;
Dynamic Buffer Cache Advisory Parameter

SQL> show parameter DB_CACHE_ADVICE

NAME TYPE VALUE


------------------------------------ ----------- ------------------------------
db_cache_advice string ON

Three values are allowed: OFF, ON, and READY.

Using V$DB_CACHE_ADVICE
--------------------------
SELECT
size_for_estimate,buffers_for_estimate,estd_physical_read_factor,estd_physical
_reads
FROM V$DB_CACHE_ADVICE
WHERE name = 'DEFAULT'
AND block_size = ( SELECT value FROM V$PARAMETER
WHERE name = 'db_block_size')
AND advice_status = 'ON';

During peak running times, use the following query to calculate how many
blocks are used by each object:
SQL> SELECT owner#, name, count(*) blocks
FROM v$cache
GROUP BY owner#, name;

KEEP Buffer Pool Guidelines


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

• Tuning goal: Keeping blocks in memory


• Size: Holds all or nearly all blocks
• Tool: ANALYZE ... ESTIMATE STATISTICS
SQL> ANALYZE TABLE hr.countries ESTIMATE STATISTICS;
SQL> SELECT table_name, blocks
FROM dba_tables
WHERE owner = 'HR'
AND table_name = 'COUNTRIES';

TABLE_NAME BLOCKS
---------- ----------
COUNTRIES 14
SELECT name,
1 - (physical_reads / (db_block_gets +
consistent_gets)) "HIT_RATIO"
FROM sys.v$buffer_pool_statistics
WHERE db_block_gets + consistent_gets > 0;

Sizing the Redo Log Buffer


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

• Adjust the LOG_BUFFER parameter


• Default value: OS-specific, generally 500k

Using Dynamic Views to Analyze Redo Log Buffer Efficiency


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

LOG_BUFFER
LOG_CHECKPOINT_INTERVAL
LOG_CHECKPOINT_TIMEOUT

SQL> select sid, event, seconds_in_wait, state


from v$session_wait
where event = 'log buffer space%';

SID EVENT SECONDS_IN_WAIT STATE


----- ------ --------------- ---------
log buffer space 110 WAITING

SQL> SELECT name, value


FROM v$sysstat
WHERE name = 'redo buffer allocation retries';

SQL> select name, value


from v$sysstat
where name='redo log space requests';
SQL> SELECT name, value
FROM v$sysstat
WHERE name IN ('redo buffer allocation retries',
'redo entries');
SQL> select event, total_waits, time_waited,
average_wait
from v$system_event
where event like 'log file switch completion%';
– Increase the size of the redo log files.

SQL>select event, total_waits, time_waited, average_wait


from v$system_event
where event like 'log file switch (check%';
– Check the frequency of checkpoints and set the appropriate values for
LOG_CHECKPOINT_INTERVAL and LOG_CHECKPOINT_TIMEOUT.
– Check the size and number of redo log groups
SQL> select event, total_waits, time_waited,
average_wait
from v$system_event
where event like 'log file switch (arch%';
– Regulate archiving speed.

The LGWR process starts a new ARCn process whenever the current number
of ARCn
processes is insufficient to handle the workload. If you anticipate a heavy
workload
for archiving, such as during bulk loading of data, specify multiple archiver
processes
with the LOG_ARCHIVE_MAX_PROCESSES initialization parameter.

• DB_BLOCK_CHECKSUM is set to TRUE, and therefore adds performance


overhead.

• SHARED_POOL_SIZE:
– 8 KB per loaded class
– 50 MB for loading large JAR files
• Configure Oracle Shared Server
• JAVA_POOL_SIZE
– 20 MB default
– 50 MB for medium-sized Java application

SELECT TOTAL_WAITS FROM V$SYSTEM_EVENT WHERE EVENT = 'FREE


BUFFER WAITS';

col name for a70


SQL> SELECT phyrds,phywrts,d.name
FROM v$datafile d, v$filestat f
WHERE d.file#=f.file# order by d.name;
SQL> select name, value from v$sysstat where name = 'sorts (rows)';
NAME VALUE
----------------- ------------------------------
sorts (rows) 639330

SQL> select disk.value "Disk", mem.value "Mem",


(disk.value/mem.value)*100 "Ratio"
from v$sysstat mem, v$sysstat disk
where mem.name = 'sorts (memory)'
and disk.name = 'sorts (disk)';

Disk Mem Ratio


--------- --------- ---------
23 206 11.165049

Increase the Shared pool & buffer cache accordingly

SQL> SELECT class, count FROM v$waitstat WHERE class LIKE '%undo%';
or
SQL> SELECT sum(value) FROM v$sysstat WHERE name IN ('db block gets',
'consistent gets');
or
SQL> SELECT sum(waits)* 100 /sum(gets) "Ratio",
sum(waits) "Waits", sum(gets) "Gets"
FROM v$rollstat;

SELECT s.username, t.used_ublk, t.start_time


FROM v$transaction t, v$session s
WHERE t.addr = s.taddr;
SQL> SELECT s.username, t.used_ublk, t.start_time
FROM v$transaction t, v$session s
WHERE t.addr = s.taddr;

Undo Space = (UNDO_RETENTION * (Undo Blocks Per Second *


DB_BLOCK_SIZE) ) + DB_BLOCK_SIZE

SELECT (RD * (UPS * OVERHEAD) + OVERHEAD) AS "Bytes"


FROM (SELECT value AS RD FROM v$parameter
WHERE name = 'undo_retention'),
(SELECT (SUM(undoblks) / SUM( ((end_time - begin_time) * 86400)))
AS UPS FROM v$undostat),
(SELECT value AS Overhead FROM v$parameter
WHERE name = 'db_block_size');

V$LOCK
V$LOCKED_OBJECT
DBA_WAITERS
DBA_BLOCKERS
SQL> SELECT owner, object_id, object_name, object_type,
v$lock.type
FROM dba_objects, v$lock
WHERE object_id = v$lock.id1 and object_name = table_name;

SELECT network , status ,


SUM(OWNED) Clients,
SUM(busy)*100/(SUM(busy)+SUM(idle)) "Busy Rate"
FROM v$dispatcher group by network,status;

SELECT d.network network, d.name disp, s.username oracle_user,


s.sid sid,s.serial# serial#, p.username os_user,
p.terminal terminal, s.program program
FROM v$dispatcher d, v$circuit c, v$session s, v$process p
WHERE d.paddr = c.dispatcher(+)
AND c.saddr = s.saddr(+)
AND s.paddr = p.addr (+)
order by d.network, d.name, s.username;
As a general guideline, you should create indexes on tables that are often
queried for less than 5% of the table's rows

Monitoring Index Space (Rebilding Indexes)


------------------------
• To collect usage statistics regarding an index:

SQL> ANALYZE INDEX EMP_NAME_IX VALIDATE STRUCTURE;

• To view statistics collected:

SQL> SELECT name, (DEL_LF_ROWS_LEN/LF_ROWS_LEN) * 100


AS wastage
FROM index_stats;

• Rebuild indexes with wastage greater than 20%:

SQL> ALTER INDEX EMP_NAME_IX REBUILD;

• To coalesce indexes (alternative to REBUILD):

SQL> ALTER INDEX EMP_NAME_IX COALESCE;

SELECT INDEX_NAME, USED FROM V$OBJECT_USAGE;


To display segments with less than 10% free blocks:

SQL> SELECT owner, table_name, blocks, empty_blocks


FROM dba_tables
WHERE empty_blocks / (blocks+empty_blocks) < .1;
OWNER TABLE_NAME BLOCKS EMPTY_BLOCKS
------ ---------- ---------- ------------
HR EMPLOYEES 1450 50
HR COUNTRIES 460 40

To avoid dynamic allocation:


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

SQL> ALTER TABLE hr.employees ALLOCATE EXTENT;


Table altered.

Recovering Space
-------------------
Below the high-water mark:
• Use the Export and Import utilities to:
– Export the table
– Drop or truncate the table
– Import the table
Or, use the Alter Table Employees Move;
command to move the table
• Above the high-water mark, use the Alter Table
Employees Deallocate Unused; command.

SQL> Explain plan for select last_name from hr.employees;

• At the session level:


SQL> alter session set SQL_TRACE = {true|false};
SQL> execute DBMS_SESSION.SET_SQL_TRACE ({true|false});
SQL> execute DBMS_SYSTEM.SET_SQL_TRACE_IN_SESSION (session_id,
serial_id, {true|false});
On some operating systems, the DBA can lock the SGA into real memory by
setting the
LOCK_SGA initialization parameter to TRUE, so it is never paged out to disk.
Obviously,
the Oracle server performs better if the entire SGA is kept in real memory.
This should be used only on systems that have sufficient memory to hold all the
SGA pages
without degrading performance in other areas.

col owner for a10


col objct_name for a50
select * from
(Select
ob.owner, ob.object_name, sum (b.tch) Touchs
from x$bh b, dba_objects ob
where b.obj = ob.data_object_id
and b.ts#> 0
group by ob.owner, ob.object_name
order by sum (tch) desc)
where rownum <= 10 ;

SELECT t.file_name,
t.tablespace_name,
round (s.singleblkrdtim / s.singleblkrds, 2) AS CS,
s.READTIM,
s.WRITETIM
FROM v$filestat s, dba_data_files t
WHERE s.file# = t.file_id and rownum <= 10 order by cs desc ;

SELECT (SELECT ROUND (value/1024/1024, 0) FROM v$parameter


WHERE name = 'pga_aggregate_target') "Current Mb"
, ROUND (pga_target_for_estimate/1024/1024, 0) "Projected Mb"
, ROUND (estd_pga_cache_hit_percentage) "%"
FROM v$pga_target_advice
ORDER BY 2;
select Username,
OSUSER,
Consistent_Gets,
Block_Gets,
Physical_Reads,
100*( Consistent_Gets + Block_Gets - Physical_Reads)/
( Consistent_Gets + Block_Gets ) "Hit Ratio %"
from V$SESSION,V$SESS_IO
where V$SESSION.SID = V$SESS_IO.SID
and ( Consistent_Gets + Block_Gets )>0
and username is not null
order by Username,"Hit Ratio %";

increase DBWn process by setting db_writer_process parameter

select rownum as rank, a.*


from (
SELECT v.sid, program, v.value / (100 * 60) CPUMins
FROM v$statname s , v$sesstat v, v$session sess
WHERE s.name = 'CPU used by this session'
and sess.sid = v.sid
and v.statistic#=s.statistic#
and v.value>0
ORDER BY v.value DESC) a
where rownum < 11
;

select rownum as rank, a.*


from (
SELECT v.sid, program, v.value
FROM v$statname s , v$sesstat v, v$session sess
WHERE s.name = 'consistent gets'
and sess.sid = v.sid
and v.statistic#=s.statistic#
and v.value>0
ORDER BY v.value DESC) a
where rownum < 11 ;
For which SQL currently is waiting on:
-----------------------------------------------------------
select sid, sql_text from v$session s, v$sql q where sid in (select sid from
v$session where state in ('WAITING') and wait_class != 'Idle' and event='enq:
TX - row lock contention' and (q.sql_id = s.sql_id or q.sql_id = s.prev_sql_id));

SELECT dt.owner, dt.table_name,


(CASE
WHEN NVL(ind.cnt, 0) < 1 THEN 'Y'
ELSE 'N'
END) AS can_shrink
FROM dba_tables dt,
(SELECT table_name, COUNT(*) cnt
FROM dba_indexes di
WHERE index_type LIKE 'FUNCTION-BASED%'
GROUP BY table_name) ind
WHERE dt.table_name = ind.table_name(+)
AND dt.table_name NOT LIKE 'AQ$%'
AND dt.table_name NOT LIKE 'BIN$%'
AND dt.owner = 'CSS_DATA'
ORDER BY 1, 2;

select * from
(
select session_id, session_serial#, count(*)
from v$active_session_history
where session_state= 'ON CPU' and
sample_time > sysdate - interval '5' minute
group by session_id, session_serial#
order by count(*) desc
)
where rownum <= 10;
select * from
(
select session_id, session_serial#,count(*)
from v$active_session_history
where session_state='WAITING' and
sample_time > sysdate - interval '5' minute
group by session_id, session_serial#
order by count(*) desc
)
where rownum <= 10;

SELECT MIN (val)


FROM (SELECT TO_NUMBER (p.VALUE) AS val
FROM SYS.v_$parameter p
WHERE UPPER (p.NAME) = 'CPU_COUNT'
UNION ALL
SELECT o.VALUE AS val
FROM SYS.v_$osstat o
WHERE UPPER (o.stat_name) = 'NUM_CPUS'
OR UPPER (o.stat_name) = 'NUM_CPU_CORES')

SELECT mymodule "Module", SUM (cpu_time) "CPU Time", SUM (wait_time)


"Wait
Time",
SUM (cpu_time) + SUM (wait_time) "Total Time"
FROM (SELECT a.module mymodule,
(CASE (session_state)
WHEN 'ON CPU'
THEN wait_time / 100
END
) cpu_time,
(CASE (session_state)
WHEN 'WAITING'
THEN time_waited / 100
END
) wait_time
FROM dba_hist_active_sess_history a, dba_hist_snapshot b
WHERE b.end_interval_time > sysdate-10
AND a.snap_id = b.snap_id
AND a.user_id NOT IN (0, 5)
AND a.instance_number = b.instance_number)
GROUP BY mymodule
HAVING SUM (cpu_time) + SUM (wait_time) > 0
ORDER BY 2 DESC
select
decode(n.wait_class,'User I/O','User I/O',
'Commit','Commit',
'Wait') CLASS,
sum(round(m.time_waited/m.INTSIZE_CSEC,3)) AAS
from v$waitclassmetric m,
v$system_wait_class n
where m.wait_class_id=n.wait_class_id
and n.wait_class != 'Idle'
group by decode(n.wait_class,'User I/O','User I/O', 'Commit','Commit',
'Wait')
union
select 'CPU_ORA_CONSUMED' CLASS,
round(value/100,3) AAS
from v$sysmetric
where metric_name='CPU Usage Per Sec'
and group_id=2
union
select 'CPU_OS' CLASS ,
round((prcnt.busy*parameter.cpu_count)/100,3) AAS
from
( select value busy from v$sysmetric where metric_name='Host CPU
Utilization (%)' and group_id=2 ) prcnt,
( select value cpu_count from v$parameter where name='cpu_count' )
parameter
union
select
'CPU_ORA_DEMAND' CLASS,
nvl(round( sum(decode(session_state,'ON CPU',1,0))/60,2),0) AAS
from v$active_session_history ash
where SAMPLE_TIME > sysdate - (60/(24*60*60));

SELECT sid, serial# , username, event,blocking_session, seconds_in_wait, sql_id FROM v$session WHERE state = 'WAITING

SELECT sql_text FROM v$sql WHERE sql_id= 'g3xry817zpwk3';

SELECT wait_class_id, wait_class#, wait_class, total_waits, time_waited FROM v$session_wait_class WHERE sid=161;

SELECT stat_name, value FROM v$sess_time_model WHERE sid=130;

SELECT wait_class_id, wait_class#, wait_class, total_waits, time_waited FROM v$system_wait_class;

select * from sys.aux_stats$

SELECT metric_name, AVG(value), metric_unit FROM v$sysmetric WHERE metric_unit LIKE '\%%' ESCAPE '\' GROUP BY m
SELECT snap_id, snap_level, instance_number,
to_char(begin_interval_time, 'yyyy/mm/dd hh24:mi:ss')
begin_interval_time,
to_char(end_interval_time, 'yyyy/mm/dd hh24:mi:ss') end_interval_time,
to_char(flush_elapsed) flush_elapsed,
to_char(startup_time, 'yyyy/mm/dd hh24:mi:ss') startup_time,
error_count
FROM DBA_HIST_SNAPSHOT
WHERE dbid = :dbid
order by 1

Select Inst_Id, EVENT, TOTAL_WAITS, TIME_WAITED ,


Round(100*Total_Waits/Time_Waited) Rate,
Round(10* Time_Waited/Total_Waits,1) Latency
From Gv$System_Event
Where Event Like '%db file sequential read%'
And Inst_Id In (1,2,3,4,5)
Order By 1;

select *
from
(select
sql_text,
sql_id,
elapsed_time,
cpu_time,
user_io_wait_time
from
sys.v_$sqlarea
order by 5 desc)
where rownum < 6;

select metric_name, round(value,2) from v$sysmetric


where metric_name in ('Database CPU Time Ratio', 'Database Wait Time Ratio')
and intsize_csec = (select max(INTSIZE_CSEC) FROM V$SYSMETRIC);

BEGIN
DBMS_WORKLOAD_REPOSITORY.CREATE_SNAPSHOT ();
END;
/
SELECT *
FROM
select * from status,
(SELECT
(select--username,
s.sql_id, RANK() OVER (ORDER BY
(max(s.CPU_TIME_TOTAL/s.executions_total))
sql_id, DESC) cpu_rank,
RANK() OVER
sql_exec_id,(ORDER BY
(max(s.ELAPSED_TIME_TOTAL/s.EXECUTIONS_TOTAL))
TO_CHAR(sql_exec_start,'dd-mon-yyyy hh24:mi:ss') AS DESC)
sql_exec_start,
elapsed_rank
ROUND(elapsed_time/1000000) AS "Elapsed (s)",
from ROUND(cpu_time /1000000) AS "CPU (s)",
dba_hist_sqlstat
buffer_gets, s,
dba_hist_snapshot sn
ROUND(physical_read_bytes /(1024*1024)) AS "Phys reads (MB)",
whereROUND(physical_write_bytes/(1024*1024)) AS "Phys writes (MB)"
sn.begin_interval_time
FROM v$sql_monitorbetween to_date('06-aug-2014 0001','dd-mon-yyyy
hh24mi')
ORDER BY elapsed_time DESC
and )
to_date('13-aug-2014
WHERE rownum<=20; 0600','dd-mon-yyyy hh24mi')
and
sn.snap_id=s.snap_id and s.executions_total >0
group by
s.sql_id
) where cpu_rank <=100 and elapsed_rank<=100;

select
SQL_ID
, PLAN_HASH_VALUE
column "File Total" format 99,999,990
, sum(EXECUTIONS_DELTA) EXECUTIONS
, sum(ROWS_PROCESSED_DELTA) CROWS
set line 132
, trunc(sum(CPU_TIME_DELTA)/1000000/60) CPU_MINS
set pagesize 33
, trunc(sum(ELAPSED_TIME_DELTA)/1000000/60) ELA_MINS
from DBA_HIST_SQLSTAT
ttitle
where " ***** Database:
SQL_ID in ( "db", DataFile's Disk Activity (As of:" tdate " ) *****"
'&sqlid')
select
group by substr(df.file#,1,2) "ID",
SQL_ID , PLAN_HASH_VALUE
rpad(substr(name,1,52),52,'.')
order by SQL_ID, CPU_MINS;"File Name",
rpad(substr(phyrds,1,10),10,'.') "Phy Reads",
rpad(substr(phywrts,1,10),10,'.') "Phy Writes",
http://uralural.blogspot.com/2007/07/oracle-cbo-chooses-wrong-index-although.html
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
'SQL*Net break/reset to client',
'SQL*Net more data from client',
'SQL*Net message to client',
'dispatcher timer',
'Null event',
'parallel query dequeue wait',
'parallel query idle wait - Slaves',
'pipe get',
'PL/SQL lock timer',
'slave wait',
'virtual circuit status',
'WMON goes to sleep'
)
AND a.event NOT LIKE 'DFS%'
AND a.event NOT LIKE 'KXFX%'
AND a.sid = b.sid)
order by 6 desc, 1 asc

select
event,
sql_id,
snap_id,
dbid,
instance_number,
sample_time,
session_id,
session_serial#,
user_id,
blocking_session,
program,
(
select
sql_text
from
dba_hist_sqltext
where
sql_id = dba_hist_active_sess_history.sql_id
) sql_text
from
dba_hist_active_sess_history
where
program = 'some.exe'
and
sample_time between
to_timestamp('START_TIME', 'YYYY-MM-DD HH24:MI:SS.FF3') and
to_timestamp('END_TIME', 'YYYY-MM-DD HH24:MI:SS.FF3')
and
event = 'some wait event';

Select Inst_Id, EVENT, TOTAL_WAITS, TIME_WAITED ,


Round(100*Total_Waits/Time_Waited) Rate,
Round(10* Time_Waited/Total_Waits,1) Latency
From GV$System_Event
Where Event Like '%db file sequential read%'
And Inst_Id In (1)
Order By 1;

http://gavinsoorma.com/2012/11/ash-and-awr-performance-tuning-scripts/
http://hourim.wordpress.com/2012/09/14/tuning-by-tkprof-a-case-study/

https://sites.google.com/site/embtdbo/wait-event-documentation

http://www.oraclerealworld.com/best-oracle-performance-tools/

select distinct
p.name sql_profile_name,
s.sql_id
from
dba_sql_profiles p,
DBA_HIST_SQLSTAT s
where
p.name=s.sql_profile;

http://nadvi.blogspot.com/2011/10/gather-optimizer-statistics-11g_26.html

exec DBMS_STATS.GATHER_TABLE_STATS (ownname => '&OWNER' , tabname => '&TABLE_NAME',cascade => true, es
exec dbms_stats.gather_index_stats ( ownname => '&OWNER', indname => '&INDEX_NAME',estimate_percent => dbms_sta
exec DBMS_STATS.GATHER_SCHEMA_STATS (ownname => '&OWNER' , estimate_percent => dbms_stats.auto_sample_
EXEC DBMS_STATS.GATHER_DATABASE_STATS(ESTIMATE_PERCENT => DBMS_STATS.AUTO_SAMPLE_SIZE, MET
select
table_name,STATUS,NUM_ROWS,SAMPLE_SIZE,to_char(LAST_ANALYZED,'
DD-MON-YYYY hh24:mi:ss') from dba_tables
where table_name in ('&tab1','&tab2','&tab3') and owner='&schema';
select 'execute DBMS_STATS.GATHER_SCHEMA_STATS('''||username||''') ;'
from dba_users where username <> 'SYS';
exec dbms_stats.gather_schema_stats ('SYS');
exec dbms_stats.gather_database_stats (gather_sys=>TRUE);
exec dbms_stats.gather_dictionary_stats;
exec dbms_stats.gather_fixed_objects_stats;

col TABLE_NAME for a30


col PARTITION_NAME for a20
col SUBPARTITION_NAME for a20
select
OWNER,TABLE_NAME,PARTITION_NAME,SUBPARTITION_NAME,NUM_RO
WS,LAST_ANALYZED from dba_TAB_STATISTICS where
STALE_STATS='YES';
SELECT CLIENT_NAME, STATUS FROM DBA_AUTOTASK_CLIENT WHERE
CLIENT_NAME='auto optimizer stats collection';

select n.object_name as
T,o.ROWCNT,o.BLKCNT,to_char(o.SAVTIME,'hh/dd/mm HH:MI:SS') as time
from dba_objects n,WRI$_OPTSTAT_TAB_HISTORY o where
o.obj#=n.object_id and n.object_name='ARS_SV_USERS';
exec dbms_stats.gather_table_stats('DBUSER01','TABLE01',
estimate_percent=>33, cascade => TRUE, method_opt => 'FOR ALL INDEXED
COLUMNS SIZE 10');

begin
dbms_stats.gather_schema_stats(
ownname => 'SCOTT',
estimate_percent => dbms_stats.auto_sample_size,
method_opt => 'for all columns size auto',
degree => 7
);
end;
/

begin
dbms_stats.set_table_stats('TESTER'
, 'TEST1'
, numrows=>10000
, numblks=>174
, avgrlen=>110);
end;
/

set lines 300 set pages 300


col table_name for a40
col owner for a30
select distinct owner, table_name, STALE_STATS, last_analyzed,
stattype_locked
from dba_tab_statistics
where (owner, table_name) in
(select distinct owner, table_name
from dba_tables
where ( table_name)
in ( select object_name
from gv$sql_plan
where upper(sql_id) = upper('&sql_id') and object_name is not null))
--and STALE_STATS='YES'
/
SELECT NAME, SQL_TEXT, CATEGORY, STATUS
FROM DBA_SQL_PROFILES;

SELECT sql_handle, plan_name, enabled, accepted


FROM dba_sql_plan_baselines
WHERE sql_text NOT LIKE '%dba_sql_plan_baselines%';
select
sql_id,
child_number,
sql_text,
elapsed_time
from
(select
sql_id,child_number,
sql_text,
elapsed_time,
cpu_time,
disk_reads,
rank ()
over
(order by elapsed_time desc)
as
sql_rank
from
gv$sql)
where
sql_rank < 10;

SET LINESIZE 1000


SET PAGESIZE 100
SELECT * FROM
(SELECT SUBSTR(SQL_TEXT,1,40) SQL,
BUFFER_GETS, EXECUTIONS, BUFFER_GETS/EXECUTIONS
"GETS/EXEC",
HASH_VALUE,ADDRESS
FROM V$SQLAREA
WHERE BUFFER_GETS > 10000
ORDER BY BUFFER_GETS DESC)
WHERE ROWNUM <= 10;

SELECT * FROM
(SELECT SUBSTR(SQL_TEXT,1,40) SQL,
DISK_READS, EXECUTIONS, DISK_READS/EXECUTIONS "READS/EXEC",
HASH_VALUE,ADDRESS
FROM V$SQLAREA
WHERE DISK_READS > 1000
ORDER BY DISK_READS DESC)
WHERE ROWNUM <= 10;
SELECT * FROM
(SELECT SUBSTR(SQL_TEXT,1,40) SQL,
EXECUTIONS, ROWS_PROCESSED, ROWS_PROCESSED/EXECUTIONS
"ROWS/EXEC",
HASH_VALUE,ADDRESS
FROM V$SQLAREA
WHERE EXECUTIONS > 100
ORDER BY EXECUTIONS DESC)
WHERE ROWNUM <= 10;

SELECT * FROM
(SELECT SUBSTR(SQL_TEXT,1,40) SQL,
PARSE_CALLS, EXECUTIONS, HASH_VALUE,ADDRESS
FROM V$SQLAREA
WHERE PARSE_CALLS > 1000
ORDER BY PARSE_CALLS DESC)
WHERE ROWNUM <= 10;

SELECT * FROM
(SELECT SUBSTR(SQL_TEXT,1,40) SQL,
SHARABLE_MEM, EXECUTIONS, HASH_VALUE,ADDRESS
FROM V$SQLAREA
WHERE SHARABLE_MEM > 1048576
ORDER BY SHARABLE_MEM DESC)
WHERE ROWNUM <= 10;

SELECT * FROM
(SELECT SUBSTR(SQL_TEXT,1,40) SQL,
VERSION_COUNT, EXECUTIONS, HASH_VALUE,ADDRESS
FROM V$SQLAREA
WHERE VERSION_COUNT > 20
ORDER BY VERSION_COUNT DESC)
WHERE ROWNUM <= 10;

http://orababy.blogspot.com/2013/08/active-session-history-queries.html
with AASSTAT as (
select
decode(n.wait_class,'User I/O','User I/O',
'Commit','Commit',
'Wait') CLASS,
sum(round(m.time_waited/m.INTSIZE_CSEC,3)) AAS
from v$waitclassmetric m,
v$system_wait_class n
where m.wait_class_id=n.wait_class_id
and n.wait_class != 'Idle'
SELECT group by decode(n.wait_class,'User I/O','User I/O', 'Commit','Commit',
sysmetric_history.sample_time,
'Wait')
cpu/60 AS cpu,
union
bcpu/60 AS bcpu,
DECLARE select 'CPU_ORA_CONSUMED'
DECODE(SIGN((cpu+bcpu)/60-cpu_ora_consumed), CLASS,
-1, 0, ((cpu+bcpu)/60-
l_sql_tune_task_id
cpu_ora_consumed)) VARCHAR2(100);
round(value/100,3)
AS cpu_ora_wait, AAS
BEGIN from v$sysmetric
scheduler/60 AS scheduler,
l_sql_tune_task_id
uio/60 AS where := DBMS_SQLTUNE.create_tuning_task
uio,metric_name='CPU Usage Per Sec' (
sio/60 AS and sql_id => '4pgqpkv31u4nn',
group_id=2
sio,
union
concurrency/60 scope => DBMS_SQLTUNE.scope_comprehensive,
AS concurrency,
application/60 time_limit
select 'CPU_OS'
AS => 2100,
application, CLASS ,
AS COMMIT, => '4pgqpkv31u4nn_tuning_task',
task_name
COMMIT/60round((prcnt.busy*parameter.cpu_count)/100,3) AAS
from
configuration/60 description => 'Tuning task for statement d4pgqpkv31u4nn.');
AS configuration,
DBMS_OUTPUT.put_line('l_sql_tune_task_id:
( select value
administrative/60 busy from v$sysmetric where
AS administrative, ' || l_sql_tune_task_id);
metric_name='Host CPU
END;
Utilization
network/60 (%)'ASand group_id=2 ) prcnt,
network,
/ queueing/60 ( selectASvalue cpu_count from v$parameter where name='cpu_count' )
queueing,
parameter
clust/60 AS clust,
EXEC DBMS_SQLTUNE.execute_tuning_task(task_name
union
other/60 AS other =>
'4pgqpkv31u4nn_tuning_task');
FROM select
(SELECT 'CPU_ORA_DEMAND' CLASS,
select task_name,
nvl(round(status
TRUNC(sample_time,'MI') fromAS dba_advisor_log
sample_time, where
sum(decode(session_state,'ON CPU',1,0))/60,2),0) AAS
task_name='4pgqpkv31u4nn_tuning_task';
from v$active_session_history ash
DECODE(session_state,'ON
where SAMPLE_TIME > sysdate - (60/(24*60*60)) CPU'), wait_class)
CPU',DECODE(session_type,'BACKGROUND','BCPU','ON
SETwait_class
)AS SERVEROUTPUT ON
SET
select
FROMLONG 100000;
v$active_session_history
setWHERE
longchunksize 1000;
( decode(sign(CPU_OS-CPU_ORA_CONSUMED),
sample_time>sysdate-INTERVAL '1' HOUR -1, 0, (CPU_OS -
SET PAGESIZE
CPU_ORA_CONSUMED 1000 )) +
AND sample_time<=TRUNC(SYSDATE,'MI')) ash
SET LINESIZE
CPU_ORA_CONSUMED
PIVOT (COUNT(*)200 FOR wait_class + IN ('ON CPU' AS cpu,'BCPU' AS
SELECT DBMS_SQLTUNE.report_tuning_task('4pgqpkv31u4nn_tuning_task')
decode(sign(CPU_ORA_DEMAND-CPU_ORA_CONSUMED),
bcpu,'Scheduler' AS scheduler,'User I/O' AS uio,'System I/O' AS sio,-1, 0,
AS'Concurrency'
recommendations
(CPU_ORA_DEMAND FROM dual;
- CPU_ORA_CONSUMED
AS concurrency,'Application' ))) CPU_TOTAL, AS
AS application,'Commit'
SET PAGESIZE 24
decode(sign(CPU_OS-CPU_ORA_CONSUMED),
COMMIT,'Configuration' AS configuration, -1, 0, (CPU_OS -
CPU_ORA_CONSUMED )) CPU_OS,
'Administrative' AS administrative,'Network' AS network,'Queueing' AS
CPU_ORA_CONSUMED
queueing,'Cluster' AS clust,'Other'CPU_ORA,
AS other)) ash,
decode(sign(CPU_ORA_DEMAND-CPU_ORA_CONSUMED), -1, 0,
(SELECT
(CPU_ORA_DEMAND
TRUNC(begin_time,'MI') - CPU_ORA_CONSUMED
AS sample_time, )) CPU_ORA_WAIT,
COMMIT, AS cpu_ora_consumed
VALUE/100
READIO,
FROM v$sysmetric_history
WAIT GROUP_ID=2
WHERE
fromAND( metric_name='CPU Usage Per Sec') sysmetric_history
select
WHERE ash.sample_time (+)=sysmetric_history.sample_time
ORDER sum(decode(CLASS,'CPU_ORA_CONSUMED',AAS,0))
BY sample_time;
CPU_ORA_CONSUMED,
sum(decode(CLASS,'CPU_ORA_DEMAND' ,AAS,0))
CPU_ORA_DEMAND,
sum(decode(CLASS,'CPU_OS' ,AAS,0)) CPU_OS,
sum(decode(CLASS,'Commit' ,AAS,0)) COMMIT,
sum(decode(CLASS,'User I/O' ,AAS,0)) READIO,
sum(decode(CLASS,'Wait' ,AAS,0)) WAIT
from AASSTAT)
/
select ksppinm name,
ksppstvl value
from sys.x$ksppi x,
sys.x$ksppcv y
where (x.indx = y.indx)
and ksppinm = '_optimizer_aggr_groupby_elim';

alter session set optimizer_features_enable = '11.2.0.4';

select ksppinm name,


ksppstvl value
from sys.x$ksppi x,
sys.x$ksppcv y
where (x.indx = y.indx)
and ksppinm = '_optimizer_aggr_groupby_elim';

alter session set "_optimizer_aggr_groupby_elim"=true;

Optimizer Evolution
• Oracle 8i – histograms
• Oracle 9i – bind variable peeking
• Oracle 10g – Automatic Optimizer Statistics Collection,Dynamic Sampling
• Oracle 11gR1 – Adaptive Cursor Sharing, Extended statistics (correlated
columns)
• Oracle 11gR2 – Cardinality Feedback
• Oracle 12c – Adaptive Query Optimization

declare
v_sql_text CLOB;
BEGIN
select sql_text into v_sql_text from v$sql where sql_id = 'bu18sp8k0wcvv';
sys.dbms_sqldiag_internal.i_create_patch(
sql_text=>v_sql_text,
hint_text=>'full(@SEL$1 test_dba_tables)',
name=>'tst_patch');
END;
/
exec dbms_sqldiag.DROP_SQL_PATCH('tst_patch');

Advisor names

Enabled or not

Job History
Parameters

EXEC_ID for sql tuning advisors (History of Job run status)

Automatic Sql advisor Report

SELECT a.command AS type,


f.message AS findings,
a.message AS recommendations,
t.message AS rationale
FROM dba_advisor_actions a,
dba_advisor_recommendations r,
dba_advisor_findings f,
dba_advisor_rationale t
WHERE a.task_id = &task_id
AND a.task_id = r.task_id
AND a.rec_id = r.rec_id
AND a.task_id = t.task_id
AND a.rec_id = t.rec_id
AND f.task_id = r.task_id
AND f.finding_id = r.finding_id;
set lines 750 pages 9999
set long 9999
select dbms_sqltune.report_auto_tuning_task(
(select min(execution_name) from dba_advisor_findings
where task_name like 'SYS_AUTO_SQL%'),
(select max(execution_name) from dba_advisor_findings
where task_name like 'SYS_AUTO_SQL%')
) from dual;

select
table_name,round((blocks*8),2) "size (kb)" ,
round((num_rows*avg_row_len/1024),2) "actual_data (kb)",
(round((blocks*8),2) - round((num_rows*avg_row_len/1024),2))
"wasted_space (kb)"
from
dba_tables
where owner='&OWNER' and table_name='&TABLE_NAME' and
(round((blocks*8),2) > round((num_rows*avg_row_len/1024),2))
order by 4 desc;
based on data from v$sql_plan_statistics already mentioned in your article. In my opinion, plan statistics have
races. The biggest obstacle to a wide adoption is the horrible slowness caused by high CPU overhead in
even in production system. So, the execution of the query is staged in a separate session where we can set
d recreate run environment. Here is the full sequence of actions:

L_ID / Child_number of runway SQL from v$session;


sh_value from v$sql using SQL_ID and CHILD_NUMBER;
s from v$sql_bind_capture. There can be problems capturing bind variables, for brevity I will skip details. If no
bind variables, skip this step;
arate session “alter session set statistics_level=all”;
nd variables, set same values and, even more importantly, same datatypes as in Capture step;
ncel execution (send break) after some time, even 10-15 secs should be sufficient;
_sql_id. If sql text was not changed, the SQL_ID should be same as in step 1. Very important: it should have
lan_hash_value, otherwise revise previous steps;
f plan statistics is that it provides data even on partial execution. It can be a separate article dedicated to the
aving a decent viewer, one should be able to see absolutely clear where the problem is. No guess work, it’s all
or the query to get to the steps where it will be running for lo-o-ong time, they can be easily identified.

sed that does all that things. The point is, once I was free from all that routine, I was able to troubleshoot not
nsive queries with a lot of gets/execution. I should add that it makes sense to use this technique in really
n, problems are simple and a quick look at the execution plan is enough to spot the cause.

OS occupies memory of
-----------------------

20 % of RAM SIZE --> for windows

10 % of RAM SIZE --> for UNIX/LINUX


For merging files

cat *.xml >> file.log

cores) * ACTIVE_INSTANCE_COUNT (number of active instances)

http://www.oracle.com/technetwork/articles/schumacher-analysis-099313.html
Instead of creating new table u can try

alter table table_name move;

It will remove the contention

In a test environment, you can measure shareable memory by selecting the number of open
cursors for a test user. You multiply the resulting value by the total number of users:
Ideally, your application should have a library cache as large as the sum of the numbers
above, plus a small allowance for dynamic SQL.

This is useful when calculating shared pool size

• Reloads should be less than 1% of the pins:


• If the reloads-to-pins ratio is greater than 1%,
increase the value of the SHARED_POOL_SIZE
parameter.

When Invalidations Occur ?

when a table, sequence, synonym, or view is re-created or altered or dropped, or


a procedure or package specification is recompiled, all dependent shared SQL areas are
invalidated.

Additional V$SQL_PLAN columns not found in PLAN_TABLE:


• ADDRESS: Cursor parent handle address
• HASH_VALUE: Parent statement hash value in library cache
• CHILD_NUMBER: Number using this execution plan
• DEPTH: Level of the operation in the tree
• CPU_COST: CPU cost of the operation as estimated by the cost-based optimizer. If
using the rule-based optimizer, this column is null.
• IO_COST: Cost of the operation as estimated by the cost-based optimizer. If using the
rule-based optimizer, this column is Null.
•Too
TEMP_SPACE:
much memorySpace usage
may have of sort
been or hash-join
allocated to the estimated by if:
reserved list cost-based optimizer
• REQUEST_MISS = 0 or not increasing
• FREE_MEMORY = > 50% of the SHARED_POOL_RESERVED_SIZE minimum
If either of these is true, decrease the value for SHARED_POOL_RESERVED_SIZE.
How to Keep Objects ?
Use the supplied DBMS_SHARED_POOL package and the KEEP procedure to keep objects.
To create the package, run the dbmspool.sql script. The prvtpool.plb script is
automatically executed at the end of the previous one. These scripts are not run by
catproc.sql.
Use the UNKEEP procedure to remove pinned objects from the shared pool.
First, the DBA determines the change in the hit ratio as buffers are added or removed. As a
general rule, increase buffer cache size if:
• The cache hit ratio is less than 90%
• There is adequate memory for other processes without inducing additional page faults

Hit ratio is affected by data access methods:


• Full table scans
• Data or application design
• Large table with random access
• Uneven distribution of cache hits
The V$SESSION_WAIT view indicates through the Log Buffer Space event if there are any
waits for space in the log buffer because the session is writing data into the log buffer faster
than LGWR can write it out.

Note: The V$SYSSTAT view displays another statistic, Redo Log Space Requests:

• The Redo Buffer Allocation Retries value should be near


0; the number should be less than 1% of redo entries.

– In the V$SYSTEM_EVENT view, check the number of occurrences of the event


Log File Switch Completion, which identifies the log file switch waits because
of log switches.

– In the V$SYSTEM_EVENT view, check the number of occurrences of the event


Log File Switch (Checkpoint Incomplete), which identifies the log file switch
waits because of incomplete checkpoints.
– In the V$SYSTEM_EVENT view, check the number of the occurrences of the
event Log File Switch (Archiving Needed), which identifies the log file switch
waits because of the archiving issue.

• Turn asynchronous I/O on or off with:


– DISK_ASYNCH_IO
– TAPE_ASYNCH_IO

Multiple DBWn processes can be deployed with


DB_WRITER_PROCESSES (DBW0 to DBW9).

Tuning DBWn I/O


Tune the DBWn by looking at the value of the
following event:
FREE BUFFER WAITS

Consider increasing the DBWn processes, if you see a high number of


free_buffer_waits after querying the V$SYSTEM_EVENT view as in the following
syntax:

Note: The last two columns contain 0 unless the TIMED_STATISTICS parameter is set to
TRUE.
Use the following query to monitor these values:
Avoiding Sorts
--------------------
Avoid sort operations whenever possible:
• Use NOSORT to create indexes.
• Use UNION ALL instead of UNION.
• Use index access for table joins.
• Create indexes on columns referenced in the
ORDER BY clause.
• Select the columns for analysis.
• Use ESTIMATE rather than COMPUTE for large
objects.

Create indexes on columns that are frequently referenced with ORDER BY statements.

SQL> select disk.value "Disk", mem.value "Mem",


(disk.value/mem.value)*100 "Ratio"
from v$sysstat mem, v$sysstat disk
where mem.name = 'sorts (memory)'
and disk.name = 'sorts (disk)';

Disk Mem Ratio


--------- --------- ---------
23 206 11.165049

• The number of waits for any class should be less than 1% of the total number of requests.
• If not, create more rollback segments.

• Deletes are expensive.TRUNCATE instead, performance is improved.


• Inserts use minimal rollback space.
• Updates use rollback space, depending on the
number of columns.
• Index maintenance adds rollback.
Using Less Rollback
----------------------
• Export / Import operations
– Import
– Set COMMIT = Y
– Size the set of rows with the BUFFER keyword
– Export: Set CONSISTENT=N
• SQL*Loader operations: Set the commit intervals with ROWS

You can use the following query to set the UNDO_RETENTION parameter and size the undo
tablespace:

You can increase the overall number of locks available for an instance by increasing the
values of the DML_LOCKS and ENQUEUE_RESOURCES parameters. This may be necessary
in a parallel server configuration.

V$LOCK
V$LOCKED_OBJECT
DBA_WAITERS
DBA_BLOCKERS

To find the table name that corresponds to a particular resource ID 1 of the V$LOCK view:

Query the V$DISPATCHER view to determine the usage for selected dispatcher processes.
You identify contention for dispatchers by checking:

A query to report the dispatcher, session, and process mapping using shared servers:
Maintenance Considerations
--------------------------
In a data warehousing environment, data is usually maintained by way of bulk inserts and
updates. Index maintenance is deferred until the end of each DML operation. For example, if
you insert 1,000 rows, then the inserted rows are placed into a sort buffer, and then the
updates of all 1,000 index entries are batched. (This is why SORT_AREA_SIZE must be set
properly for good performance with inserts and updates on bitmap indexes.) Thus, each
bitmap segment is updated only once per DML operation, even if more than one row in that
segment changes.

Typically, if 15% of the index data is deleted, then you


should consider rebuilding the index.

Identifying Unused Indexes


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

• To start monitoring the usage of an index:


ALTER INDEX HR. EMP_NAME_IX MONITORING USAGE;
• To stop monitoring the usage of an index:
ALTER INDEX HR. EMP_NAME_IX NOMONITORING USAGE;
• To query the usage of the index:
• Larger extents can have a small performance benefit because the Oracle server can read
one large extent from disk with fewer multiblock reads than would be required to read
many small extents. To avoid partial multiblock reads, set the extent size to a multiple
of 5 × DB_FILE_MULTIBLOCK_READ_COUNT. Multiply by five because the Oracle
server tries to allocate extents on five-block boundaries. By matching extent sizes to the
I/O and space allocation sizes, the performance cost of having many extents in a
segment is minimized. However, for a table that never has a full table scan operation, it
makes no difference in terms of query performance whether the table has one extent or
multiple extents.

The High-Water Mark


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

• Reset by the TRUNCATE command


• Never reset by DELETE statements

The High-Water Mark


Space above the high-water mark can be reclaimed at the table level by using the following
command:
ALTER TABLE <table_name> DEALLOCATE UNUSED...

Move the table


---------------
After the table is moved, all indexes are marked unusable, and must be rebuilt.

The DB_BLOCK_SIZE Parameter


The database block size:
• Is defined by the DB_BLOCK_SIZE parameter
• Is set when the database is created
• Is the minimum I/O unit for data file reads
• Is 2 KB or 4 KB by default, but up to 64 KB is
allowed
• Cannot be changed easily
• Should be an integer multiple of the OS block size
• Should be less than, or equal to, the OS I/O size

• Query plan_table to display the execution plans:


– Query PLAN_TABLE directly
– Use script utlxpls.sql (Hide Parallel Query information)
– Use script utlxplp.sql (Show parallel Query information)
Hot Segments under Specific Schema & type=table
select * from
(Select
ob.owner, ob.object_name, sum (b.tch) Touchs
from x$bh b, dba_objects ob
where b.obj = ob.data_object_id
and b.ts#> 0 and ob.object_type='TABLE' and ob.owner='&owner'
group by ob.owner, ob.object_name
order by sum (tch) desc)
where rownum <= 10 ;
The blocking session is:

select blocking_session, sid, serial#, wait_class, seconds_in_wait from v$session where


blocking_session is not NULL order by blocking_session;
http://www.oaktable.net/content/oracle-cpu-time

n_wait, sql_id FROM v$session WHERE state = 'WAITING' AND wait_class!= 'Idle' ;

aited FROM v$session_wait_class WHERE sid=161;

aited FROM v$system_wait_class;

WHERE metric_unit LIKE '\%%' ESCAPE '\' GROUP BY metric_name, metric_unit;


Latency should be always within 5-10 ms ..If it exceeds then it is a issue
http://blog.yannickjaquier.com/oracle/real-time-sql-monitoring.html

x-although.html
NER' , tabname => '&TABLE_NAME',cascade => true, estimate_percent => dbms_stats.auto_sample_size,method_opt=>'FOR ALL COLU
name => '&INDEX_NAME',estimate_percent => dbms_stats.auto_sample_size, degree => 8);
WNER' , estimate_percent => dbms_stats.auto_sample_size ,method_opt=>'FOR ALL COLUMNS SIZE AUTO', degree => 8);
ERCENT => DBMS_STATS.AUTO_SAMPLE_SIZE, METHOD_OPT => 'FOR ALL COLUMNS SIZE AUTO', DEGREE => 8, CASCADE =>
select blocks allocated_blks,
count( distinct substr(t.rowid,1,8)
||substr(t.rowid,15,4)) used
from user_segments e,
&tab_name t
where e.segment_name=upper ('&tab_name')
and e.segment_type='TABLE'
group by e.blocks;

SELECT *
FROM
TABLE(DBMS_XPLAN.display_sql_plan_baseline(plan_name=>'SYS_SQLPROF_015fdc7edac
e0003'));

http://rohitsinhago.blogspot.com/2009/05/tracing-other-sessions.html
SELECT sql_id,child_number,sql_text, elapsed_time
FROM (SELECT sql_id, child_number, sql_text, elapsed_time, cpu_time,
disk_reads,
RANK () OVER (ORDER BY elapsed_time DESC) AS elapsed_rank
FROM gv$sql)
WHERE elapsed_rank <= 10;
exec
dbms_sqltune.alter_sql_profile('SYS_SQLPROF_0236d8f37a490001','STATUS','DISABLED');

exec dbms_sqltune.alter_sql_profile('SQL_PROF_FOR_DELETE','STATUS','ENABLED');

EXEC DBMS_SQLTUNE.DROP_SQL_PROFILE('SYS_SQLPROF_02384d2b5e320000');

https://blog.yannickjaquier.com/oracle/visualizing-active-session-history-ash-to-produce-grid-control-charts.html
https://blogs.oracle.com/optimizer/setting-a-session-parameter-overrides-ofe

https://prasanthkothuri.files.wordpress.com/2015/06/who-changed-my-plan.pdf

https://prasanthkothuri.wordpress.com/2015/06/08/sql-patch-fast-way-to-add-a-hint-without-changing-the-code/

SELECT * FROM dba_advisor_definitions;

SELECT client_name, status, max_duration_last_30_days FROM DBA_AUTOTASK_CLIENT;


SELECT job_start_time, job_status, job_duration,WINDOW_NAME FROM
DBA_AUTOTASK_JOB_HISTORY
WHERE client_name='sql tuning advisor'
AND job_start_time >= SYSDATE -7
ORDER BY job_start_time DESC;
SET lines 750 pages 9999
col DESCRIPTION FOR a150
col parameter_name for a50
col parameter_value FOR a15
SELECT parameter_name,parameter_value,is_default,description
FROM DBA_ADVISOR_PARAMETERS
WHERE task_name='SYS_AUTO_SQL_TUNING_TASK'
ORDER BY parameter_name;

set lines 750 pages 9999


col execution_name for a15
col TASK_NAME for a30
col ERROR_MESSAGE for a100

SELECT execution_name,task_id,task_name,TO_CHAR(execution_start,'dd-mon-yyyy
hh24:mi:ss') AS execution_start,TO_CHAR(execution_end,'dd-mon-yyyy hh24:mi:ss') AS
execution_end,
status,error_message FROM DBA_ADVISOR_EXECUTIONS
WHERE task_name='SYS_AUTO_SQL_TUNING_TASK'
ORDER BY execution_id DESC;

SET LONG 999999999


SELECT
DBMS_AUTO_SQLTUNE.REPORT_AUTO_TUNING_TASK('&EXEC_ID_MIN','&EXEC_ID_MAX
','TEXT','ALL','SUMMARY') FROM dual;

(or) Most Recent

SET LONG 999999999


SELECT
DBMS_AUTO_SQLTUNE.REPORT_AUTO_TUNING_TASK(NULL,NULL,'TEXT','ALL','SUMMA
RY') FROM dual;
http://www.jamesmorle.com/the-oracle-wait-interface-is-useless-sometimes-pt/
Guidelines When SHARED_POOL_SIZE Is Too Small
The V$SHARED_POOL_RESERVED fixed table can also
indicate when the value for
SHARED_POOL_SIZE is too small. This may be the case if
REQUEST_FAILURES > 0 and
increasing.
Then, if you have enabled the reserved list, decrease the
value for
SHARED_POOL_RESERVED_SIZE. If you have not enabled
the reserved list, you could
increase SHARED_POOL_SIZE.
show parameter db_cache_size;

• Initial parameter values:


– SGA_MAX_SIZE = 128M,
- DB_CACHE_SIZE = 96M
– SHARED_POOL_SIZE = 32M
With S1 As (
Select /*+Parallel(X 10) */ Snap_Id,
Round(Sum(Singleblkrds)/1000000,1)
Megreads, Round(Sum(Singleblkrdtim)*10) Ms
From Dba_Hist_Filestatxs X
Where Snap_Id > &awr_id
Group By Snap_Id),
--
S2 As
(Select Snap_Id, Megreads - Lag(Megreads,1)
Over(Order By Snap_Id) Totrds,
Ms- Lag(Ms,1) Over (Order By Snap_Id) Tot_Ms
From S1 )
--
Select Snap_Id, Totrds Megards,
Round(Tot_Ms/Totrds/1000000,1)
"Latency(Ms)" From S2
Where Totrds > 1 For over a period using awr snap_id
It should be less than < 8 ms
mple_size,method_opt=>'FOR ALL COLUMNS SIZE AUTO', granularity => 'ALL', degree => 8);

S SIZE AUTO', degree => 8);


ZE AUTO', DEGREE => 8, CASCADE => TRUE);
<-- displays the plan_name recommendation in details
ce-grid-control-charts.html
This link is having performance tunign of CERN nuclear system , having manual sql profile creations

ithout-changing-the-code/
SET LINESIZE 80 PAGESIZE 1000 LONG 100000
SELECT
DBMS_SQLTUNE.REPORT_TUNING_TASK('SYS_AUTO_S
QL_TUNING_TASK') FROM DUAL;
Database

Database Size
Table

Table size in MB

Each Table Size under a Schema


Schema

Schema size in GB

Each Schema Size in MB


Tablespace

Tablespace Free

datafiles under tablespace

Temp Tablespace Usage

Db block size
What is the minimum size we can reduce for a datafile

How much size we can reduce a datafile

List the size of Oracle stored procedures

Top 10 large tables

INDEX larger than Table size for rebuilding

Extent That going to get failed in Next Extent


Table fragmentation
CDB

select a.data_size+b.temp_size+c.redo_size+d.controlfile_size
"total_size in MB" from ( select sum(bytes)/1024/1024 data_size
from dba_data_files) a,( select nvl(sum(bytes),0)/1024/1024
temp_size from dba_temp_files ) b,( select sum(bytes)/1024/1024
redo_size from sys.v_$log ) c,
( select sum(BLOCK_SIZE*FILE_SIZE_BLKS)/1024/1024
controlfile_size from v$controlfile) d;
select
segment_name table_name,
select segment_name,sum(bytes)/(1024*1024)
sum(bytes)/(1024*1024) table_size_meg "TABLE_SIZE(MB)"
from
from dba_extents where segment_type='TABLE' and
owner=upper('&OWNER')
dba_extents and segment_name
=upper(
where '&SEGMENT_NAME') group by segment_name;
segment_type='TABLE'
and
setowner='GLOGOWNER'
lines 750 pages 9999 group by segment_name order by 2 desc;
SELECT ts.tablespace_name, "File Count",
TRUNC("SIZE(MB)", 2) "Size(MB)",
TRUNC(fr."FREE(MB)", 2) "Free(MB)",
SELECT owner,tablespace_name,Sum(bytes)/1024/1024/1024 AS
TRUNC("SIZE(MB)"
total_size_gb - "FREE(MB)", 2) "Used(MB)",
df."MAX_EXT"
FROM dba_segments "Max Ext(MB)",
(fr."FREE(MB)" / df."SIZE(MB)")
WHERE owner =upper('&1') * 100
group by "% Free"
owner,tablespace_name;
FROM (SELECT tablespace_name,
select owner,sum(bytes/1024/1024) ||'M' from dba_segments group
SUM (bytes) / (1024 * 1024) "FREE(MB)"
by owner order by sum(bytes/1024/1024) desc;
FROM dba_free_space
GROUP BY tablespace_name) fr,
(SELECT tablespace_name, SUM(bytes) / (1024 * 1024) "SIZE(MB)",
COUNT(*)
"File Count", SUM(maxbytes) / (1024 * 1024) "MAX_EXT"
FROM dba_data_files
GROUP BY tablespace_name) df,
(SELECT tablespace_name
FROM dba_tablespaces) ts
SELECT A.tablespace_name
WHERE fr.tablespace_name = tablespace, D.mb_total,
df.tablespace_name (+)
SUM (A.used_blocks * D.block_size)
AND fr.tablespace_name = ts.tablespace_name / 1024(+)
/ 1024 mb_used,
ORDER D.mb_total - SUM (A.used_blocks * D.block_size) / 1024 / 1024
BY ts.tablespace_name;
mb_free
col file_name for a60
FROM
select gv$sort_segment A,
(
TABLESPACE_NAME,FILE_ID,FILE_NAME,BYTES/1024/1024 "size
in SELECT B.name, C.block_size, SUM (C.bytes) / 1024 / 1024
mb_total
MB",AUTOEXTENSIBLE,MAXBYTES/1024/1024,ONLINE_STATUS
FROM v$tablespace
from dba_data_files where B, v$tempfile C
WHERE B.ts#= C.ts#
TABLESPACE_NAME='&TABLESPACE_NAME';
GROUP BY B.name, C.block_size
)D
WHERE A.tablespace_name = D.name
GROUP by A.tablespace_name, D.mb_total;

column value new_val blksize


select value from v$parameter where name = 'db_block_size'
/
ceil(hwm_bytes/1024/1024)||'M;'
else -- generate only a comment when autoextensible is off
set '/* verify
reclaim off'||to_char(ceil((bytes-hwm_bytes)/1024/1024),999999)
column||'M fromfile_name format a50 word_wrapped
'||to_char(ceil(bytes/1024/1024),999999)
column smallest
||'M after settingformat 999,990 heading
autoextensible maxsize"Smallest|Size|Poss."
higher than current size for
column
file ' currsize format 999,990 heading "Current|Size"
column savings */'
|| file_name||' format 999,990 heading "Poss.|Savings"
break
end SQL on report
compute
from hwmdf sum of savings on report
where
column value new_val blksize -- resize only if at least 1MB can be
bytes-hwm_bytes>1024*1024
select
reclaimed from v$parameter where name = 'db_block_size'
value
/order by bytes-hwm_bytes desc
column num_instances heading "Num" format 999
/column type heading "Object Type" format a12
select file_name,
column source_size heading "Source" format 99,999,999
ceil( (nvl(hwm,1)*&&blksize)/1024/1024 ) smallest,
column parsed_size heading "Parsed" format 99,999,999
ceil( blocks*&&blksize/1024/1024) currsize,
column code_size heading "Code" format 99,999,999
ceil( blocks*&&blksize/1024/1024) -
column error_size heading "Errors" format 999,999
ceil( (nvl(hwm,1)*&&blksize)/1024/1024 ) savings
column size_required heading "Total" format 999,999,999
from dba_data_files a,
compute sum of size_required on report
( select file_id, max(block_id+blocks-1) hwm
from dba_extents
select count(name) num_instances
group by file_id ) b
,type
where a.file_id = b.file_id(+)
,sum(source_size) source_size
/
,sum(parsed_size) parsed_size
,sum(code_size) code_size
,sum(error_size) error_size
,sum(source_size)
+sum(parsed_size)
+sum(code_size)
+sum(error_size) size_required
select si.owner,si.tablespace_name, i.index_name, t.table_name,
from dba_object_size
round(si.bytes/1024/1024,1)
group by type index_mb, round(st.bytes/1024/1024,1)
table_mb,
order by 2
round(si.bytes/st.bytes*100,1)
/ pct_larger
from dba_segments si, dba_indexes i, dba_tables t, dba_segments st
where si.owner = i.owner
select
and * from (select owner,segment_name,
si.segment_name = i.index_name bytes/1024/1024 meg
fromsi.tablespace_name=i.tablespace_name
and dba_segments
and where segment_type
si.segment_type = 'TABLE' and owner not in
= 'INDEX'
('SYS','SYSTEM','DBSNMP','APEX_040200','MDSYS')
and i.table_owner = t.owner
and order by bytes/1024/1024
i.table_name = t.table_namedesc) where rownum <= 10;
and t.owner = st.owner
and t.table_name = st.segment_name
and st.segment_type = 'TABLE'
and si.bytes > st.bytes
and si.bytes> 100*1024*1024 /* Larger than 100 MB */
order by pct_larger desc
SELECT
segment_name,OWNER,segment_type,extents,max_extents,TABLE
SPACE_NAME
FROM dba_segments
WHERE extents > max_extents - 10;
select
table_name,round((blocks*8),2) "size (kb)" ,
round((num_rows*avg_row_len/1024),2) "actual_data (kb)",
(round((blocks*8),2) - round((num_rows*avg_row_len/1024),2))
"wasted_space (kb)"
from
dba_tables
where owner='&OWNER' and table_name='&TABLE_NAME' and
(round((blocks*8),2) > round((num_rows*avg_row_len/1024),2))
order by 4 desc;
column dummy noprint GROUP BY
column pct_used format 999.9 heading "%|Used" c.con_id,name
column name format a19 heading "Tablespace Name" UNION
column Kbytes format 999,999,999 heading "KBytes" select
column used format 999,999,999 heading "Used" c.con_id,nvl(p.name,
column free format 999,999,999 heading "Free" 'CDB') name ,
column largest format 999,999,999 heading "Largest" sum(bytes)/1024/10
column
PDB max_size format 999,999,999 heading "MaxPoss|Kbytes" CDB
24 WITH ALL
SIZE_MB PDB
from
column pct_max_used format 999.9 heading "%|Max|Used" cdb_temp_files c,
break on report v$pdbs p where
compute sum of kbytes on report c.con_id=p.con_id(+)
compute sum of free on report "total_size in MB"
select a.data_size+b.temp_size GROUP BY
compute sumsum(bytes)/1024/1024
from ( select of used on report data_size c.con_id,name
from dba_data_files) a, )group by
select
( select(select decode(extent_management,'LOCAL','*','
nvl(sum(bytes),0)/1024/1024 temp_size ') || con_id,name
decode(segment_space_management,'AUTO','a
from dba_temp_files ) b; ','m ') order by con_id;
from dba_tablespaces where tablespace_name = b.tablespace_name) ||
nvl(b.tablespace_name,
nvl(a.tablespace_name,'UNKOWN')) name,
kbytes_alloc kbytes,
kbytes_alloc-nvl(kbytes_free,0) used,
nvl(kbytes_free,0) free,
((kbytes_alloc-nvl(kbytes_free,0))/
kbytes_alloc)*100 pct_used,
nvl(largest,0) largest,
nvl(kbytes_max,kbytes_alloc) Max_Size,
decode( kbytes_max, 0, 0, (kbytes_alloc/kbytes_max)*100) pct_max_used
from ( select sum(bytes)/1024 Kbytes_free,
max(bytes)/1024 largest,
tablespace_name
from sys.dba_free_space
group by tablespace_name ) a,
( select sum(bytes)/1024 Kbytes_alloc,
sum(maxbytes)/1024 Kbytes_max,
tablespace_name SELECT
from sys.dba_data_files tablespace_name,
group by tablespace_name select b.Total_MB,
SUM (bytes) / (1024
union all b.Total_MB -
* 1024) "FREE(MB)"
select sum(bytes)/1024 Kbytes_alloc, round(a.used_blocks
FROM
sum(maxbytes)/1024 Kbytes_max, *8/1024)
dba_free_space
tablespace_name Current_Free_MB,
where
from sys.dba_temp_files tablespace_name=U
group by tablespace_name )b round(used_blocks*
PPER('&TABLESPA
where a.tablespace_name (+) = b.tablespace_name 8/1024)
CE_NAME')
SELECT
order by 4 A.tablespace_name tablespace, D.mb_total, Current_Used_MB,
GROUP BY
/ SUM (A.used_blocks * D.block_size) / 1024 / 1024 mb_used, tablespace_name;
D.mb_total - SUM (A.used_blocks * D.block_size) / 1024 / 1024 mb_free round(max_used_bl
FROM v$sort_segment A, ocks*8/1024)
( Max_used_MB
SELECT B.name, C.block_size, SUM (C.bytes) / 1024 / 1024 mb_total from v$sort_segment
FROM v$tablespace B, v$tempfile C a,
WHERE B.ts#=
alter tablespace C.ts#
USERTABLESPACE add datafile '+DATAGROUP' size 10G; (select
GROUP BY B.name, C.block_size round(sum(bytes)/10
)D 24/1024) Total_MB
WHERE A.tablespace_name = D.name from
GROUP by A.tablespace_name, D.mb_total; dba_temp_files ) b;
where
df.file_id = &file_id
and
df.file_id = ex.file_id
and
df.tablespace_name
=
ts.tablespace_name
order by
ex.block_id desc
)
Script to Command to resize where rownum
------------------------------------------ <= 100
column
Good query valueruns
new_val
fasterblksize
than the next query below /
select value from v$parameter where name = 'db_block_size'
/
column cmd format a75 word_wrapped

select 'alter database datafile '''||file_name||''' resize ' ||


ceil( (nvl(hwm,1)*&&blksize)/1024/1024 ) || 'm;' cmd
from dba_data_files a,
( select file_id, max(block_id+blocks-1) hwm
from dba_extents
group by file_id ) b
where a.file_id = b.file_id(+)
and ceil( blocks*&&blksize/1024/1024) -
ceil( (nvl(hwm,1)*&&blksize)/1024/1024 ) > 0
/

http://oracletechdba.blogspot.com/2014/08/oracle-to-find-over-sizedfragmented.html
http://stelliosdba.blogspot.com/2012/03/ora-03297-file-contains-used-data.html http://blog.dbi-services.com/resiz
http://blog.dbi-services.com/resize-your-oracle-datafiles-down-to-the-minimum-without-ora-03297/
find services belongs to pdb

pdb name for a service

find cdb name from pdb name

Close and opne PDB's

connect to PDB directly

registering the service on CRS

Relocate services
COLUMN name FORMAT A30
SELECT name, pdb FROM v$services ORDER BY name;
export CHANGE_ME=abcd_srv
crsctl status resource -t|grep -iw $CHANGE_ME |grep ora.*.svc|cut -f2 -d. |
while read line ; do
echo -e "\033[0;31mDatabase Name: \033[0;0m"$line
echo -e "\033[0;31mNodes: \033[0;0m"`crsctl stat res ora.$line.db -p | grep
"GEN_USR_ORA_INST_NAME@SERVERNAME" | cut -f 2 -d'@'`;
ORACLE_HOME=`crsctl stat res ora.$line.db -p | grep -iw ORACLE_HOME | cut -d'=' -f2` ; export
ORACLE_HOME
echo -e "\033[0;31mPDB: \033[0;0m"`$ORACLE_HOME/bin/srvctl config service -d $line -s
$CHANGE_ME | grep -i "Pluggable database name" | cut -f2 -d:`;
done ; unset CHANGE_ME

ps -ef | grep tns | grep SCAN | awk {'print $9'} |


while read line ; do
lsnrctl status $line | grep -i pdb_name -A 2
done

alter pluggable database <PDB_NAME> close immediate instances=ALL;


alter pluggable database <PDB_NAME> open instances=ALL;
alter pluggable database <PDB_NAME> close instances=('INST1');

sid (or) . oraenv --> to cdb then


connect to pdb : export TWO_TASK=PDB1

collabn1:/home/oracle[RAC1]$ srvctl add service -d RAC -pdb PDB -s svctest -r RAC1 -a RAC2 -P
BASIC
collabn1:/home/oracle[RAC1]$ srvctl start service -d RAC -s svctest
srvctl status service -d <db_name> -s <service>
srvctl relocate service -d RAC12C -s <service> -oldinst <INST1> -newinst <INST2>
export CHANGE_ME=servicenamepls
crsctl status resource -t|grep -i $CHANGE_ME |grep ora.*.svc|cut -f2 -d. |
while read line ; do
echo -e "\033[0;31mDatabase Name: \033[0;0m"$line
echo -e "\033[0;31mNodes: \033[0;0m"`srvctl config database -d $line | grep
"Configured nodes" | cut -f2 -d:`;
echo -e "\033[0;31mPDB: \033[0;0m"`srvctl config service -d $line -s
$CHANGE_ME | grep -i "Pluggable database name" | cut -f2 -d:`;
done ; unset CHANGE_ME

srvctl add service -db RAC12C -service TAFSRV -preferred RAC12C1 -available
RAC12C2 \
-tafpolicy BASIC -policy AUTOMATIC -failovertype SELECT -failovermethod BASIC \
-failoverretry 5 -pdb DEMOPDB -verbose
srvctl start service -d RAC12C -s TAFSRV
<---- input the service name
Rman Tuning

RMAN Examples & scenarios

Rman script to run in background

Get the latest SCN by using the below


command.

Clone Progress
% completed - Good query

Rman throughput speed -good query

RMAN backup speed history

Running RMAN info ( Good Query)

To see RMAN Config in sqlplus

last 7 days backup report (Best)


Short RMAN report

RMAN Backup Report

RMAN output Log File Viewing

Yesterdays Backup output / Status

RMAN Backup Available or not

Available Backup Size

Obsolete BACKUP SIZE


Day wise backup size

RMAN Currently running or not

Files Need Recovery

How long we can go back using RMAN Backup

Block Recovery

Object under corrupted block

if the v$database_block_corruption is not showing anything then (refer


the link. That is good )

Skip the corrupted block

extract usefull data from corrupted table


refer this link for block corruption , if RMAN block recover command is not
working

RMAN catalog version

Unregister from catalog

To see the dbid from catalog

SBT - RMAN interaction

SET NEWNAME FOR DATAFILE

ALTER DATABASE RENAME FILE


Backup Failure report
Datafile report

RMAN catalog report ( Completion time is older than 7 days)


Oldest backup available

Oldest backup Available in rman catalog ( this gives result of all datafile
oldest backup)

Oldest backup Available in rman catalog ( this gives result of just


time stamp)
backup throughput

restore/duplicate throughput
Backup not deleting the archivelog
ORA-19625: error identifying file
ORA-17503: ksfdopn:2 Failed to open file
ORA-15012: ASM file '+BKUP/thread_1_seq_49222.1018.892640727'
does not exist

ORA-01113: file 1 needs media recovery


ORA-01110: data file 1: '/OraData/SIAMST/siamst_system.dbf

history of my database incarnations

%FRA Used

Tracing RMAN

restoring missing archive log file


standby archivelog deletion command

Backup the backup sets from ASM disk to TAPE


http://www.oraclecoursebooks.com/books/oracle10g_rman/12_10g_rman/oracle10g_rman12.HTM

https://web.stanford.edu/dept/itss/docs/oracle/10gR2/backup.102/b14191/rcmdupdb006.htm

oracle@hostname$ cat rman_db1_clone.sh


nohup rman target sys/pwd@db1 catalog user/pwd@rcat_db auxiliary /
cmdfile='rman_db1_clone.rcv' log='rman_db1_clone.log' &
oracle@hostname$ cat rman_db1_clone.rcv
run{
allocate auxiliary channel aux1 type 'sbt_tape' parms
'ENV=(TDPO_OPTFILE=/usr/tivoli/tsm/client/oracle/bin64/tdpo.opt.host123)';
allocate auxiliary channel aux2 type 'sbt_tape' parms
'ENV=(TDPO_OPTFILE=/usr/tivoli/tsm/client/oracle/bin64/tdpo.opt.host123)';
allocate auxiliary channel aux3 type 'sbt_tape' parms
'ENV=(TDPO_OPTFILE=/usr/tivoli/tsm/client/oracle/bin64/tdpo.opt.host123)';
SET NEWNAME FOR DATAFILE 1 to '/db/db1/d1/DB2SYS.DBF';
SET NEWNAME FOR DATAFILE 2 to '/db/db1/d2/DB2UNDOT1A.DBF';
SET NEWNAME FOR DATAFILE 3 to '/db/db1/d1/DB2TLST1A.DBF';
SET NEWNAME FOR DATAFILE 4 to '/db/db1/d2/DB2USRT1A.DBF';
SET NEWNAME FOR DATAFILE 5 to '/db/db1/d13/DB2RAPT7R.DBF';
SET NEWNAME FOR DATAFILE 6 to '/db/db1/d12/DB2RAPI7O.DBF';
SET NEWNAME FOR DATAFILE 7 to '/db/db1/d14/DB2RAPT7I.DBF';
duplicate target database to db2;
}

select max(first_change#) chng


from v$archived_log
/

COLUMN sid FORMAT 999


COLUMN serial# FORMAT 9999999
COLUMN machine FORMAT A30
COLUMN progress_pct FORMAT 99999999.00
COLUMN elapsed FORMAT A10
COLUMN remaining FORMAT A10
SELECT sl.opname,s.sid,
s.serial#,
s.machine,
TRUNC(sl.elapsed_seconds/60) || ':' || MOD(sl.elapsed_seconds,60) elapsed,
TRUNC(sl.time_remaining/60) || ':' || MOD(sl.time_remaining,60) remaining,
ROUND(sl.sofar/sl.totalwork*100, 2) progress_pct
FROM v$session s,
v$session_longops sl
WHERE s.sid = sl.sid
AND s.serial# = sl.serial#;
column Pct_Complete format 99.99
column client_info format a25
column sid format 999
column MB_PER_S format 999.99
select s.client_info,
l.sid,
l.serial#,
l.sofar,
l.totalwork,
round (l.sofar / l.totalwork*100,2) "Pct_Complete",
aio.MB_PER_S,
SELECT SID, SERIAL#, CONTEXT, SOFAR, TOTALWORK,opname ,
aio.LONG_WAIT_PCT
ROUND(SOFAR/TOTALWORK*100,2)
from v$session_longops l, "%_COMPLETE", Time_remaining
FROM
v$sessionV$SESSION_LONGOPS
s,
WHERE OPNAME LIKE 'RMAN%'
(select sid,
AND OPNAME NOT LIKE '%aggregate%'
serial,
AND sum
100* TOTALWORK != 0
(long_waits) / sum (io_count) as "LONG_WAIT_PCT",
AND (effective_bytes_per_second)/1024/1024
sum SOFAR != TOTALWORK; as "MB_PER_S"
from v$backup_async_io
group by sid, serial) aio
where aio.sid = s.sid
and aio.serial = s.serial#
and l.opname like 'RMAN%'
and l.opname not like '%aggregate%'
and l.totalwork != 0
and l.sofar <> l.totalwork
select to_char(START_TIME,'MM-DD-YYYY
and s.sid = l.sid HH24:MI:SS') as
START_TIME,to_char(END_TIME,'MM-DD-YYYY
and s.serial# = l.serial# HH24:MI:SS') as
END_TIME,ELAPSED_SECONDS/60/60,INPUT_BYTES/1024/1024/1024/1024
order by 1; as
INPUT_TB,OUTPUT_BYTES/1024/1024/1024/1024 as
OUTPUT_TB,INPUT_BYTES_PER_SEC/1024/1024 as
INPUT_SEC_MB,OUTPUT_BYTES_PER_SEC/1024/1024 as
OUTPUT_SEC_MB,status from
V$RMAN_BACKUP_job_details where INPUT_TYPE like 'DB%INCR%';

SELECT p.SPID, s.sid, s.serial#, sw.EVENT, sw.SECONDS_IN_WAIT AS


SEC_WAIT, sw.STATE, CLIENT_INFO
FROM V$SESSION_WAIT sw, V$SESSION s, V$PROCESS p
WHERE s.client_info LIKE 'rman%'
AND s.SID=sw.SID
AND s.PADDR=p.ADDR;

select * from v$rman_configuration;

COL STATUS FORMAT a25


COL HRS FORMAT 999.99
COL start_time format a15
COL end_time format a15
COL in_size FORMAT a10

SELECT INPUT_TYPE,
STATUS,
TO_CHAR(START_TIME,'mm/dd/yy hh24:mi') start_time,
TO_CHAR(END_TIME,'mm/dd/yy hh24:mi') end_time,
INPUT_BYTES_DISPLAY in_size,
round(ELAPSED_SECONDS/3600,3) HRS
FROM V$RMAN_BACKUP_JOB_DETAILS
where sysdate - start_time <= 7;
left outer join
SELECT (select
where s.input_file_scan_only = 'NO'
d.session_recid,
bs.recid group by d.session_recid, d.session_stamp,
bs_key d.session_stamp) x
on sum(case
x.session_recid
, bp.tag = when d.controlfile_included
j.session_recid = 'YES' then
and x.session_stamp d.piecestag
else 0 end)
= j.session_stamp
CF,
,left outer join (select o.session_recid, o.session_stamp, min(inst_id) inst_id
DECODE(backup_type
sum(case
from
, 'L', 'Archived when
GV$RMAN_OUTPUT
Redo d.controlfile_included
Logs' o = 'NO'
, 'D', 'Datafile and
group byFull d.backup_type||d.incremental_level
o.session_recid,
Backup' o.session_stamp) = 'D' then d.pieces else 0
end) DF,
ro on, 'I',
ro.session_recid = j.session_recid
'Incremental Backup' ) and ro.session_stamp = j.session_stamp
backup_type
where sum(case
j.start_time
, bs.incremental_level when d.backup_type||d.incremental_level = 'D0' then d.pieces
> trunc(next_day(sysdate-6,'SUNDAY'))
else
order0by end) I0,
j.start_time
incremental_level
/ , DECODE( sum(case bp.statuswhen d.backup_type||d.incremental_level = 'I1' then d.pieces
else 0 end) I1,
, 'A', 'Available'
sum(case when d.backup_type = 'L' then d.pieces else 0 end) L
, 'D', 'Deleted'
from
, 'X', 'Expired' ) status
V$BACKUP_SET_DETAILS
, DECODE(bs.controlfile_included, 'NO',d '-', bs.controlfile_included)
controlfile_included join V$BACKUP_SET s on s.set_stamp = d.set_stamp and s.set_count =
d.set_count
, NVL(sp.spfile_included, '-') spfile_included
, bs.pieceswhere s.input_file_scan_only = 'NO' pieces
group by d.session_recid,
, TO_CHAR(bs.start_time, 'mm/dd/yyyy d.session_stamp)
HH24:MI:SS') x start_time
on x.session_recid = j.session_recid
, TO_CHAR(bs.completion_time, and x.session_stamp
'mm/dd/yyyy HH24:MI:SS')= j.session_stamp
completion_time
left outer join
, bs.elapsed_seconds (select o.session_recid, o.session_stamp, min(inst_id) inst_id
elapsed_seconds from GV$RMAN_OUTPUT o
, bs.block_size group by o.session_recid, o.session_stamp) block_size
ro on
, bs.keep ro.session_recid = j.session_recid and keep ro.session_stamp = j.session_stamp
order by j.start_time desc;
, NVL(TO_CHAR(bs.keep_until, 'mm/dd/yyyy HH24:MI:SS'),'') keep_until
, bs.keep_options keep_options
, device_type device_type
FROM
select output
v$backup_set bs
from GV$RMAN_OUTPUT
, (select distinct
whereset_stamp
session_recid = &SESSION_RECID
and, session_stamp
set_count = &SESSION_STAMP
order, tagby recid;
, device_type
, status
from v$backup_piece
where status in ('A','D', 'X')) bp
, (select distinct set_stamp, set_count, 'YES' spfile_included
from v$backup_spfile) sp
select output
WHERE
frombs.set_stamp
v$rman_output = bp.set_stamp
where session_recid==bp.set_count
AND bs.set_count (select max(session_recid) from v$rman_status)
order
ANDby recid ;
bs.set_stamp = sp.set_stamp (+)
AND bs.set_count = sp.set_count (+)
ORDER BY
bs.start_time desc;

select round(sum(bytes/1024/1024/1024),2) bsize from v$backup_piece where


STATUS='A';
SELECT SUM(BYTES/1024/1024/1024) FROM V$BACKUP_FILES where
OBSOLETE='YES' and FNAME is not null and ((FILE_TYPE='PIECE' and
BACKUP_TYPE='BACKUP SET') or BACKUP_TYPE='COPY')
select ctime "Date"
, decode(backup_type, 'L', 'Archive Log', 'D', 'Full', 'Incremental') backup_type
, bsize "Size MB"
from (select trunc(bp.completion_time) ctime
, backup_type
, round(sum(bp.bytes/1024/1024),2) bsize
from v$backup_set bs, v$backup_piece bp
where bs.set_stamp = bp.set_stamp
COLUMN CLIENT_INFO
and bs.set_count FORMAT a30
= bp.set_count
COLUMN SID FORMAT
and bp.status = 'A' 999
COLUMN
group by SPID FORMAT 9999
trunc(bp.completion_time), backup_type)
order by 1, 2;
SELECT s.SID, p.SPID, s.CLIENT_INFO
FROM V$PROCESS p, V$SESSION s
WHERE p.ADDR = s.PADDR
AND CLIENT_INFO LIKE 'rman%'
/

SELECT * FROM V$RECOVER_FILE;

select TO_CHAR(min(bs.completion_time),'DD/MM/YYYY HH24:MI') completion_time


from v$backup_set bs, v$backup_piece bp where
bs.set_stamp = bp.set_stamp
AND bs.set_count = bp.set_count and bs.backup_type='D'
AND bp.status='A';

blockrecover datafile 8 block 13;

SELECT owner, segment_name, segment_type


FROM dba_extents
WHERE file_id = 1
AND 16516 BETWEEN block_id AND block_id + blocks - 1;

RMAN> validate tablespace corrupt;

BEGIN
DBMS_REPAIR.SKIP_CORRUPT_BLOCKS (
SCHEMA_NAME => 'SCOTT',
OBJECT_NAME => 'DEPT',
OBJECT_TYPE => dbms_repair.table_object,
FLAGS => dbms_repair.skip_flag);
END;
/
SQL> exec DBMS_REPAIR.SKIP_CORRUPT_BLOCKS( 'MANA', 'TAXINQUIRY_LOG' );
PL/SQL procedure successfully completed.
Querying scott's tables using the DBA_TABLES view shows that SKIP_CORRUPT is enabled
SQL> insert into MANA.TAXINQUIRY_LOG_REPAIR ( select * from
for table scott.dept.
MANA.TAXINQUIRY_LOG );
68 rows created.
SELECT OWNER, TABLE_NAME, SKIP_CORRUPT FROM DBA_TABLES
SQL> commit;
WHERE OWNER = 'SCOTT';
Commit complete.
SQL> drop table MANA.TAXINQUIRY_LOG;
Table dropped.
SQL> alter table TAXINQUIRY_LOG_REPAIR rename to TAXINQUIRY_LOG;
Table altered.
SQL> alter system flush shared_pool;
System altered.
Note: if any error while creating table (SCRIPT to skip ORA-8103 ORA-1410 ORA-1578 ORA-
600 [kdsgrp1] when reading a TABLE (Doc ID 1527738.1)) this metalink note will help

https://docs.oracle.com/cd/B10501_01/server.920/a96521/repair.htm

select * from schemaname.rcver;

RUN
{
SET DBID 3668200963;
UNREGISTER DATABASE DB_NAME NOPROMPT;
}

select DBID, NAME ,STATUS from RC_DATABASE_INCARNATION where name like


'%IKB%'

COLUMN EVENT FORMAT a10


COLUMN SECONDS_IN_WAIT FORMAT 999
COLUMN STATE FORMAT a20
COLUMN CLIENT_INFO FORMAT a30

SELECT p.SPID, EVENT, SECONDS_IN_WAIT AS SEC_WAIT,


sw.STATE, CLIENT_INFO
FROM V$SESSION_WAIT sw, V$SESSION s, V$PROCESS p
WHERE sw.EVENT LIKE 's%bt%'
AND s.SID=sw.SID
AND s.PADDR=p.ADDR
;

select 'SET NEWNAME FOR DATAFILE ' || FILE# || ' TO ''' || '/u03/oradata/&1/' ||
substr(name,instr(name,'/',-
1)+1) || ''';' from v$datafile;

SELECT 'SQL "ALTER DATABASE RENAME FILE '''''|| MEMBER ||'''''' ||chr(10)||'to ''''' ||
member || '''''" ;' FROM
V$LOGFILE;
from v105.rc_database a,v105.bs b
where a.db_key=b.db_key
and b.bck_type is not null having max(start_time) < sysdate - 7
group by a.name,dbid,b.bck_type
) group by db,dbid
union
select 'V112 - ' ||DB NAME,dbid,min(backuptype_db) DBBKP,min(backuptype_arch)
ARCBKP
from (
select a.name DB,dbid,
decode(b.bck_type,'D',max(b.completion_time),'I',
max(b.completion_time)) BACKUPTYPE_db,
decode(b.bck_type,'L',
max(b.completion_time)) BACKUPTYPE_arch
from v112.rc_database a,v112.bs b
where a.db_key=b.db_key
and b.bck_type is not null having max(start_time) < sysdate - 7
group by a.name,dbid,b.bck_type
) group by db,dbid
union
select 'isp102 - ' ||DB NAME,dbid,min(backuptype_db) DBBKP,min(backuptype_arch)
ARCBKP
from (
select a.name DB,dbid,
decode(b.bck_type,'D',max(b.completion_time),'I',
max(b.completion_time)) BACKUPTYPE_db,
decode(b.bck_type,'L',
max(b.completion_time)) BACKUPTYPE_arch
from isp102.rc_database a,isp102.bs b
where a.db_key=b.db_key and a.name not in
('RTL0892','RTL0890','RTL0888','RTL0007','RTL0881')
and b.bck_type is not null having max(start_time) < sysdate - 7
group by a.name,dbid,b.bck_type
) group by db,dbid
;
end if;

sys.dbms_output.put_line(rpad(r.fname,25)||' '||d0||d1||d2||d3||d4||d5||d6||' '||


to_char(c0+c1+c2+c3+c4+c5+c6)||'/7'||' '||to_char(ct,'MM/DD HH24:MI'));

b0 := b0+c0;
b1 := b1+c1;
b2 := b2+c2;
b3 := b3+c3;
b4 := b4+c4;
b5 := b5+c5;
b6 := b6+c6;

rows := rows+1;

end loop;

select max(completion_time) into ct from &_DB.BDF;


sys.dbms_output.put_line('-------------------------- --- --- --- --- --- --- --- ---- -----------');
sys.dbms_output.put_line(rpad('datafiles backed up',24)||' '||to_char(b0,9000)||
to_char(b1,9000)||to_char(b2,9000)||to_char(b3,9000)||to_char(b4,9000)||
to_char(b5,9000)||to_char(b6,9000)||' /'||rpad(to_char(rows),3)||' '||to_char(ct,'MM/DD
HH24:MI'));
sys.dbms_output.put_line(rpad('percentage',24)||' '||to_char((b0/rows)*100,9000)||
to_char((b1/rows)*100,9000)||to_char((b2/rows)*100,9000)||
to_char((b3/rows)*100,9000)||to_char((b4/rows)*100,9000)||
to_char((b5/rows)*100,9000)||to_char((b6/rows)*100,9000)||' '||
to_char(((b0+b1+b2+b3+b4+b5+b6)*100/rows/7), 9000)||' '||to_char(mct,'MM/DD
HH24:MI'));

end;
/

drop table &_DB.BDF;

set feedback on
set verify on

select 'V92 - ' ||DB NAME,dbid,min(backuptype_db) DBBKP,min(backuptype_arch)


ARCBKP
from (
select a.name DB,dbid,
decode(b.bck_type,'D',max(b.completion_time),'I',
max(b.completion_time)) BACKUPTYPE_db,
decode(b.bck_type,'L',
max(b.completion_time)) BACKUPTYPE_arch
from v92.rc_database a,v92.bs b
where a.db_key=b.db_key
and b.bck_type is not null having max(start_time) < sysdate - 7
group by a.name,dbid,b.bck_type
) group by db,dbid
V92

v102 SELECT DISTINCT dbi.db_name,


bdf.completion_time,
df.file#,
fname,
v104 tag
FROM v112.dbinc dbi,
v112 v112.bdf,
v112.ts,
v112.df,
v112.bp,
v112.node,
v112.site_dfatt
WHERE dbi.dbinc_key = ts.dbinc_key
AND ts.dbinc_key = df.dbinc_key
v121 AND ts.ts# = df.ts#
select DB NAME,dbid,NVL(TO_CHAR(min(backuptype_db),'DD/MM/YYYY
AND ts.create_scn = df.ts_create_scn
HH24:MI'),'01/01/0001:00:00') DBBKP,
AND dbi.dbinc_key = df.dbinc_key
NVL(TO_CHAR(min(backuptype_arch),'DD/MM/YYYY HH24:MI'),'01/01/0001:00:00')
ARCBKPAND bdf.dbinc_key = df.dbinc_key
from (AND node.db_key = dbi.db_key
selectAND bdf.file#
a.name = df.file#
DB,dbid,
AND (bdf.incr_level = 0 OR bdf.incr_level IS NULL)
decode(b.bck_type,'D',min(b.completion_time),'I', min(b.completion_time))
AND node.site_key
BACKUPTYPE_db, = site_dfatt.site_key
AND df.df_key = site_dfatt.df_key
decode(b.bck_type,'L',min(b.completion_time)) BACKUPTYPE_arch
AND bdf.bs_key
from rc_database a,bs=bbp.bs_key
whereAND dbi.db_name='D1OIM' order by 2;
a.db_key=b.db_key
and a.name='D1OIM'
and b.bck_type is not null
and b.bs_key not in(Select bs_key from rc_backup_controlfile where
AUTOBACKUP_DATE
is not null or AUTOBACKUP_SEQUENCE is not null)
and b.bs_key not in(select bs_key from rc_backup_spfile)
group by a.name,dbid,b.bck_type
) group by db,dbid
ORDER BY least(to_date(DBBKP,'DD/MM/YYYY
HH24:MI'),to_date(ARCBKP,'DD/MM/YYYY HH24:MI'))
/
SELECT
'BACKUP THROUGHPUT',
round(SUM(v.value/1024/1024),1) mbytes_sofar,
round(SUM(v.value /1024/1024)/nvl((SELECT MIN(elapsed_seconds)
FROM v\$session_longops
WHERE OPNAME LIKE 'RMAN: aggregate output'
AND SOFAR != TOTALWORK
AND elapsed_seconds IS NOT NULL
),SUM(v.value /1024/1024)),2) mbytes_per_sec,
n.name
FROM gv\$sesstat v,
v\$statname n,
gv\$session s
WHERE v.statistic#=n.statistic#
AND n.name = 'physical read total bytes'
AND v.sid = s.sid
AND v.inst_id=s.inst_id
AND s.program like 'rman@%'
GROUP BY 'BACKUP THROUGHPUT',n.name;

SELECT
'DUPLICATE/RESTORE THROUGHPUT',
round(SUM(v.value/1024/1024),1) mbytes_sofar,
round(SUM(v.value /1024/1024)/nvl((SELECT MIN(elapsed_seconds)
FROM v\$session_longops
WHERE OPNAME LIKE 'RMAN: aggregate input'
AND SOFAR != TOTALWORK
AND elapsed_seconds IS NOT NULL
),SUM(v.value /1024/1024)),2) mbytes_per_sec,
n.name
FROM gv\$sesstat v,
v\$statname n,
gv\$session s
WHERE v.statistic#=n.statistic#
AND n.name = 'physical write total bytes'
AND v.sid = s.sid
AND v.inst_id=s.inst_id
AND s.program like 'rman@%'
GROUP BY 'DUPLICATE/RESTORE THROUGHPUT',n.name;
SQL> SELECT MEMBER FROM V$LOG G, V$LOGFILE F WHERE G.GROUP# =
F.GROUP#
2 AND G.STATUS = 'CURRENT';

MEMBER
--------------------------------------------------------------------------------
/OraRedo/RedoLogFiles/siamst_log01.dbf

run { a backup control file, start the cancel based recovery. The system may suggest a
Using
allocate channel
non-existing c1 type
archive log --'SBT'
ignore it and specify the log file name {with full path} that you
parms'ENV=(TDPO_OPTFILE=/opt/tivoli/tsm/client/oracle/bin64/tdpo.opt)';
got in the above step
allocate channel c2DATABASE
SQL> RECOVER type 'SBT' USING BACKUP CONTROLFILE UNTIL CANCEL
parms'ENV=(TDPO_OPTFILE=/opt/tivoli/tsm/client/oracle/bin64/tdpo.opt)';
ORA-00279: change 21375038 generated at 09/21/2007 20:12:47 needed for thread 1
backup archivelog
ORA-00289: all skip: /export/pspp/oracle/dbs/arch1_4_633901491.dbf
suggestion inaccessible delete input;
release channel
ORA-00280: c1; 21375038 for thread 1 is in sequence #4
change
release channel c2;
}Specify log: {=suggested | filename | AUTO | CANCEL}
/OraRedo/RedoLogFiles/siamst_log01.dbf
Log applied.
Media recovery complete.

Finally open the database in RESETLOGS mode. It is recommended to reset the online
logs after incomplete recovery or recovery with a backup control file
SQL> ALTER DATABASE OPEN RESETLOGS;
Database altered.

SELECT lpad(' ',2*(level-1))


|| TO_CHAR(DBINC_KEY) AS DBINC_KEY,
db_key,
db_name,
TO_CHAR(reset_time,'YYYY-MM-DD HH24:MI:SS'),
dbinc_status
FROM rman.dbinc
START WITH PARENT_DBINC_KEY IS NULL
CONNECT BY prior DBINC_KEY = PARENT_DBINC_KEY ;

SELECT
ROUND((A.SPACE_LIMIT / 1024 / 1024 / 1024), 2) AS FLASH_IN_GB,
ROUND((A.SPACE_USED / 1024 / 1024 / 1024), 2) AS FLASH_USED_IN_GB,
ROUND((A.SPACE_RECLAIMABLE / 1024 / 1024 / 1024), 2) AS
FLASH_RECLAIMABLE_GB,
SUM(B.PERCENT_SPACE_USED) AS PERCENT_OF_SPACE_USED
FROM
V$RECOVERY_FILE_DEST A,
V$FLASH_RECOVERY_AREA_USAGE B
GROUP BY
SPACE_LIMIT,
SPACE_USED ,
SPACE_RECLAIMABLE ;

rman rcvcat rman/rman@catalog target user/passwd@target debug trace trace_file_name

run
{
set archivelog destination to '/ora_backup/rman/arch/';
restore archivelog from logseq=8619 until logseq=8632 thread=2;
}
run{
CONFIGURE ARCHIVELOG DELETION POLICY TO NONE;
crosscheck archivelog all;
crosscheck backup;
delete noprompt expired backup;
delete noprompt expired archivelog all;
delete noprompt obsolete;
delete noprompt archivelog all completed before 'sysdate - 1/24';
}

RMAN> crosscheck backup;


RMAN> BACKUP DEVICE TYPE sbt BACKUPSET ALL DELETE INPUT;
cle10g_rman12.HTM

mdupdb006.htm
select sl.sid, sl.opname,
to_char(100*(sofar/totalwork), '990.9')||'%'
pct_done,
sysdate+(TIME_REMAINING/60/60/24)
done_by
from v$session_longops sl, v$session s
where sl.sid = s.sid
and sl.serial# = s.serial#
and sl.sid in (select sid from v$session where
module like 'backup%' or module like 'restore%' or
module like 'rman%')
setand sofar
lines 750!=pages
totalwork
9999
and totalwork heading
col start_time >0 'Started' format a30
/ end_time
col heading 'End' format a30
col time_taken_display heading 'Elapsed|Time'
format a10

select to_char(start_time, 'Dy MM-DD-YYYY


hh24:mi:ss') start_time,
to_char(end_time, 'Dy MM-DD-YYYY
hh24:mi:ss') end_time,
time_taken_display,
INPUT_BYTES_PER_SEC/1024/1024 as
INPUT_SEC_MB,
OUTPUT_BYTES_PER_SEC/1024/1024 as
OUTPUT_SEC_MB,
status
from
V$RMAN_BACKUP_job_details where
INPUT_TYPE like 'DB%INCR%';
sum(case when d.backup_type = 'L'
then d.pieces else 0 end) L
from
V$BACKUP_SET_DETAILS d
join V$BACKUP_SET s on
s.set_stamp = d.set_stamp and s.set_count =
d.set_count
where s.input_file_scan_only = 'NO'
group<--by d.session_recid,
Very good query
d.session_stamp) x
on x.session_recid = j.session_recid and
x.session_stamp = j.session_stamp
left outer join (select o.session_recid,
o.session_stamp, min(inst_id) inst_id
from GV$RMAN_OUTPUT o
group by o.session_recid,
o.session_stamp)
ro on ro.session_recid = j.session_recid and
ro.session_stamp = j.session_stamp
where j.start_time > trunc(next_day(sysdate-
30,'SUNDAY'))
order by start_time DESC
)r
;

First execute the above query & get RECID &


STAMP ID

select object_type,mbytes_processed, start_time,


end_time,status
from v$rman_status
where session_recid = (select max(session_recid)
from v$rman_status)
and operation !='RMAN'
order by recid;
may work

http://www.pythian.com/blog/oracle-free-block-corruption-test-case/

https://gruffdba.wordpress.com/2012/11/28/oracle-database-corruption-identify-and-correct/
https://alexzeng.wordpress.com/2008/09/17/how-to-recover-or-delete-corrupted-blocks/
http://www.adp-gmbh.ch/ora/admin/scripts/rman_backup_history.html Just test once before running
SELECT DISTINCT dbi.db_name,
v104.ts,
FROM bp.tag
v112.dbinc dbi,
bdf.completion_time,
v104.df,
FROM v92.dbinc
v112.bdf, dbi,
df.file#,
v104.bp,
v92.bdf
v112.ts, bdf,
fname,
SELECT DISTINCT
v104.node, dbi.db_name,
v92.dfatt
v112.df, df,
bp.tag
bdf.completion_time,
v104.site_dfatt
v92.bp
v112.bp,
FROM bp
v102.dbinc dbi, = ts.dbinc_key
WHERE df.file#,
dbi.dbinc_key
WHERE dbi.dbinc_key
v112.node,
v102.bdf bdf, = df.dbinc_key
AND fname,
ts.dbinc_key = =df.dbinc_key
AND bdf.dbinc_key
v112.site_dfatt
v102.dfatt df.dbinc_key
AND tag df,
AND ts.ts#
WHERE
v102.bp
= df.ts#
bdf.file#
bp = dbi,
df.file#= ts.dbinc_key
dbi.dbinc_key
FROM
AND v121.dbinc
ts.create_scn
AND
WHERE (bdf.incr_level
ts.dbinc_key
dbi.dbinc_key
v121.bdf, ===df.dbinc_key
df.ts_create_scn
0= OR bdf.incr_level IS
df.dbinc_key
NULL)AND
AND dbi.dbinc_key
ts.ts# = df.ts#
bdf.dbinc_key
= df.dbinc_key
= df.dbinc_key
v121.ts,
AND bdf.dbinc_key
AND bdf.bs_key
ts.create_scn
bdf.file#
v121.df, == df.ts_create_scn
= df.file#
df.dbinc_key
= bp.bs_key;
AND
AND node.db_key = dbi.db_key
dbi.dbinc_key = df.dbinc_key
AND (bdf.incr_level
v121.bp,
bdf.file# = df.file# 0 OR bdf.incr_level IS
NULL)AND bdf.dbinc_key
v121.node,
AND (bdf.incr_level
= df.dbinc_key
AND node.db_key ==dbi.db_key
0 OR bdf.incr_level IS
NULL)AND
AND
bdf.bs_key
v121.site_dfatt
bdf.file# =
= bp.bs_key;
df.file#
WHERE
AND dbi.dbinc_key
node.site_key = ts.dbinc_key
= site_dfatt.site_key
AND
AND (bdf.incr_level
ts.dbinc_key = =df.dbinc_key
0 OR bdf.incr_level IS
df.df_key =
NULL)AND ts.ts# = df.ts# site_dfatt.df_key
AND bdf.bs_key = bp.bs_key;
AND node.site_key
ts.create_scn == df.ts_create_scn
site_dfatt.site_key
AND df.df_key = site_dfatt.df_key
AND dbi.dbinc_key = df.dbinc_key
AND
AND bdf.bs_key
bdf.dbinc_key = bp.bs_key;
= df.dbinc_key
AND node.db_key = dbi.db_key
AND bdf.file# = df.file#
AND (bdf.incr_level = 0 OR bdf.incr_level IS
NULL)
AND node.site_key = site_dfatt.site_key
AND df.df_key = site_dfatt.df_key
AND bdf.bs_key = bp.bs_key;

Customized from the Above query

This is a GOOD Query for the TIMESTAMP


https://blogs.oracle.com/sysdba/entry/rman_backup_error_what_to_do_i

http://technopark02.blogspot.com/2007/09/oracle-fixing-ora-01113-file-x-needs.html

select * from v$flash_recovery_area_usage;

ce_file_name
col compression for 990.00 justify right head "COMPRESS|% ORIG"
col est_complete for a20 head "ESTIMATED COMPLETION"
col recid for 9999999 head "ID"

select recid
, output_device_type
, dbsize_mbytes
, input_bytes/1024/1024 input_mbytes
, output_bytes/1024/1024 output_mbytes
, (output_bytes/input_bytes*100) compression
, (mbytes_processed/dbsize_mbytes*100) complete
, to_char(start_time + (sysdate-start_time)/(mbytes_processed/dbsize_mbytes),'DD-MON-YYYY HH24:MI:SS')
est_complete
from v$rman_status rs
, (select sum(bytes)/1024/1024 dbsize_mbytes from v$datafile)
where status='RUNNING'
and output_device_type is not null
/
CF: Number of controlfile backups included in the backup setDF: Number of datafile full backups included in the backup setI0:
-block-corruption-test-case/

/28/oracle-database-corruption-identify-and-correct/
9/17/how-to-recover-or-delete-corrupted-blocks/
AND bdf.bs_key = bp.bs_key
AND df.create_scn IN
(SELECT MAX (create_scn)
FROM v92.dfatt
WHERE df.file# = file# AND DF.DBINC_KEY = dbinc_key)
AND bdf.create_scn IN
(SELECT MAX (create_scn)
FROM v92.bdf bdf2
WHERE bdf.file# = file# AND bDF.DBINC_KEY = dbinc_key);
we have to do a full backup, Any backup prior to missing archives is no longer valid.... 1:51 PM
before that we have to .... 1:51 PM
backup archivelog all skip inaccessible delete input; 1:52 PM
and 1:52 PM
change archivelog all validate.... 1:52 PM
the first will allow the backup of all the archives and skip the missing 1:52 PM
the second will allow the backups to continue normally going forward by marking the archive backups as validated even
though the are missing. 1:53 PM
The fact that we had hard errors on the disk that were not correctable is odd.

09/oracle-fixing-ora-01113-file-x-needs.html
output_size
,
r.output_bytes_per_sec_dis
play output_rate_per_sec
FROM
(select
command_id
, start_time
, end_time
, time_taken_display
, status
, input_type
, output_device_type
, input_bytes_display
, output_bytes_display
,
output_bytes_per_sec_displ
ay
from
v$rman_backup_job_details
order by start_time
DESC
)r
;
restore point check
drop restorepoint

flashback on /off
FRA Usage

Is row movement enabled for a table?

finding Dependent constraint.(or) ORA-02266:


unique/primary keys in table referenced by enabled foreign
keys

FRA size

TIME stamp to SCN

SCN to Time stamp

Findng Current SCN


v$flash_recovery_area_usage incorrect archivelog count
select name, scn, time, guarantee_flashback_database,DATABASE_INCARNATION# from v$restore_point;
drop restore point PSUCHECK;

select flashback_on from v$database;


alter database flashback off;
alter database flashback on;
select * from v$flash_recovery_area_usage;

select
table_name,row_movement from dba_tables
where
owner='ODB'
and
table_name = 'AC_ACTUAL_FLIGHTS';

SELECT CONSTRAINT_NAME, OWNER,TABLE_NAME FROM DBA_CONSTRAINTS


WHERE R_CONSTRAINT_NAME IN
( SELECT CONSTRAINT_NAME
FROM dba_constraints
WHERE
OWNER=UPPER('&user_dependent_from') AND
TABLE_NAME=UPPER('&object_dependent_from') )
AND STATUS='ENABLED';

set lines 100


col name format a60
select name
, floor(space_limit / 1024 / 1024) "Size MB"
, ceil(space_used / 1024 / 1024) "Used MB"
from v$recovery_file_dest
order by name
/

select timestamp_to_scn(to_timestamp('25/07/2012 16:32:30','DD/MM/YYYY HH24:MI:SS')) as scn from dual;

select scn_to_timestamp(176195435) as timestamp from dual;

select current_scn from v$database ;


RUN {
change archivelog all crosscheck;
report obsolete orphan;
report obsolete;
crosscheck backup;
crosscheck copy;
crosscheck backup of controlfile;

delete noprompt expired backup;


delete noprompt expired archivelog all;
delete noprompt expired backup of controlfile;
delete force noprompt expired copy;
delete force noprompt obsolete orphan;
delete force noprompt obsolete;
}
EXAMPLE:
----------

Enter value for user_dependent_from: FRODO


Enter value for object_dependent_from: CITY

CONSTRAINT_NAME OWNER TABLE_NAME


ZZZ FRODO COUNTRY

alter table scott.country disable constraint ZZZ;


-- z.sql_text,
p.MESSAGE,
p.totalwork,
p.sofar,
ROUND ( (p.sofar / p.totalwork) * 100,
2) done,
p.time_remaining
FROM dba_datapump_jobs b
LEFT JOIN dba_datapump_sessions
x ON (x.job_name = b.job_name)
LEFT JOIN v$session y ON (y.saddr
= x.saddr)
LEFT JOIN v$sql z ON (y.sql_id =
z.sql_id)
LEFT JOIN v$session_longops p ON
(p.sql_id = y.sql_id)
WHERE y.module = 'Data Pump Worker'
EXP , How long will it take ? AND p.time_remaining > 0;

set arraysize 1000 


copy from
username/passwd@source_connect_strin
g to
username/passwd@target_connect_string
insert table_target using select * from
copy one table from one db to another table_source;

Suppose if the table exists then


COPY FROM
username1/passwd1@PROD to
username2/passwd2@SANDBOX
INSERT TABLE_C (*) USING (SELECT
* FROM TABLE_C WHERE COL_A =
4884);

Estimate Dumpfile Size expdp system/******* SCHEMAS=CMX_ORS NOLOGFILE=y ESTIMATE_ONLY

alter session set current_schema=CMFP;


select 'alter table '||a.owner||'.'||
a.table_name||' disable constraint '||
a.constraint_name||';'
from all_constraints a, all_constraints b
where a.constraint_type = 'R'
and a.r_constraint_name =
b.constraint_name
and a.r_owner = b.owner
ORA-02266: unique/primary keys in table ref and b.table_name = 'CMFP_HRCHY';
ORA-27054: NFS file system where the file
is created or resides is not mounted with
correct options ALTER SYSTEM SET EVENTS '10298 trace na

Export the table from previous time exp system/***** tables=schema.table_name file=exp_ix_str_store.dmp log=exp_
union all
select
dbms_metadata.get_ddl('PROFILE',
u.profile) AS ddl
from dba_users u
where u.username = :v_username
and u.profile <> 'DEFAULT'
union all
select to_clob('End profile creation script
*/') AS ddl
from dba_users u
where u.username = :v_username
and u.profile <> 'DEFAULT'
and rownum = 1
/

set linesize 80 pagesize 14 feedback on


user privs for impdp trimspool on verify on

SELECT DISTINCT dp.job_name,


dp.session_type, s.inst_id, s.SID,
s.serial#,
s.username, s.inst_id, s.event, s.sql_id,
q.sql_text,
dj.operation, dj.state
FROM gv$session s,
dba_datapump_sessions dp,
dba_datapump_jobs dj,
gv$sql q
WHERE s.saddr = dp.saddr
AND dp.job_name = dj.job_name
AND s.sql_id = q.sql_id
AND s.inst_id IN (1, 2, 3)
ORDER BY s.inst_id;

what expdp/impdp actualy executing

userid='/
expdp as sysdba'
dumpfile=WRNAME_exp_dbname_SCOT
T.dmp
nohup expdp parfile=/dbexports/EXP/dbname/schemaexpdp.par &
logfile=WRNAME_exp_w665pr_SCOTT.lo
g
schemas=SCOTT
compression=all
schema backup directory=DATA_PUMP_DIR
col username for a20
col opname for a50
col message for a100
set lines 750 pages 9999
select username,opname,target_desc,sofar,totalwork,message from
V$SESSION_LONGOPS where message not like '%RMAN%' and
username='SYS';

COPY FROM username1/passwd1@//192.168.3.17:1521/PROD_SERVICE to


username2/passwd2@//192.168.4.17:1521/SANDBOX_SERVICE
INSERT TABLE_C (*) USING (SELECT * FROM TABLE_C WHERE COL_A
= 4884);

AS=CMX_ORS NOLOGFILE=y ESTIMATE_ONLY=y DIRECTORY=tmp_pump_dir

alter system set event='10298 trace name context forever, level 32' scope=spfile;

ma.table_name file=exp_ix_str_store.dmp log=exp_ix_str_store.log query=\"where DBTIME\<to_date\(\'2014-05-27 00:01:08\'\,\'yyyy-mm-dd


Schema imp dp important

s/EXP/dbname/schemaexpdp.par &
SYS_EX
PORT_S
CHEMA_
01 will
show the
actual
SELECT b.username, a.sid, b.opname, time
b.target, required
Rowid
round(b.SOFAR*100/b.TOTALWORK,0) || Range
'%' as "%DONE", b.TIME_REMAINING, scan
shows
to_char(b.start_time,'YYYY/MM/DD the
HH24:MI:SS') start_time progress
FROM v$session_longops b, of
v$session a Currently
WHERE a.sid = b.sid ORDER BY running
6; table http://www.dbaref.com/home/oracle-11g-new-features/monitoringdatapu

scope=spfile;

e DBTIME\<to_date\(\'2014-05-27 00:01:08\'\,\'yyyy-mm-dd hh24:mi:ss\'\)\"


ew-features/monitoringdatapump
Reverse Engineering

ddl statement of all types

Last DDL Date

DDL

package ddl

Generating DDL of table

Generate DDL of DB_LINK

Sequence DDL

Tablespace DDL

Users DDL

roles granted to user


system privs granted to user
other privs granted to user
A single Objects Grants ( any type of Object )

Password DDL
Cannot reuse the password

ORA-28003: password verification for the specified


password failed
ORA-20009: Error: You cannot change password.

Profile

Roles DDL

create a role and assign all privileges to the role


Roles comparision between databases

No of users have a particular role

ALL Privileges for a SINGLE user

List of Users/Roles having privilege on TABLE


Privileges granted by you to others

System privileges to roles and users

Roles & privs for a user

when was the password was changed for a user

NON Default database users

DDL of V$ Tables
Parallel DDL option
http://www.orafaq.com/node/807

http://amit7oracledba.blogspot.com/2013/02/dbmsmetadatagetddl-package-how-to-get.html

select
set longto_char(last_ddl_time,'DD-MON-YYYY
2000 HH24:MI:SS') from dba_objects where owner='&user' and
object_name='&table_name';
select (case
when ((select count(*)
SELECT DBMS_METADATA.GET_DDL('&OBJECT_TYPE','&OBJECT_NAME','&OWNER')
from dba_users AAA FROM DUAL;
where username = 'ODB') > 0)
SELECTthenDBMS_METADATA.GET_DDL('PACKAGE_SPEC','&OBJECT_NAME','&OWNER')
dbms_metadata.get_ddl ('USER', 'ODB') AAA FROM DUAL;
else to_clob (' -- Note: User not found!')
end ) Extracted_DDL from dual
set long 1000
UNION ALL
select dbms_metadata.get_ddl('TABLE','EMP','SCHEMA')||'/' from dual;
select (case
when ((select count(*)
from dba_ts_quotas
where username = 'ODB') > 0)
then dbms_metadata.get_granted_ddl( 'TABLESPACE_QUOTA', 'ODB')
selectelse to_clobSEQUENCE
'CREATE (' -- Note: No TS Quotas found!')
'||SEQUENCE_NAME||chr(10)||
SET LONG 1000
end
' INCREMENT) from dual
BY '||INCREMENT_BY||chr(10)||
SELECT DBMS_METADATA.GET_DDL('DB_LINK',db.db_link,db.owner) from dba_db_links db;
UNION
' STARTALL WITH '||LAST_NUMBER||chr(10)||
select (case '||MIN_VALUE||chr(10)||
' MINVALUE
when
' MAXVALUE ((select count(*)
'||MAX_VALUE||chr(10)||
from dba_role_privs
decode(CYCLE_FLAG,'N',' NOCYCLE','CICLE')||chr(10)||
where grantee = 'ODB')
decode(ORDER_FLAG,'N',' > 0)
NOORDER','ORDER')||chr(10)||
then dbms_metadata.get_granted_ddl
' CACHE '||CACHE_SIZE|| ';' ('ROLE_GRANT', 'ODB')
else to_clob (' -- Note: No granted Roles
from DBA_SEQUENCES where SEQUENCE_OWNER='&OWNER_NAME';found!')
end ) from dual
UNION ALL
select (case
selectwhen
'select dbms_metadata.get_ddl(''TABLESPACE'','''||
((select count(*) tablespace_name || ''') from dual;' from
dba_tablespaces;
from dba_sys_privs
where grantee = 'ODB') > 0)
then dbms_metadata.get_granted_ddl ('SYSTEM_GRANT', 'ODB')
selectelse
dbms_metadata.get_ddl('TABLESPACE','&TABLESPACE_NAME')
to_clob (' -- Note: No System Privileges found!') from dual;
end ) from dual
UNION ALL
select (case
when ((select count(*)
from dba_tab_privs
where grantee = 'ODB') > 0)
then dbms_metadata.get_granted_ddl ('OBJECT_GRANT', 'ODB')
else to_clob (' -- Note: No Object Privileges found!')
end ) from dual
/

select dbms_metadata.get_ddl('USER', '&USER') || '/' usercreate from dual;


SELECT DBMS_METADATA.GET_GRANTED_DDL('ROLE_GRANT','&USER') || '/' FROM DUAL;
SELECT DBMS_METADATA.GET_GRANTED_DDL('SYSTEM_GRANT','&USER') || '/' FROM DUAL;
SELECT DBMS_METADATA.GET_GRANTED_DDL('OBJECT_GRANT','&USER') || '/' FROM DUAL;
select DBMS_METADATA.GET_GRANTED_DDL('TABLESPACE_QUOTA', '&USER') '/' from dual;
select 'grant ' || PRIVILEGE || ' on ' || OWNER || '.' ||TABLE_NAME || ' to ' || GRANTEE || ';' from
dba_tab_privs where table_name='&Any_type_of_object_name' ;
select 'alter user ' || NAME ||' identified by values ''' || password || ''';' from user$;
declare
userNm varchar2(100);
userpswd varchar2(100);
begin
userNm := upper('&TypeUserNameHere');
select password into userpswd from sys.user$ where name = userNm;
execute immediate ('ALTER PROFILE "FUNCTIONAL_USER" LIMIT
PASSWORD_VERIFY_FUNCTION null
PASSWORD_LIFE_TIME UNLIMITED
PASSWORD_REUSE_TIME UNLIMITED
PASSWORD_REUSE_MAX UNLIMITED');
execute immediate ('alter user '||userNm||' identified by oct152014oct');
execute immediate ('alter user '||userNm||' identified by values '''||userpswd||'''');
execute immediate ('ALTER PROFILE "FUNCTIONAL_USER" LIMIT
set long 20000 longchunksize 20000 PASSWDCOMPLEXVERIFICATION');
PASSWORD_VERIFY_FUNCTION pagesize 0 linesize 1000 feedback off verify off trimspool on
column ddl format a1000
end;
begin
/
dbms_metadata.set_transform_param (dbms_metadata.session_transform, 'SQLTERMINATOR', true);
dbms_metadata.set_transform_param
SQL> ALTER PROFILE FUNCTIONAL_USER (dbms_metadata.session_transform,
LIMIT PASSWORD_VERIFY_FUNCTION 'PRETTY', true);
NULL;
end;
Profile altered.
/SQL> alter user trial identified by test;
User altered.
variable
SQL> connv_role VARCHAR2(30);
trial/test;
ALTER PROFILE "FUNCTIONAL_USER" LIMIT PASSWORD_VERIFY_FUNCTION
exec :v_role := upper('&1');
PASSWDCOMPLEXVERIFICATION;

select dbms_metadata.get_ddl('ROLE', r.role) AS ddl


from dba_roles r
where r.role = :v_role
create
union all role L1_SUPPORT;
create role L2_SUPPORT;
select dbms_metadata.get_granted_ddl('ROLE_GRANT', rp.grantee) AS ddl
create role L3_SUPPORT;
from dba_role_privs rp
where rp.grantee = :v_role
set
andpagesize
rownum0 = 1
set
unionechoall
select ' alteroff user '||username||' profile '||PROFILE||';' from dba_users;
set trimspool on
select dbms_metadata.get_granted_ddl('SYSTEM_GRANT', sp.grantee) AS ddl
set linesize 120
from dba_sys_privs sp
set
wherefeedback off = :v_role
sp.grantee
and rownum = 1
spool
union grant.sql
all
select dbms_metadata.get_granted_ddl('OBJECT_GRANT', tp.grantee) AS ddl
select 'grant select,insert,update,delete
from dba_tab_privs tp on ' || a.owner || '."' ||
where a.table_name
tp.grantee =|| :v_role
'"' || CHR(10) ||
and ' rownum
to L2_SUPPORT;'
=1 || CHR(10) ||
/ 'grant select on ' || a.owner || '."' ||
a.table_name || '"' || CHR(10) ||
' to L1_SUPPORT;'
set linesize 80 pagesize 14 || CHR(10)
feedback||on verify on
'grant select on ' || a.owner || '."' ||
a.table_name || '"' || CHR(10) ||
' to L3_SUPPORT;'
from dba_tables a
where owner in ('SCHEMA_NAME')
order by owner, table_name;

spool off

set feedback on
WHERE PRIVILEGE = 'SELECT')
CONNECT BY PRIOR grantee = granted_role
UNION
SELECT grantee || ' Through role ' || granted_role ge, 'UPDATE' priv
FROM dba_role_privs
START WITH granted_role IN (SELECT grantee
FROM dba_tab_privs
WHERE PRIVILEGE = 'UPDATE')
DB link : devBY
CONNECT to PRIOR
prod grantee = granted_role
UNION
CREATE DATABASE
SELECT grantee || 'LINK "COMPARE"
Through CONNECTge,
role ' || granted_role TO'INSERT'
DBSNMPprivIDENTIFIED BY mypwd USING
'destonation-db-name';
FROM dba_role_privs
select *WITH
START from granted_role
DBA_TAB_PRIVS@compare
IN (SELECT grantee T1 where not exists (select 1 from dba_tab_privs T2 where
t1.TABLE_NAME=t2.TABLE_NAME
FROM dba_tab_privs and t1.PRIVILEGE=t2.PRIVILEGE and
t1.GRANTEE=t2.GRANTEE WHERE PRIVILEGE ) and t1.grantee='&ROLE_NAME';
= 'INSERT')
CONNECT BY PRIOR grantee = granted_role
UNION
SELECT grantee || ' Through role ' || granted_role ge, 'DELETE' priv
FROM dba_role_privs
START WITH granted_role IN (SELECT grantee
FROM dba_tab_privs
WHERE PRIVILEGE = 'DELETE')
select
CONNECT GRANTEE
BY PRIOR as users from=dba_role_privs
grantee granted_role where GRANTED_ROLE=UPPER('&GRANTED_ROLE');
UNION
SELECT grantee || ' Through role ' || granted_role ge, 'INDEX' priv
FROM dba_role_privs
START WITH granted_role IN (SELECT grantee
FROM dba_tab_privs
WHERE PRIVILEGE = 'INDEX')
CONNECT BY PRIOR grantee = granted_role
UNION
SELECT grantee || ' Through role ' || granted_role ge, 'ALTER' priv
FROM dba_role_privs
START WITH granted_role
select 'GRANT IN (SELECT
'||granted_role||' grantee
to '||grantee||
DECODE(ADMIN_OPTION,FROM dba_tab_privs 'Y', ' WITH ADMIN OPTION;', ';')
from dba_role_privs WHERE PRIVILEGE = 'ALTER')
CONNECT
where grantee BY PRIOR grantee = granted_role
like upper('%&&uname%')
UNION UNION
SELECT
select 'GRANT grantee || ' Through
'||privilege||' role ' || granted_role ge, 'REFERENCES' priv
to '||grantee||
FROM dba_role_privs
DECODE(ADMIN_OPTION, 'Y', ' WITH ADMIN OPTION;', ';')
START WITH granted_role IN (SELECT grantee
from dba_sys_privs
where grantee likeFROM dba_tab_privs
upper('%&&uname%')
UNION WHERE PRIVILEGE = 'REFERENCES')
CONNECT
select 'grantBY ' || PRIOR
PRIVILEGE grantee = granted_role
|| ' on ' || OWNER || '.' ||TABLE_NAME || ' to ' || GRANTEE || ';'
UNION
from dba_tab_privs
SELECT
where grantee grantee || ' Through role ' || granted_role ge, 'EXECUTE' priv
like upper('%&&uname%');
FROM dba_role_privs
START WITH granted_role IN (SELECT grantee
FROM dba_tab_privs
WHERE PRIVILEGE = 'EXECUTE')
CONNECT BY PRIOR grantee = granted_role
UNION
SELECT grantee || ' Direct' ge, PRIVILEGE priv
FROM SYS.dba_tab_privs
WHERE table_name = UPPER ('&TABLE_NAME')
ORDER BY 1, 2;
'$UNAUTHENTICATED',
'CTXSYS',
'DBSNMP',
'DMSYS',
select
'DSSYS',
lpad(' ', 2*level) || c "Privilege, Roles and Users"
'EXFSYS',
from
'MDSYS',
(
'ODM',
/* THE PRIVILEGES */
'ODM_MTR',
LISTING
select INFORMATION ABOUT PRIVILEGES
'OLAPSYS',
-------------------------------------------------------------------------------
null p,
'ORDPLUGINS',
name c
'ORDSYS',
To see which table privileges are granted by you to other users.
from
'OSE$HTTP$ADMIN',
SELECT * FROM USER_TAB_PRIVS_MADE
system_privilege_map
'OUTLN',
To
'PERFSTAT', table privileges are granted to you by other users
see
where which
SELECTname*like
'PUBLIC', FROM USER_TAB_PRIVS_RECD;
upper('%&enter_privliege%')
To/* see
THEwhich
'REPADMIN', ROLES column
TO ROLESlevel privileges
RELATIONS are granted
*/ by you to other users.
SELECT
union
'SYS', * FROM USER_COL_PRIVS_MADE
To see which column level privileges are granted to you by other users
select
'SYSMAN',
SELECT * FROM p,
granted_role
'SYSTEM', USER_COL_PRIVS_RECD;
To see which privileges
grantee
'TRACESVR', c are granted to roles
SELECT
from
'WKPROXY', * FROM USER_ROLE_PRIVS;
dba_role_privs
'WKSYS',
/* THE ROLES TO PRIVILEGE RELATIONS */
'WMSYS',
union
'XDB',
Granted
select Roles:
'APEX_PUBLIC_USER' ,
SELECT * FROM
privilege
'APEX_030200', p, DBA_ROLE_PRIVS
WHEREgrantee
'APPQOSSYS', GRANTEE c = 'USER';
Privileges
'BI'from
, Granted Directly To User:
SELECT *
dba_sys_privs
'DIP' ,
FROM
) DBA_TAB_PRIVS
'FLOWS_XXXXXX' ,
WHERE
start
'HR', with GRANTEE
p is null = 'USER';
Privileges
connect
'IX' , by p = prior c; Role Granted to User:
Granted to
SELECT
'LBACSYS' * ,
FROM
'MDDATA' , DBA_TAB_PRIVS
WHERE GRANTEE
'MGMT_VIEW' , IN (SELECT granted_role
'OE' , FROM DBA_ROLE_PRIVS
'ORACLE_OCM' WHERE , GRANTEE = 'USER');
Granted
'ORDDATA' , System Privileges:
SELECT
'PM' , *
FROM DBA_SYS_PRIVS
'SCOTT' ,
WHERE
'SH' , GRANTEE = 'USER';
'SI_INFORMTN_SCHEMA' ,
SELECT NAME, TO_CHAR (ptime, 'DD-MON-YYYY HH24:MI:SS') AS "LAST TIME CHANGED", ctime
'SPATIAL_CSW_ADMIN_USR' ,
"CREATION TIME", ltime "LOCKED"
'SPATIAL_WFS_ADMIN_USR',
FROM USER$
'MTSSYS',
WHERE ptime IS NOT NULL
'OASPUBLIC',
ORDER BY ptime DESC;
'OLAPSYS',
'OWBSYS',
'OWBSYS_AUDIT',
'WEBSYS',
'WK_PROXY',
'WK_TEST',
'AURORA$JIS$UTILITY$',
'SECURE',
'AURORA$ORB$UNAUTHENTICATED',
'XS$NULL',
'FLOWS_FILES');

set long 10000


select
VIEW_DEFINITION
from
V$FIXED_VIEW_DEFINITION
where
view_name='GV$SQL_MONITOR';
alter session enable parallel DDL;
spool d1riskusercreate.sql
set pagesize 0
set escape on
select 'create user ' || U.username || ' identified ' ||
DECODE(password,
NULL, 'EXTERNALLY',
' by values ' || '''' || password || ''''
)
|| chr(10) ||
http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:494205100346718343
'default tablespace ' || default_tablespace || chr(10) ||
'temporary tablespace ' || temporary_Tablespace || chr(10) ||
' profile ' || profile || chr(10) ||
'quota ' ||
decode ( Q.max_bytes, -1, 'UNLIMITED', NULL, 'UNLIMITED',
The general syntax
Q.max_bytes) || of GET_DDL is
GET_DDL(object_type,
' on ' || default_tablespace name,
|| schema, version, model, transform).
decode (account_status,'LOCKED', ' account lock',
AA FROM DUAL; 'EXPIRED', ' password expire',
'EXPIRED and LOCKED', ' account lock password
expire',
AA FROM DUAL;
null)
set lines 1000 long 2000 pages 9999
||
select dbms_metadata.get_ddl('TABLE', table_name) from
';'
SELECT
user_tables 'create
where '||DECODE(U.NAME,'PUBLIC','public
table_name in ')||'database
from dba_users U, dba_ts_quotas Q
link '||CHR(10)
-- Comment this clause out to include system and default users
||DECODE(U.NAME,'PUBLIC',Null, U.NAME||'.')|| L.NAME||chr(10)
where U.username not in ('SYS','SYSTEM',
||'connect to ' || L.USERID || ' identified by '
'SCOTT','DBSNMP','OUTLN','WKPROXY','WMSYS','ORDSYS','O
||L.PASSWORD||' using ''' || L.host || ''''
RDPLUGINS','MDSYS',
||chr(10)||';' TEXT
'CTXSYS','XDB','ANONYMOUS','OWNER','WKSYS','ODM_MTR','
FROM sys.link$ L, sys.user$ U
ODM','OLAPSYS',
WHERE L.OWNER# = U.USER#;
select 'create tablespace ' || df.tablespace_name || chr(10)
'PERFSTAT')
and|| ' datafile ''' || df.file_name || ''' size
U.username=Q.username(+) and' || df.bytes
|| decode(autoextensible,'N',null, chr(10) || ' autoextend on
U.default_tablespace=Q.tablespace_name(+)
;maxsize '
|| maxbytes)
SELECT 'ALTER USER '||username||' QUOTA '||
|| chr(10)
DECODE(MAX_BYTES, -1, 'UNLIMITED',
|| 'default storage ( initial ' || initial_extent
TO_CHAR(ROUND(MAX_BYTES/1024))||'K')
|| decode
||' ON (next_extent, null, null, lne
'||tablespace_name||';' ' next ' || next_extent )
||FROM
' minextents ' || min_extents
DBA_TS_QUOTAS
||ORDER
' maxextents ' ||
BY USERNAME;
decode(max_extents,'2147483645','unlimited',max_extents)
select 'GRANT '||granted_role||' to '||grantee||
|| ') ;'DECODE(ADMIN_OPTION, 'Y', ' WITH ADMIN OPTION;', ';')
from
fromdba_data_files
dba_role_privsdf, dba_tablespaces t
df.tablespace_name=t.tablespace_name
where grantee like upper('%&&uname%')
/ UNION
select 'GRANT '||privilege||' to '||grantee||
DECODE(ADMIN_OPTION, 'Y', ' WITH ADMIN OPTION;', ';')
from dba_sys_privs
where grantee like upper('%&&uname%')
UNION
select 'grant ' || PRIVILEGE || ' on ' || OWNER || '.' ||
TABLE_NAME || ' to ' || GRANTEE || ';'
from dba_tab_privs
where grantee like upper('%&&uname%');
set pagesize 100
set escape off
spool off
set long 100000
set longchunksize 200
set heading off
set feedback off
set echo off
set verify off
undefine role

select (case
when ((select count(*)
from dba_roles
where role = '&&role') > 0)
then dbms_metadata.get_ddl ('ROLE', '&&role')
else to_clob ('Role does not exist')
end ) Extracted_DDL from dual
UNION ALL
select (case
when ((select count(*)
from dba_role_privs
where grantee = '&&role') > 0)
then dbms_metadata.get_granted_ddl ('ROLE_GRANT', '&&role')
end ) from dual
UNION ALL
select (case
when ((select count(*)
from
selectdba_role_privs
'grant ' || GRANTED_ROLE || ' to ' || ROLE || ';' from
where grantee =where
role_role_privs '&&role') > 0)
role='&ROLE'
then
union dbms_metadata.get_granted_ddl ('DEFAULT_ROLE',
'&&role')
select 'grant ' || PRIVILEGE || ' to ' || ROLE || ';' from role_sys_privs
end
where) from dual
role='&&ROLE'
UNION
union ALL
select
select (case
'grant ' || PRIVILEGE || ' on ' || OWNER || '.' ||
when ((select count(*)
TABLE_NAME || ' to ' || GRANTEE || ';' from dba_tab_privs where
from dba_sys_privs ;
GRANTEE='&&ROLE'
where grantee = '&&role') > 0)
then dbms_metadata.get_granted_ddl ('SYSTEM_GRANT',
'&&role')
end ) from dual
UNION ALL
select (case
when ((select count(*)
from dba_tab_privs
where grantee = '&&role') > 0)
then dbms_metadata.get_granted_ddl ('OBJECT_GRANT',
'&&role')
end ) from dual;
select
select
case *when
from level
DBA_TAB_PRIVS
= 1 then own ||where grantee
'.' || obj || ' (' || like
typ || ')' else
upper('%&enter_username%');
lpad (' ', 2*(level-1)) || obj || nvl2 (typ, ' (' || typ || ')', null)
select
end * from DBA_ROLE_PRIVS where grantee like
upper('%&enter_username%');
from
select
( * from DBA_SYS_PRIVS where grantee like
upper('%&enter_username%');
/* THE OBJECTS */
select * from DBA_COL_PRIVS where grantee like
select
upper('%&enter_username%');
null p1,
null p2,
object_name obj,
owner own,
object_type typ
from
dba_objects
where
owner like upper('%&enter_username%')
/* THE OBJECT TO PRIVILEGE RELATIONS */
union
select
table_name p1,
owner p2,
grantee,
grantee,
privilege
from
dba_tab_privs
/* THE ROLES TO ROLES/USERS RELATIONS */
union
select
granted_role p1,
granted_role p2,
grantee,
grantee,
null
from
dba_role_privs
)
start with p1 is null and p2 is null
connect by p1 = prior obj and p2 = prior own;
granted role permissions
select * from ROLE_ROLE_PRIVS where ROLE IN (select
granted_role from USER_ROLE_PRIVS where USERNAME
USER);
select * from ROLE_TAB_PRIVS where ROLE IN (select
granted_role from USER_ROLE_PRIVS where
USERNAME=USER);
select * from ROLE_SYS_PRIVS where ROLE IN (select
granted_role from USER_ROLE_PRIVS where
USERNAME=USER);
select
select dbms_metadata.get_ddl('USER', u.username) AS ddl dbms_me
from dba_users u tadata.get
where u.username = :v_username _ddl('USE
union all R',
select dbms_metadata.get_granted_ddl('TABLESPACE_QUOTA', 'KPHU00
tq.username) AS ddl 0') || '/'
from dba_ts_quotas tq usercreat
where tq.username = :v_username
1_QUESTION_ID:494205100346718343 e from
and rownum = 1 dual;
union all SELECT
select dbms_metadata.get_granted_ddl('ROLE_GRANT', DBMS_M
rp.grantee) AS ddl ETADAT
from dba_role_privs rp A.GET_G
where rp.grantee = :v_username RANTED
and rownum = 1 _DDL('R
union all OLE_GR
select dbms_metadata.get_granted_ddl('SYSTEM_GRANT', ANT','KP
sp.grantee) AS ddl HU000') ||
from dba_sys_privs sp '/' FROM
where sp.grantee = :v_username DUAL;
and rownum = 1 SELECT
union all DBMS_M
select dbms_metadata.get_granted_ddl('OBJECT_GRANT', ETADAT
tp.grantee) AS ddl A.GET_G
from dba_tab_privs tp RANTED
where tp.grantee = :v_username _DDL('SY
and rownum = 1 STEM_G
union all RANT','K
select dbms_metadata.get_granted_ddl('DEFAULT_ROLE', PHU000')
rp.grantee) AS ddl || '/'
from dba_role_privs rp FROM
where rp.grantee = :v_username DUAL;
and rp.default_role = 'YES' SELECT
and rownum = 1 DBMS_M
union all ETADAT
select to_clob('/* Start profile creation script in case they are A.GET_G
missing') AS ddl RANTED
from dba_users u _DDL('O
where u.username = :v_username BJECT_
and u.profile <> 'DEFAULT' GRANT','
and rownum = 1 KPHU000
union all ') || '/'
select dbms_metadata.get_ddl('PROFILE', u.profile) AS ddl FROM
from dba_users u DUAL;
where u.username = :v_username select
and u.profile <> 'DEFAULT' DBMS_M
union all ETADAT
select to_clob('End profile creation script */') AS ddl A.GET_G
from dba_users u RANTED
where u.username = :v_username _DDL('TA
and u.profile <> 'DEFAULT' BLESPA
and rownum = 1 CE_QUO
/ TA',
'KPHU00
set linesize 80 pagesize 14 feedback on trimspool on verify on 0') '/' from
dual;
try this

Find locked Object

To find who is accessing the particular Table

To find Blocking GOOD query

Check who is blocking who in RAC, including objects

what sql_id ,sql_text are waiting due to blocking session


blocking session history

Reference Object
To Find Lock & Session - Metalink

Locked statistics Table


who is using my dblink
, 1, 'Blocking'
, 2, 'Global') status
, decode(v.locked_mode
, 0, 'None'
,
select 1,sn.USERNAME,
'Null'
,m.SID, 2, 'Row-S (SS)'
,sn.SERIAL#,
3, 'Row-X (SX)'
,m.TYPE, 4, 'Share'
,https://github.com/gwenshap/Oracle-DBA-Scripts/blob/master/locks.sql
5, 'S/Row-X (SSX)'
decode(LMODE,
, 0, 'None',
6, 'Exclusive', TO_CHAR(lmode)) mode_held
SELECT
from t1.sid SID, s.username,
1, 'Null',v$locked_object v s.osuser, s.program,
s.machine,
, 2,dba_objects o.object_name,
'Row-S (SS)', d t1.ctime
FROM
, 3,v$lock
'Row-X l (SX)',
v$ACCESS
, 4, 'Share', s A,
v$session
v$LOCK
where
5, 'S/Row-X T1,
v.object_id
(SSX)', = d.object_id
v$SESSION
and S,lock_type,
v.object_id
6, 'Exclusive') = l.id1
DBA_OBJECTS
and v.session_id
decode(REQUEST, O = s.sid
WHERE
set0, lines
order 750 pages 9999
by oracle_username
'None',
t1.TYPE='TM'
col
, 1, blocking_status
session_id;
'Null', for a100
AND
select A.SID
2, 'Row-S = S.SID
s1.inst_id,s2.inst_id,s1.username
(SS)', || '@' || s1.machine
AND T1.sid||(SX)',
||3,' ('Row-X
SID=' = s.sid|| ' ) is blocking '
s1.sid
AND T1.id1 = o.object_id
||4,s2.username
'Share', || '@' || s2.machine || ' ( SID=' || s2.sid || ' ) ' AS
AND A.OBJECT
blocking_status
5, 'S/Row-X (SSX)', LIKE 'TABLE_NAME'||'%'
ORDER
from
6, BY T1.sid,
gv$lock
'Exclusive') l1, T1.ctime; s1, gv$lock l2, gv$session s2
gv$session
lock_requested,
where s1.sid=l1.sid and s2.sid=l2.sid and s1.inst_id=l1.inst_id and
m.ID1,
s2.inst_id=l2.inst_id
SELECT
m.ID2, DECODE(request,0,'Holder: ','Waiter: ') || gv$lock.sid sess,
and l1.BLOCK=1
machine,
t.sql_id, and l2.request
do.object_name >0
as locked_object,id1, id2, lmode, request,
and l1.id1
gv$lock.type
t.SQL_TEXT = l2.id1
and l2.id2
FROM
from = l2.id2
gv$lock
v$session join
sn, gv$session on gv$lock.sid=gv$session.sid and
order
v$lockbyms1.inst_id;
gv$lock.inst_id=gv$session.inst_id
,
join gv$locked_object
v$sqltext t lo on gv$lock.SID = lo.SESSION_ID and
gv$lock.inst_id=lo.inst_id
where t.ADDRESS = sn.SQL_ADDRESS
join
and dba_objects
t.HASH_VALUE do on= lo.OBJECT_ID = do.OBJECT_ID
sn.SQL_HASH_VALUE
WHERE
and (id1, =
((sn.SID id2, gv$lock.type)
m.SID IN (
and m.REQUEST != 0)
orSELECT
(sn.SIDid1, id2, type
= m.SID and FROM gv$lock=WHERE
m.REQUEST 0 and LMODErequest>0)
!= 4 and (ID1, ID2)
ORDER BY id1, request;
in
(select s.ID1, s.ID2
from v$lock S
where REQUEST != 0
and s.ID1 = m.ID1
and s.ID2 = m.ID2)))
order by sn.USERNAME, sn.SID, t.PIECE;
select sample_time, session_state, blocking_session,
owner||'.'||object_name||':'||nvl(subobject_name,'-') obj_name,
dbms_ROWID.ROWID_create (
1,
o.data_object_id,
current_file#,
current_block#,
current_row#
) row_id
from dba_hist_active_sess_history s, dba_objects o
where user_id = 92
and sample_time between
to_date('29-SEP-12 04.55.02 PM','dd-MON-yy hh:mi:ss PM')
and
to_date('29-SEP-12 05.05.02 PM','dd-MON-yy hh:mi:ss PM')
and event = 'enq: TX - row lock contention'
and o.data_object_id = s.current_obj#
order by 1,2;

SELECT p.table_name "Parent Table", c.table_name "Child Table",


p.constraint_name "Parent Constraint", c.constraint_name "Child
Constraint" FROM user_constraints p JOIN user_constraints c
ON(p.constraint_name=c.r_constraint_name) WHERE
(p.constraint_type = 'P' OR p.constraint_type = 'U') AND
c.constraint_type = 'R' AND p.table_name = UPPER('&table_name');
prompt # Blocking Information #
prompt ########################
select b.inst_id||'/'||b.sid blocker,
-- s.module,
w.inst_id||'/'||w.sid waiter,
b.type,
b.id1,
b.id2,
b.lmode,
w.request
from gv$lock b,
( select inst_id, sid, type, id1, id2, lmode, request
from gv$lock where request > 0 ) w
-- gv$session s
where b.lmode > 0
and ( b.id1 = w.id1 and b.id2 = w.id2 and b.type = w.type )
--and ( b.sid = s.sid and b.inst_id = s.inst_id )
order by b.inst_id, b.sid
/
prompt ########################
prompt # Locking Information #
prompt ########################
select a.inst_id, a.sid, a.type, a.lmode, a.request, a.id1, a.id2, a.block
from gv$lock a
order by a.inst_id, a.sid
/
prompt ########################
prompt # Session Information #
prompt ########################
select s.inst_id, s.sid, s.serial# s#, s.username, s.process client, p.spid
server, p.pname, -- p.pname -> p.program in 10g
s.status, s.module, s.osuser
from gv$session s , gv$process p
where ( s.paddr = p.addr and s.inst_id = p.inst_id )
order by s.inst_id, s.sid --, s.audsid
/
spool off

select owner, table_name, stattype_locked from dba_tab_statistics where stattype_locked is not null and owner not in ('SYS','S
who is querying via dblink?
Courtesy of Tom Kyte, via Mark Bobak
this script can be used at both ends of the database link
to match up which session on the remote database started
the local transaction
the GTXID will match for those sessions
just run the script on both databases

Select /*+ ORDERED */


substr(s.ksusemnm,1,10)||'-'|| substr(s.ksusepid,1,10) "ORIGIN",
substr(g.K2GTITID_ORA,1,35) "GTXID",
substr(s.indx,1,4)||'.'|| substr(s.ksuseser,1,5) "LSESSION" ,
s2.username,
substr(
decode(bitand(ksuseidl,11),
1,'ACTIVE',
0, decode( bitand(ksuseflg,4096) , 0,'INACTIVE','CACHED'),
2,'SNIPED',
3,'SNIPED',
'KILLED'
),1,1
) "S",
substr(w.event,1,10) "WAITING"
from x$k2gte g, x$ktcxb t, x$ksuse s, v$session_wait w, v$session s2
where g.K2GTDXCB =t.ktcxbxba
and g.K2GTDSES=t.ktcxbses
and s.addr=g.K2GTDSES
and w.sid=s.indx
and s2.sid = w.sid;
'UL',b.session_id
'PL/SQL User ASLock',
sid,
'DX',NVL(b.oracle_username,
'Distributed Xaction', '(oracle)') AS username,
'CF',a.owner
'ControlAS object_owner,
File',
'IS',a.object_name,
'Instance State',
'FS',Decode(b.locked_mode,
'File Set', 0, 'None',
'IR', 'Instance Recovery', 1, 'Null (NULL)', SELECT DECODE(request,0,'Holder: ','Waiter: ') ||
'ST', 'Disk Space 2, 'Row-S (SS)',
Transaction', gv$lock.sid sess, machine, do.object_name as
'TS', 'Temp Segment', 3, 'Row-X (SX)', locked_object,id1, id2, lmode, request, gv$lock.type
'IV', 'Library Cache 4, Invalidation',
'Share (S)', FROM gv$lock join gv$session on
set lines
'LS', 'Log 300
Start pages
or5, 300
'S/Row-X (SSX)',
Switch', gv$lock.sid=gv$session.sid and
col blocking_sessions
'RW', 'Row Wait',6, 'Exclusive for a200 (X)', gv$lock.inst_id=gv$session.inst_id
set linesize
'SQ', 'Sequence 200 Number',
b.locked_mode) locked_mode, join gv$locked_object lo on gv$lock.SID =
SELECT
'TE', 'Instance
b.os_user_name
'Extend Table','||s1.INST_ID||' '|| s1.username || lo.SESSION_ID and gv$lock.inst_id=lo.inst_id
'@'
FROM || s1.machine
'TT', 'Temp dba_objects
Table',|| ' type)
(a,
SID=' || s1.sid || ','|| s1.serial#||' '||
lock_type, join dba_objects do on lo.OBJECT_ID =
s1.status|| ','||s1.sql_id||'
gv$locked_object
decode(LMODE, b ) do.OBJECT_ID
is 0,blocking
WHERE '|| s2.username
'None',a.object_id || '@' || s2.machine || '
= b.object_id WHERE (id1, id2, gv$lock.type) IN (
(ORDER
SID='
1, 'Null', || BY
s2.sid1, 2,|| 3,
')4 '||s2.sql_id ||' since '|| SELECT id1, id2, type FROM gv$lock WHERE
round(s2.LAST_CALL_ET/60)||'
/ 2, 'Row-S (SS)', mins' as request>0)
blocking_sessions
3, 'Row-X (SX)', ORDER BY id1, request;
FROM
4, 'Share',gv$lock l1, gv$session s1, gv$lock l2,
gv$session
5, 'S/Row-X s2(SSX)',
WHERE s1.sid=l1.sid
6, 'Exclusive', lmode) lock_held, AND SELECT
s1.inst_id=l1.inst_id
decode(REQUEST, AND l1.sid || ' is blocking ' || l2.sid blocking_sessions
0,s2.sid=l2.sid
'None', AND FROM
1,s2.inst_id=l2.inst_id
'Null', AND v$lock l1, v$lock l2
2,l1.BLOCK=1
'Row-S (SS)', AND WHERE
l2.request
3, 'Row-X (SX)', > 0 AND l1.block = 1 AND
l1.id1
4, 'Share', = l2.id1 AND l2.request > 0 AND
l2.id2
5, 'S/Row-X = l2.id2 ;
(SSX)', l1.id1 = l2.id1 AND
6, 'Exclusive', request) lock_requested, l1.id2 = l2.id2;
decode(BLOCK,
0, 'Not Blocking',
1, 'Blocking',
2, 'Global', block) status,
OWNER,
OBJECT_NAME
from v$locked_object lo,
dba_objects do,
v$lock l
where lo.OBJECT_ID = do.OBJECT_ID
AND l.SID = lo.SESSION_ID
and block=1;
col sql_id format a15
col inst_id format '9'
col sql_text format a50
col module format a10
col blocker_ses format '999999'
col blocker_ser format '999999'
SELECT distinct
a.sql_id ,
a.inst_id,
a.blocking_session blocker_ses,
a.blocking_session_serial# blocker_ser,
a.user_id,
s.sql_text,
a.module
FROM GV$ACTIVE_SESSION_HISTORY a,
gv$sql s
where a.sql_id=s.sql_id
and blocking_session is not null
and a.user_id <> 0 -- exclude SYS user
and a.sample_time > sysdate - 1
/

ORA-02266: unique/primary keys in table referenced by enabled foreign keys


tics where stattype_locked is not null and owner not in ('SYS','SYSTEM');
select
INST_ID,
sid,BLOC
KING_SE
SSION,B
LOCKIN
G_instan
ce from
gv$sessio
n where
BLOCKIN
G_SESSI
ON is not
SELECT * from null;
dba_waiters;

https://github.com/gwenshap/Oracle-DBA-Scripts/blob/master/locks.sqlhttp://www.oracle-ckpt.com/scripts-for-locks-and-blocki
Finding own sid & serial number

Start session trace

Tracing other user's sessions 10g

tracing in 11g (use this)

Trace a module:

Trace a specific sql_id


Trace using Trigger

Other important traces

Tracing an entire database


Tkprof

DB HUNG - OS level

Database HUNG - db level


to see wait events and bind variables for a different session

10046 Trace

10046 Tracing existing process

For any sql_id that is in the shared pool (since 11gR2)

Login to db when hung

Tracing RMAN

Tracing Oracle process OS level


Tracing SQLPLUS at OS level
Tracing your own process using sqlplus

Oradebug utility

adrci

adrci create package

Diag collection
10132 Trace

Check this

parallel session trace


http://tinky2jed.wordpress.com/technical-stuff/oracle-stuff/what-is-the-correct-way-to-trace-a-session-in-oracle/
http://alexzeng.wordpress.com/2008/08/01/how-to-trace-oracle-sessions/
http://www.oracle-developer.net/display.php?id=516
https://mahmoudhatem.wordpress.com/2015/07/23/trcextprof-sql-the-raw-trace-file-10046-profiler-based-on-external-tables-re
select username,inst_id, sid, serial# FROM gV$SESSION WHERE audsid =
userenv('sessionid');

ALTER SESSION SET sql_trace = true;


ALTER SESSION SET sql_trace = false;

execute dbms_system.set_sql_trace_in_session(501, 44396, true);

execute dbms_system.set_sql_trace_in_session(501, 44396, false);


Look for trace file in USER_DUMP_DEST:

SQL> exec
dbms_monitor.session_trace_enable(session_id=>3,serial_num=>5027,binds=>tr
ue,waits=>true);
PL/SQL procedure successfully completed.
SQL> exec
dbms_monitor.session_trace_disable(session_id=>3,serial_num=>5027);
PL/SQL procedure successfully completed.

EXECUTE DBMS_MONITOR.SERV_MOD_ACT_TRACE_ENABLE(
service_name=>'vasont.world', module_name=>'VasontU.exe',
action_name=>DBMS_MONITOR.ALL_ACTIONS,waits=>TRUE,
binds=>TRUE,instance_name=>NULL);
EXECUTE DBMS_MONITOR.SERV_MOD_ACT_TRACE_DISABLE(
service_name=>'vasont.world',module_name=>'VasontU.exe');
alter system set events 'sql_trace[SQL:8kybysnu4nn34]
plan_stat=all_executions,wait=true,bind=true';

alter system set events 'sql_trace[SQL:8kybysnu4nn34] off';


create or replace trigger sqltrace
after logon on database
begin
$ sqlplus /nolog
if user='XXXXX'
then
### SQL> set _prelim on
execute immediate 'alter session set events ''10046 trace name context
forever,
SQL> level 4''';
connect / as sysdba
end if;
end;
SQL> oradebug setorapname reco
/
SQL> oradebug -g all hanganalyze 3
10132

SQL> oradebug -g all dump systemstate 266


ALTER SYSTEM SET sql_trace = true SCOPE=MEMORY;
ALTER SYSTEMsetorapname
SQL> oradebug SET sql_trace = false SCOPE=MEMORY;
diag

SQL> oradebug tracefile_name


$ tkprof orcl102_ora_3064.trc output.prf EXPLAIN=scott/tiger SYS=NO
Otherwise
tkprof if it is a single instance
ora10g_ora_5868.trc database,
tracea.prf run:
sort=fchcpu,prscpu,execpu

$ ps -ef| egrep '4711|4713'


$
$ sqlplus /nolog
truss -aefo /tmp/truss.out -p <PID>
strace -f -o output.txt sqlplus / as sysdba
SQL> set _prelim on

SQL> connect / as sysdba

SQL> oradebug setorapname diag

SQL> oradebug dump hanganalyze 3

SQL> oradebug dump systemstate 266

SQL> oradebug tracefile_name


exec sys.dbms_system.set_ev([SID], [SERIAL], 10046, 12, '');
exec dbms_system.set_ev(si=>123, se=>1234, ev=>10046, le=>8, nm=>' ');

SQL> SELECT p.spid, s.sid, s.serial#


FROM v$session s, v$process p
WHERE s.paddr = p.addr AND p.spid = 24078
SPID SID SERIAL#
------------ ---------- ----------
24078 18 5
SQL> begin dbms_system.set_ev(18,5, 10046,12,''); end; -- trace on
-- collect trace information for approximately 15 minutes during the problem
SQL> begin dbms_system.set_ev(18, 5, 10046,0,''); end; -- trace off

Find SID of that session


Find its OS pid from the following (This does not work for Windows)
select p.PID,p.SPID,s.SID from v$process p,v$session s where s.paddr = p.addr
and s.sid = &SESSION_ID;
oradebug setospid spid??? (spid from above query)
oradebug unlimit
oradebug event 10046 trace name context forever,level 12;
execute DBMS_SQLDIAG.DUMP_TRACE(p_sql_id=>'&sid',
p_child_number=>0,
p_component=>'Optimizer',
p_file_id=>'TRACE_10053');

sqlplus -prelim / as sysdba

SQL*Plus: Release 10.2.0.2.0 - Production on Mon Dec 11 17:28:14 2006

SQL> oradebug setmypid


Statement processed.
SQL> oradebug unlimit
Statement processed.
SQL> oradebug dump systemstate 266

Metalink Note : 452358.1

rman rcvcat rman/rman@catalog target user/passwd@target debug trace trace_file_name

strace -fF -v -p 16311 -o output.txt


strace /oracle/product/10.2.0.1/bin/sqlplus -V 2>&1 |less
2 from v$session s,v$process p
3* where s.paddr=p.addr
SQL> /

SID SERIAL# SPID PID USERNAME OSUSER


------- ------- -------- ---------- -------------------- --------------------
1 1 2528 2 SYSTEM
2 1 2536 3 SYSTEM
3 1 2540 4 SYSTEM
4 1 2544 5 SYSTEM
5 1 2552 6 SYSTEM
6 1 2604 7 SYSTEM
7 1 2612 8 SYSTEM
8 1 2652 9 SYSTEM
10 343 3740 12 SYS ZULIA\pete
12 70 864 13 SCOTT ZULIA\pete

10 rows selected.

Now that we have found the Operating System PID and Oracle PID (values 864
and 13 in this case) of SCOTT's session we can use this to set trace with the
oradebug tool as follows:

SQL> -- set the OS PID


SQL> oradebug
host strace setospid 864
-e trace=open -p #unix_pid & echo $! > .tmp.pid
Windows thread id: 864, image: ORACLE.EXE
SQL> -- or set the Oracle pid
SQL> oradebug setorapid 13
Windows thread id: 864, image: ORACLE.EXE
SQL> -- set the trace file size to unlimitd
SQL> oradebug unlimit
Statement processed.
SQL> -- now turn on trace for SCOTT
SQL> oradebug event 10046 trace name context forever, level 12
Statement processed.
SQL> -- run some queries in another session and then turn trace off
SQL> oradebug event 10046 trace name context off
Statement processed.

adrci> show homes


diag/tnslsnr/servername/listener
adrci> set home diag/tnslsnr/dbname/listener
adrci> purge -age 2880 -type ALERT
adrci> purge -age 2880 -type TRACE

So to purge all diagnostic information, including trace files, older than 2 days you
would issue the following.
adrci> purge -age 2880

adrci> show homes


adrci> set homepath diag/rdbms/dbname/insatncename
adrci> show incident
adrci> ips pack incident 90737 in /tmp

Oracle
Root
For 11.2 and higher, issue "$GRID_HOME/bin/diagcollection.sh" as root on all
nodes.
For 10.2 and 11.1, issue "$CRS_HOME/bin/diagcollection.pl
-crshome=$CRS_HOME --collect" as root on all nodes.

alter session set tracefile_identifier='My_trace';

alter session set events '10132 trace name context forever, level 12';

alter session set events '10132 trace name context off';

SQL> exec dbms_sqldiag.dump_trace(p_sql_id=>'<SQL_ID>',


p_child_number=>0, p_component=>'Compiler',
p_file_id=>'CBO_TRACE_DEV');
SQL> exec dbms_sqldiag.dump_trace(p_sql_id=>'<SQL_ID>',
p_child_number=>0, p_component=>'Compiler',
p_file_id=>'CBO_TRACE_PRD');

alter session set "_px_trace"=high,all;


correct-way-to-trace-a-session-in-oracle/

raw-trace-file-10046-profiler-based-on-external-tables-regexp/

select sys_context ( 'USERENV' , 'SID' ) OwnSID from dual;

You can also add an identifier to the trace file name for later identification:
ALTER SESSION SET sql_trace = true;
ALTER SESSION SET tracefile_identifier = mysqltrace;
http://www.orafaq.com/wiki/SQL_Trace

Get the SID & Serial number from Row 1

tkprof ora10g_ora_5868.trc tracea.prfs sort=fchcpu,prscpu,execpu

https://avdeo.com/tag/sql-tuning/
create or replace trigger trace_trigger_scott
AFTER LOGON ON DATABASE
WHEN (USER='SCOTT')
declare
stmt varchar2(100);
hname varchar2(20);
uname varchar2(20);
begin
select sys_context('USERENV','HOST'),
sys_context('USERENV','SESSION_USER')
into hname,uname from dual;
stmt := 'alter session set tracefile_identifier='||hname||'_'||uname;
EXECUTE IMMEDIATE stmt;
EXECUTE IMMEDIATE 'alter session set sql_trace=true';
end;
/
and disable tracing when the user disconnects:
------------------------------------------------
create or replace trigger trace_trigger_off
BEFORE LOGOFF ON DATABASE
when(user='SCOTT')
begin
execute immediate 'alter session set sql_trace=false';
end;
/

https://jonathanlewis.wordpress.com/2006/11/27/event-10132/

http://www.orafaq.com/wiki/TKProf
best

solaris
linux
connect / as sysdba
oradebug setospid 9834
oradebug unlimit
oradebug event 10046 trace name context forever,level 12
oradebug tracefile_name
--wait for 5 mins and then trace off
oradebug event 10046 trace name context off

Find SID of that session


Find its Orable pid from the following (This does work for Windows)
select p.PID,p.SPID,s.SID from v$process p,v$session s where s.paddr = p.addr and
s.sid = &SESSION_ID;
oradebug setorapid pid??? (pid from above query)
oradebug unlimit
oradebug event 10046 trace name context forever,level 12;

sqlplus '/ as sysdba'


oradebug setmypid
oradebug unlimit
oradebug hanganalyze 3
-- Wait one minute before getting the second hanganalyze
oradebug hanganalyze 3
oradebug tracefile_name
exit

ace trace_file_name

for linux
SQL> select spid from v$process p join v$session s on p.addr=s.paddr and
s.sid=sys_context('userenv','sid');
SPID
------------------------
10914

SQL> host strace -e trace=open -p #unix_pid & echo $! > .tmp.pid


Process 10914 attached - interrupt to quit

SQL> declare
p_file utl_file.file_type;
begin
p_file := utl_file.fopen ('MYDIR', 'myfile2.txt', 'w');
end;
/
2 3 4 5 6

declare
*
ERROR at line 1:
ORA-29283: invalid file operation
ORA-06512: at "SYS.UTL_FILE", line 536
ORA-29283: invalid file operation
ORA-06512: at line 4

for i in `adrci exec="show homes"|grep listener`;do


echo "adrci exec=\"set home $i;purge\""
adrci exec="set home $i;purge";
# maybe check $? here
done

$GI_HOME/bin/diagcollection.pl --collect --chmos --incidenttime 11/04/201702:00:00


--incidentduration 02:00
This will trim and collect all key diagnostics for the past 12 hours.
tfactl diagcollect

To collect for a specific date use:


tfactl diagcollect -for "yyyy-mm-dd"

tfactl diagcollect -from "yyyy-mm-dd hh:mm:ss" -to "yyyy-mm-dd hh:mm:ss"


select distinct sid OwnSID from v$mystat;
https://blog.dbi-services.com/oracle-is-hanging-dont-forget-hanganalyze-and-systemstate/
alter session set tracefile_identifier='mytrace_1089';
alter session set events '10046 trace name context forever,level
12:1089 trace name errorstack level 3';
select * from dual@DBLINK;
alter session set events '10046 trace name context off';

SQL> alter session set tracefile_identifier='trap_03150';


SQL> alter session set events '10046 trace name context
forever,level 12:3150 trace name errorstack level 3';

Systemstate

sqlplus '/ as sysdba'


oradebug setmypid
oradebug unlimit
oradebug dump systemstate 266
oradebug dump systemstate 266
oradebug tracefile_name
exit
TFA Collector - TFA with Database Support Tools Bundle (Doc ID 1513912.1)
Invalid Objects

Recomplinig Invalid objects (nonpdb) --> for pdb refer next column

Script to recompile invalid objects

Compile errors
Dropping all objects under ur schema
How to recompile a pakage?

Objects count order by owner

row count of all tables in a schema

Disable Trigger

Disable constraint
Disable constraints

Dependency Objects

dependent objects
Dblinks

Select * from dba_db_links;

Drop Private db link

Rebuild / Fragmentation
Indexes requires rebuild
Rebuild Indexes

Unused indexes

Tables requires rebuild

TABLE Fragmentation / All Tables

re-organizing table
where status<>'VALID'
and object_type='TYPE BODY'
union
select 'alter materialized view '||owner||'.'||object_name||' compile;'
from dba_objects
where status<>'VALID'
and object_type='UNDEFINED'
select owner, object_type, substr(object_name,1,30) object_name, status
union
from dba_objects
select where
'alter java class status='INVALID' order by resolve;'
'||owner||'."'||object_name||'" object_type;
from dba_objects
where status<>'VALID'
set
andserveroutput on sizeCLASS'
object_type='JAVA 100000;
declare
union
sqlstring
select varchar2(2000);
'alter synonym '||owner||'.'||object_name||' compile;'
rec_count
from integer;
dba_objects
begin
where status<>'VALID'
dbms_utility.compile_schema('SCHEMA1');
and object_type='SYNONYM'
dbms_utility.compile_schema('SCHEMA2');
and owner<>'PUBLIC'
select count(1) into rec_count from sys.all_objects
union
where'alter
select owner in ('SCHEMA1','SCHEMA2')
public synonym '||object_name||' compile;'
and object_type
from dba_objectsin ('FUNCTION','VIEW','PROCEDURE','TRIGGER') and status = 'INVALID';
if (rec_count
where > 0) then
status<>'VALID'
andfor object_type='SYNONYM'
recs in (select owner, object_type, object_name from sys.dba_objects where owner in
('SCHEMA1','SCHEMA2')
and owner='PUBLIC'; and object_type in ('FUNCTION','VIEW','PROCEDURE','TRIGGER') and status
= 'INVALID')
loop
begin
sqlstring := 'ALTER ' || recs.object_type || ' ' || recs.owner || '.' || recs.object_name || ' COMPILE';
execute immediate (sqlstring);
exception
when others then
dbms_output.put_line(recs.object_type || ' ' || recs.owner || '.' || recs.object_name || ' failed to compile :
' || sqlerrm);
end;
end loop;
end if;
end;
/

SQL> alter view OWNER.VIEW1 compile;

Warning: View altered with compilation errors.

SQL> select text from dba_errors where name='VIEW1';


ORA-28545: error diagnosed by Net8 when connecting to an agent
Unable to retrieve text of NETWORK/NCR message 65535

ORA-02063: preceding 2 lines from TUBPR01


ORA-28545: error diagnosed by Net8 when connecting to an agent
Unable to retrieve text of NETWORK/NCR message 65535
alter session set current_schema=&SCHEMA;

DECLARE
BEGIN
FOR r1 IN ( SELECT 'DROP ' || object_type || ' ' || owner || '."'|| object_name || '"' || DECODE
( object_type, 'TABLE', ' CASCADE CONSTRAINTS PURGE' ) AS v_sql FROM dba_objects
WHERE owner in ('&SCHEMA') and object_type IN ( 'TABLE', 'VIEW', 'PACKAGE', 'TYPE',
'PROCEDURE', 'FUNCTION', 'TRIGGER', 'SEQUENCE', 'MATERIALIZED VIEW', 'JAVA CLASS' )
ORDER BY object_type,
object_name ) LOOP
EXECUTE IMMEDIATE r1.v_sql;
END LOOP;
END;
/
purge dba_recyclebin;

ALTER PACKAGE pkg1 COMPILE REUSE SETTINGS;

break on owner skip1 on object_type


compute sum of cnt on owner
col owner for a30
select distinct owner,object_type, count(*) cnt
from dba_objects
group by object_type,owner order by owner;

clear break
clear computes

select
table_name,
to_number(
extractvalue(
xmltype(dbms_xmlgen.getxml(‘select count(*) c from ‘||table_name))
,’/ROWSET/ROW/C’)
)
count
from user_tables order by table_name;

select 'ALTER TRIGGER '||OWNER||'.'||TRIGGER_NAME||' DISABLE '||';' from dba_triggers where table_name in ('&TABLE_

select 'ALTER TABLE '||OWNER||'.'||TABLE_NAME||' DISABLE CONSTRAINT '||CONSTRAINT_NAME ||';' from dba_constrai
SELECT TYPE
|| ' '
|| OWNER
|| '.'
set serveroutput on
|| NAME
SELECT
DECLARE
|| ' 'ALTER
references '
l_sql CLOBTABLE := '||OWNER||'.'||
|| REFERENCED_TYPE
TABLE_NAME||' '||var_action||' CONSTRAINT '||CONSTRAINT_NAME AS sql_string,
'CREATE PROCEDURE <OWNER>.drop_db_links_prc
|| ' CONSTRAINT_NAME
'
IS
||FROM
REFERENCED_OWNER
BEGIN
|| '.'ALL_CONSTRAINTS
FOR i IN (SELECT * FROM user_db_links)
||WHERE
REFERENCED_NAME AS DEPENDENCIES
LOOP
FROM dba_dependencies
CONSTRAINT_TYPE='R'
dbms_output.put_line(''toANDdrop OWNER=Target_Schema_Name;
''||i.db_link);
WHERE referenced_name = UPPER(LTRIM(RTRIM( '&ls_REF_name' )))
EXECUTE IMMEDIATE ''DROP DATABASE LINK ''||i.db_link;
OR name = UPPER(LTRIM(RTRIM( '&ls_REF_name' )))
END LOOP;
AND (REFERENCED_OWNER <> 'SYS'
END;';
select name, type, owner
AND REFERENCED_OWNER <> 'SYSTEM'
l_sql1 clob;
from all_dependencies
AND REFERENCED_OWNER <> 'PUBLIC')
BEGIN
where referenced_owner = 'USER_NAME'
AND (OWNER <> 'SYS'
FORand ireferenced_name
in (SELECT DISTINCT owner
= 'OBJECT_NAME';
AND OWNER <> 'SYSTEM'
FROM dba_objects
AND OWNER <> 'PUBLIC' )
WHERE owner IN ('TOMASZ')
ORDER BY 1 ;
AND object_type='DATABASE LINK')
LOOP
l_sql1 := REPLACE(l_sql, '<OWNER>', i.owner);
coldbms_output.put_line(l_sql1);
owner for a30
colEXECUTE
db_link forIMMEDIATE
a50 l_sql1;
col username for a30
coll_sql1
host for:= 'BEGIN
a100 '||i.owner||'.drop_db_links_prc; END;';
Select * from dba_db_links;
EXECUTE IMMEDIATE l_sql1;

l_sql1 := 'DROP PROCEDURE '||i.owner||'.drop_db_links_prc';

EXECUTE IMMEDIATE l_sql1;


END loop;
END;
/
select a.*, round(index_leaf_estimate_if_rebuilt/current_leaf_blocks*100) percent, case when
index_leaf_estimate_if_rebuilt/current_leaf_blocks < 0.5 then 'candidate for rebuild' end status
from
(
select table_name, index_name, current_leaf_blocks, round (100 / 90 * (ind_num_rows * (rowid_length +
uniq_ind + 4) + sum((avg_col_len) * (tab_num_rows) ) ) / (8192 - 192) ) as index_leaf_estimate_if_rebuilt
from (
select tab.table_name, tab.num_rows tab_num_rows , decode(tab.partitioned,'YES',10,6) rowid_length ,
ind.index_name, ind.index_type, ind.num_rows ind_num_rows, ind.leaf_blocks as current_leaf_blocks,
decode(uniqueness,'UNIQUE',0,1) uniq_ind,ic.column_name as ind_column_name, tc.column_name ,
tc.avg_col_len
from dba_tables tab
join dba_indexes ind on ind.owner=tab.owner and ind.table_name=tab.table_name
join dba_ind_columns ic on ic.table_owner=tab.owner and ic.table_name=tab.table_name and
ic.index_owner=tab.owner and ic.index_name=ind.index_name
join dba_tab_columns tc on tc.owner=tab.owner and tc.table_name=tab.table_name and
tc.column_name=ic.column_name
where tab.owner='&OWNER' and ind.leaf_blocks is not null and ind.leaf_blocks > 1000
) group by table_name, index_name, current_leaf_blocks, ind_num_rows, uniq_ind, rowid_length
) a where index_leaf_estimate_if_rebuilt/current_leaf_blocks < 0.5
order by index_leaf_estimate_if_rebuilt/current_leaf_blocks;

SELECT ' alter index ' || owner || '.' || index_name || ' rebuild ; ' FROM dba_indexes where owner not in ('SYS','SYSTEM');

SELECT table_name, index_name


from user_indexes i
WhERE uniqueness <> 'UNIQUE'
select
AND
‘exec index_name NOT IN
analyzedb.reorg_a_table4(’||””||rtrim(t.table_owner)||””||’,'||””||
(sELECT DISTINCT object_name
rtrim(t.table_name)||””||’);’,
from v$sql_plan
t.table_owner||’.'||t.table_name name,
where operation LIKE '%INDEX%'
a.num_rows,
AND object_owner='&OWNER');
sum(t.inserts) ins,
select
select owner,table_name,round((blocks*8),2)||'
sum(t.updates) upd, kb' "TABLE SIZE",round((num_rows*avg_row_len/1024),2)||' kb' "ACTUAL DAT
table_name,round((blocks*8),2)
sum(t.deletes) del, "size (kb)" ,
round((num_rows*avg_row_len/1024),2) "actual_data
sum(t.updates)+sum(t.inserts)+sum(t.deletes) tot_chgs, (kb)",
(round((blocks*8),2) - round((num_rows*avg_row_len/1024),2)) "wasted_space (kb)"
to_char((sum(t.deletes)/(decode(a.num_rows,0,1,a.num_rows)))*100.0,’999999.99') per_del,
from
round(((sum(t.updates)+sum(t.inserts)+sum(t.deletes))/(decode(a.num_rows,0,1,a.num_rows)) *100.0),2)
dba_tables
per_chg
where owner='&OWNER' and table_name='&TABLE_NAME'
from analyzedb.table_modifications t, and
(round((blocks*8),2)
all_tables a > round((num_rows*avg_row_len/1024),2))
order by
where 4 desc; >= to_date(’&from_date’,'dd-mon-yyyy’) and
t.timestamp
t.table_owner = a.owner and t.table_owner not in (’SYS’,'SYSTEM’) and
t.table_name=a.table_name
having (sum(t.deletes)/(decode(a.num_rows,0,1,a.num_rows)))*100.0 >=5
group by t.table_owner, t.table_name, a.num_rows
order by num_rows desc, t.table_owner, t.table_name;
Set this below parameter if u want to run the compilation script in PDB

alter session set "_ORACLE_SCRIPT"=true;

Session altered.

exec dbms_pdb.exec_as_oracle_sc

set lines 750 pages 9999


col text for a150
col owner for a15
col name for a50
col position for a10
SELECT e.owner, e.name, TO_CHAR(e.line) || '/' || TO_CHAR(e.position) "POSITION",
e.text
FROM dba_errors e
ORDER BY e.owner, e.name, e.sequence;
select 'drop '||object_type||' '|| object_name|| DECODE(OBJECT_TYPE,'TABLE','
CASCADE CONSTRAINTS;',';')
from user_objects;

select 'drop java class "'||object_name||'";' from dba_objects WHERE owner in


('&SCHEMA');

here table_name in ('&TABLE_NAME1') and owner='&OWNER';

NT_NAME ||';' from dba_constraints where table_name in ('&TABLE1') and owner='&OWNER';


if ts_rec.extent_management = 'LOCAL' then
if ts_rec.allocation_type = 'SYSTEM' then
dbms_output.put_line (' AUTOALLOCATE ');
else
dbms_output.put_line (' UNIFORM SIZE '||ts_rec.initial_extent);
end if;
end if;
if ts_rec.extent_management = 'DICTIONARY' then
dbms_output.put_line ('DEFAULT STORAGE (INITIAL '||ts_rec.initial_extent
||' NEXT '||ts_rec.next_extent
||' MINEXTENTS '||ts_rec.min_extents
||' MAXEXTENTS '||ts_rec.max_extents
||' PCTINCREASE '||ts_rec.pct_increase||' ) ');
end if;
dbms_output.put_line (' ONLINE;');
dbms_output.new_line;
END LOOP;
END;
/

https://rodgersnotes.wordpress.com/2011/12/27/scripts-to-find-object-dependencies/
owner,tab
le_name,
blocks,nu
m_rows,a
vg_row_l
en,round(
((blocks*8
/1024)),2)
"TOTAL_
SIZE( MB
)",
round((nu
m_rows*a
vg_row_l
en

/1024/102
4),2)
"ACTUAL
_SIZE(M
B)",
round(((bl
ocks*8/10
24)-
(num_row
s*avg_ro
w_len/10
24/1024))
,2)
"FRAGM
ENTED_
SPACE(
Table size (with fragmentation) MB)" from

er not in ('SYS','SYSTEM');
SQL> select table_name,round((blocks*8),2)||'kb' "size" dba_table
from user_tables s where
where table_name = 'BIG1'; owner='&
owner'
TABLE_NAME size and
------------------------------ ------------------------------------------ table_na
BIG1 72952kb me='&tabl
e_name'
Actual data in table: and
round(((bl
len/1024),2)||'SQL> select table_name,round((num_rows*avg_row_len/1024),2)||'kb'
kb' "ACTUAL "size"
DATA" from dba_tables where table_name='&Table_name'; ocks*8/10
from user_tables 24)-
where table_name = 'BIG1'; (num_row
s*avg_ro
TABLE_NAME size w_len/10
------------------------------ ------------------------------------------ 24/1024))
BIG1 30604.2kb ,2) > 1
order by
Note = 72952 - 30604 = 42348 Kb is wasted space in table 8 desc;
ms_pdb.exec_as_oracle_script('alter package SYS.DBMS_METADATA compile body;');
check this
v$parameter for undo

% UNDO tablespacee Free As per expired segments

does undo have expired segments ?

User Generated UNDO

UNDO tablespace usage by USER

recreating the undo tblspce or resolving undo issue

ORA-30019: Illegal rollback Segment operation in Automatic


Undo mode
active,expired, unexpired undo

active,expired, unexpired undo by Size in MB

TEMP

sort space usage by sesison

History of Temp tablespace usage

shrink tempfile
undo advisor
http://vsbabu.org/oracle/sect07.html
select inst_id,name,value from gv$parameter where name like '%undo%';

SELECT d.tablespace_name, round(((NVL(f.bytes,0) + (a.maxbytes -


a.bytes))/1048576+ u.exp_space),2)
as max_free_mb, round(((a.bytes - (NVL(f.bytes,0)+
(1024*1024*u.exp_space)))*100/a.maxbytes),2)
used_pct FROM sys.dba_tablespaces d, (select tablespace_name, sum(bytes) bytes,
sum(greatest(maxbytes,bytes)) maxbytes from sys.dba_data_files group by
tablespace_name) a,
(select tablespace_name, sum(bytes) bytes from sys.dba_free_space group by
tablespace_name) f ,
(select tablespace_name , sum(blocks)*8/(1024) exp_space from
dba_undo_extents where status NOT IN ('ACTIVE','UNEXPIRED') group by
tablespace_name) u
WHERE d.tablespace_name = a.tablespace_name(+) AND d.tablespace_name =
f.tablespace_name(+)
AND d.tablespace_name=u.tablespace_name AND d.contents = 'UNDO' AND
u.tablespace_name = (select UPPER(value)
from v$parameter where name = 'undo_tablespace');
select status, count(1)
from dba_undo_extents
colgroup
sql_text
by format
status; a40
set lines 130
select sq.sql_text sql_text, t.USED_UREC Records, t.USED_UBLK Blocks,
(t.USED_UBLK*8192/1024) KBytes from v$transaction t,
v$session s,
v$sql sq
where t.addr
SELECT = s.taddr
TO_CHAR(s.sid)||','||TO_CHAR(s.serial#) sid_serial,
and s.sql_id = sq.sql_id 'None') orauser,
NVL(s.username,
and s.username
s.program,= '<user>'
/ r.name undoseg,
t.used_ublk * TO_NUMBER(x.value)/1024||'K' "Undo"
FROM sys.v_$rollname r,
sys.v_$session s,
sys.v_$transaction t,
sys.v_$parameter x
WHERE s.taddr = t.addr
AND r.usn = t.xidusn(+)
AND
select x.name = 'db_block_size';
a.name,b.status , d.username , d.sid , d.serial#
from v$rollname a,v$rollstat b, v$transaction c , v$session d
where a.name IN ( select segment_name
from dba_segments where tablespace_name = 'UNDOTBS1')
and a.usn = b.usn
and a.usn = c.xidusn
and c.ses_addr = d.saddr;

ALTER SYSTEM SET UNDO_SUPPRESS_ERRORS=TRUE scope=both;


round((sum_bytes / undo_size) * 100, 0) as PERC
from
(
select status, sum(bytes) sum_bytes
from dba_undo_extents
group by status
),
(
select sum(a.bytes) undo_size
from dba_tablespaces c
join v$tablespace b on b.name = c.tablespace_name
setjoin v$datafile
lines a on9999
1500 pages a.ts# = b.ts#
where sid
column c.contents = 'UNDO'
format 9999
and c.status
column username= 'ONLINE'
format a15
);
column SQL_EXEC_START for a21
column sql_text format a50
select status,TABLESPACE_NAME,sum(bytes) / 1024 / 1024 || 'MB' from
column module format a35
DBA_UNDO_EXTENTS group by status,TABLESPACE_NAME;
column sql_text format a50
break on report
compute SUM of MB_USED on report
SELECT a.inst_id,a.username, a.sid, a.serial#, a.osuser,
(b.blocks*d.block_size)/1048576 MB_USED,a.sql_id,a.sql_child_number
child,c.plan_hash_value,to_char (a.sql_exec_start, 'dd-Mon-yyyy hh24:mi:ss')
sql_exec_start,c.rows_processed,a.status,
-- c.sql_text
substr(c.sql_text,1,50) sql_text
FROM gv$session a, gv$tempseg_usage b, gv$sqlarea c
,(select block_size from dba_tablespaces where tablespace_name='TEMP') d
WHERE b.tablespace = 'TEMP'
and a.saddr = b.session_addr
AND c.address= a.sql_address
-- AND c.hash_value = a.sql_hash_value
AND a.inst_id=b.inst_id
ORDER BY 6 desc;

select
sql_id,SQL_PLAN_HASH_VALUE,max(TEMP_SPACE_ALLOCATED)/(1024*1024*10
24) gig
from DBA_HIST_ACTIVE_SESS_HISTORY
where
sample_time > sysdate-10 and
TEMP_SPACE_ALLOCATED > (10*1024*1024*1024)
group by sql_id,SQL_PLAN_HASH_VALUE order by sql_id;
ALTER TABLESPACE temp SHRINK TEMPFILE
'+DATA_KRONIA/p1kronia/tempfile/temp.313.868020865' KEEP 500M;
SELECT d.undo_size/(1024*1024) "ACTUAL UNDO SIZE [MByte]",
SUBSTR(e.value,1,25) "UNDO RETENTION [Sec]",
ROUND((d.undo_size / (to_number(f.value) *
g.undo_block_per_sec))) "OPTIMAL UNDO RETENTION [Sec]"
FROM (
SELECT SUM(a.bytes) undo_size
FROM v$datafile a,
v$tablespace b,
dba_tablespaces c
WHERE c.contents = 'UNDO'
AND c.status = 'ONLINE'
AND b.name = c.tablespace_name
AND a.ts# = b.ts#
) d,
v$parameter e,
v$parameter f,
(
SELECT MAX(undoblks/((end_time-begin_time)*3600*24))
undo_block_per_sec
FROM v$undostat
)g
WHERE e.name = 'undo_retention'
AND f.name = 'db_block_size'
/
select username,
t.used_ublk ,t.used_urec
from gv$transaction t,gv$session s
where t.addr=s.taddr and
s.sid='&sid';

https://community.oracle.com/thread/1098943?tstart=0http://www.oracleflash.com/32/Change-or-switch-undo-tablespace-in-O
refer once for CFS1

If TRUE means it will not show any undo errors , So some times job may complete sucessfully.
block_siz
e from
dba_table
spaces
where
select count(status) from dba_undo_extents where tablespac
status = 'EXPIRED'; e_name='
TEMP') d

select count(status) from dba_undo_extents where WHERE


status = 'UNEXPIRED'; b.tablesp
ace =
'TEMP'
select count(status) from dba_undo_extents where and
status = 'ACTIVE'; a.saddr =
b.session
_addr
select status, sum(bytes) / 1024 / 1024 || 'MB' from DBA_UNDO_EXTENTS group by status;
AND
col sid_serial for a20 c.address
SELECT S.sid || ',' || S.serial# sid_serial, =
S.username, S.osuser, P.spid, S.module, a.sql_add
S.program, SUM (T.blocks) * ress select
TBS.block_size / 1024 / 1024 mb_used, AND ROUND(
T.tablespace, c.hash_v SUM(tem
COUNT(*) sort_ops alue = pseg_siz
FROM v$sort_usage T, v$session S, a.sql_has e)/10485
dba_tablespaces TBS, v$process P h_value 76)
WHERE T.session_addr = S.saddr temp_mb
AND S.paddr = P.addr ORDER from
AND T.tablespace = TBS.tablespace_name BY gv$sql_w
GROUP BY S.sid, S.serial#, S.username, b.tablesp orkarea_
S.osuser, P.spid, S.module, ace, 5 active
S.program, TBS.block_size, T.tablespace desc; WHERE
ORDER BY sid_serial; sid=&sid;
SELECT
dbms_undo_adv.required_undo_size(1800,
SYSDATE-30, SYSDATE)
FROM dual;
Archivelog

archive log size

Finding Busy archive process

Archive generated per month

archive log creation time

scn to archivelog file

REDO

Redo logfile info


Redo log files
standby redelog files
Redo Generated PERDAY

How full is the current redo log file?

Dropping a redolog file error

Dropping a redolog file of other instance on RAC

Adding a New Redo Logfile Group

Adding Members to an existing group

Dropping Members from a group


Dropping Logfile Group
Renaming or Relocating Logfiles

Clearing REDO LOGFILES


') "16",
to_char(sum(decode(to_char(first_time,'HH24'),'17',1,0)),'99
') "17",
to_char(sum(decode(to_char(first_time,'HH24'),'18',1,0)),'99
') "18",
to_char(sum(decode(to_char(first_time,'HH24'),'19',1,0)),'99
') "19",
to_char(sum(decode(to_char(first_time,'HH24'),'20',1,0)),'99
')
set"20",
lines 1000 pages 9999
to_char(sum(decode(to_char(first_time,'HH24'),'21',1,0)),'99
col name for a100
') "21",thread#, sequence#, name,
select
to_char(sum(decode(to_char(first_time,'HH24'),'22',1,0)),'99
round(blocks*block_size/1024/1024) MBytes
') "22",
from v$archived_log order by thread#, sequence#;
to_char(sum(decode(to_char(first_time,'HH24'),'23',1,0)),'99
') "23"
from v$log_history
select
group by * from v$archive_processes;
to_char(first_time,'YYYY-MON-DD')
order by 1;

select sequence#, substr(name,1,96),creator,


to_char(first_time,'DD-MON HH24:MI'),
to_char(completion_time,'DD-MON HH24:MI')
from v$archived_log
where first_time > sysdate-5
order by 1

select name,thread#, sequence#, first_time, next_time,


first_change#, next_change# from v$archived_log where
9113281811148 between first_change# and next_change#;

col group# format 999


col thread# format 999
col member format a70 wrap
col status format a10
col archived format a10
col fsize format 999 heading "Size (MB)"

select l.group#, l.thread#,


f.member,
l.archived,
l.status,
(bytes/1024/1024) fsize
from
v$log l, v$logfile f
where f.group# = l.group#
order by 1,2
/
select group#,thread#,bytes/1024/1024 from v$log;
select group#,dbid,sequence#,status from v$standby_log;
select trunc(completion_time) rundate
,count(*) logswitch
,round((sum(blocks*block_size)/1024/1024)) "REDO PER
DAY (MB)"
from v$archived_log
group by trunc(completion_time)
order by 1;

SELECT le.leseq "Current log sequence No",


100*cp.cpodr_bno/le.lesiz "Percent Full",
cp.cpodr_bno "Current Block No",
le.lesiz "Size of Log in Blocks"
FROM x$kcccp cp, x$kccle le
WHERE le.leseq =CP.cpodr_seq
AND bitand(le.leflg,24) = 8
/

SQL> ALTER DATABASE DROP LOGFILE GROUP 1;


ALTER DATABASE DROP LOGFILE GROUP 1
*
ERROR at line 1:
ORA-01624: log 1 needed for crash recovery of instance
ORA920 (thread 1)
ORA-00312: online log 1 thread 1: '<file_name>'

SQL> ALTER DATABASE DROP LOGFILE GROUP 3;


ALTER DATABASE DROP LOGFILE GROUP 3
*
ERROR at line 1:
ORA-01623: log 3 is current log for instance
UNNAMED_INSTANCE_2 (thread 2) -
cannot drop
ORA-00312: online log 3 thread 2:
'+DATA_OAM/q1oam/onlinelog/group_3.277.790574217'

alter database add logfile group 3


‘/u01/oracle/ica/log3.ora’ size 10M;

alter database add logfile member


‘/u01/oracle/ica/log11.ora’ to group 1;

alter database drop logfile member


‘/u01/oracle/ica/log11.ora’;
alter database drop logfile group 3;

alter database rename file ‘/u01/oracle/ica/log1.ora’ to


‘/u02/oracle/ica/log2.ora’;

ALTER DATABASE CLEAR LOGFILE GROUP 3;


ALTER DATABASE CLEAR UNARCHIVED LOGFILE
GROUP 3;
ALTER DATABASE CLEAR UNARCHIVED LOGFILE
'/ora10gsoft/10.2.0/oradata/dosa/redo1.log';
ALTER DATABASE CLEAR UNARCHIVED LOGFILE
GROUP 1 UNRECOVERABLE DATAFILE;
Then kill that session.nothing will happen to DB

select sequence#, name,creator, to_char(first_time,'DD-MON


HH24:MI'), to_char(completion_time,'DD-MON HH24:MI')
from v$archived_log
where first_time > sysdate-1
and name is not null
order by 1

select * from v$logfile;


Easy problem to resolve. Simply perform a checkpoint on the database:

SQL> ALTER SYSTEM CHECKPOINT GLOBAL;

System altered.

SQL> ALTER DATABASE DROP LOGFILE GROUP 1;

Database altered.

select * from gv$thread; ( Check thread is PUBLIC or PRIVATE)


ALTER DATABASE DISABLE THREAD 2 ;
ALTER DATABASE DROP LOGFILE GROUP 3;
ALTER DATABASE ENABLE PUBLIC THREAD 2 ;
select * from gv$thread;
ALTER DATABASE
ADD LOGFILE GROUP 10
('c:\oracle\oradata\whs\redo\redo_05_01.log',
'd:\oracle\oradata\whs\redo\redo_05_02.log')
SIZE 100M;

ALTER DATABASE ADD LOGFILE MEMBER


/DISK2/log1b.rdo' TO GROUP 1,
'/DISK2/log2b.rdo' TO GROUP 2;
In Disaster scenarios (Redo log file deleted From os side)clear that
unarchived logfile then delete it.
select * from v$log;
Use this command to check the Redolog file status, If it is UNUSED (or)
YES,CLEARING state then, we can able to drop that logfile.

In Disaster scenarios (Redo log file deleted From os side)clear that


unarchived logfile then delete it.
select * from v$log;
Use this command to check the Redolog file status, If it is UNUSED (or)
YES,CLEARING state then, we can able to drop that logfile.
ALTER DATABASE
ADD LOGFILE MEMBER '+DATAC1'
TO GROUP 1; <-- FOR RAC
OEM repository details

Clear OEM alerts

useful link

List Hostnames

target names

standalone db's not part of rac database

Changing DBSNMP password for targets


extracting port/sid/dbname & creating tnsnames.ora file

OEM sqls

emctl commands

list targets

start blackout
All blackout commands

clearing unknown status of targets

Find CLUSTERNAME from hostname


select t.target_name
, t.target_type
, collection_timestamp
ps -ef | grep oms
, message
./emctl config oms -list_repos_details
, 'exec sysman.em_severity.delete_current_severity(''' ||
t.target_guid || ''',''' ||
metric_guid || ''',''' ||
key_value || ''')' em_severity
from sysman.mgmt_targets t
inner join
sysman.mgmt_current_severity s
on
t.target_guid = s.target_guid;

Commit ;

http://www.oracledbasupport.co.uk/querying-grid-repository-tables/
SELECT distinct(mgmt$target.host_name)
FROM mgmt$target
, mgmt$target_properties
WHERE ( mgmt$target.target_name =
mgmt$target_properties.target_name )
AND ( mgmt$target.target_type =
mgmt$target_properties.target_type )
AND ( mgmt$target_properties.property_name in
( 'CPUCount','DBVersion' ) )
GROUP BY mgmt$target.host_name
, mgmt$target_properties.property_name
, mgmt$target_properties.property_value
order by mgmt$target.host_name;

select * from sysman.mgmt$db_dbninstanceinfo

select * from sysman.mgmt$db_dbninstanceinfo


where target_type = 'oracle_database' and database_name in
(select database_name from sysman.mgmt$db_dbninstanceinfo
where target_type = 'oracle_database'
having database_name not in (select database_name from
sysman.mgmt$db_dbninstanceinfo where target_type =
'rac_database')
group by database_name)
order by database_name;

Get the target names using

for rac -->


for non rac -->

use this for both RAC & NON RAC

http://askdba.org/weblog/2011/01/retrieving-database-sidport-information-from-grid-control-repository/

http://www.oracledbasupport.co.uk/querying-grid-repository-tables/

http://satya-dba.blogspot.com/2010/01/emctl-commands.html

emctl config agent listtargets

emctl start blackout test DB1:oracle_database -d 07:00


http://dbaclass.com/article/emcli-command-oem-12c/

oracle@testhost [oemagent] cd
/u01/app/oracle/agent/agent12c/bin
./emctl stop agent
./emctl clearstate agent
./emctl start agent
./emctl upload agent

col target_name for a30


col host_name for a60
col property_value for a30
SELECT a.target_name,a.host_name ,b.property_value
FROM sysman.mgmt$target a
, sysman.mgmt$target_properties b
WHERE a.target_name = b.target_name
and a.target_type = 'rac_database'
and b.property_name in ( 'ClusterName')
and a.host_name like lower('%&HOST_NAME%') order by
a.host_name;
select database_name from
select target_name from
sysman.mgmt$db_dbninstanceinfo
sysman.mgmt$db_dbninstanceinfo
having database_name not in (select where target_type =
database_name from
'rac_database';
sysman.mgmt$db_dbninstanceinfo where target_type =
'rac_database')
group by database_name
select
minus target_name from
sysman.mgmt$db_dbninstanceinfo
select database_name from
where target_type = 'oracle_database'
sysman.mgmt$db_dbninstanceinfo and
where
database_name in
lower(database_name) = lower(instance_name)
(select
; database_name from 2nd query will not return properly. May be one or 2 difference will
sysman.mgmt$db_dbninstanceinfo
where target_type = 'oracle_database'
having database_name not in (select database_name from
emcli argfile Chng_DB_mon_passwd1
sysman.mgmt$db_dbninstanceinfo where target_type =
'rac_database')
group by database_name)
order by database_name;

update_password -target_type=rac_database -target_name=d1dbname -credential_type=DBCreds -key_column=DBUserNam


update_password -target_type=oracle_database
-target_name=db_name -credential_type=DBCreds
-key_column=DBUserName:dbsnmp
-non_key_column=DBPassword:p@ssw0rdold:m
0nit0r

emcli set_monitoring_credential
-target_type=rac_database -target_name=db_name
-set_name="DBCredsMonitoring" -cred_type="DBCreds"
-attributes="DBUserName:dbsnmp;DBPassword:m0nit0r;D
BRole:NORMAL"
emcli sync
ly. May be one or 2 difference will be there

BCreds -key_column=DBUserName:dbsnmp -non_key_column=DBPassword:p@ssw0rdold:m0nit0r


GG running or not

agctl ___location
agctl start

agctl status

agctl relocate

gg status

Get lag report

view report

to check the detail

error
no data found

start extract

check manager details


params of extract process

others
ps -ef | grep ./mgr

locate agctl
/opt/oracle/product/emagent/gg/install/xag/bin/agctl start goldengate ggate_prod --node server2
cd /opt/oracle/product/emagent/gg/install/xag/bin
./agctl status goldengate ggate_<uat/prod/bcp>
cd /opt/oracle/product/emagent/gg/install/xag/bin/
./agctl relocate goldengate ggate_prod --node secondnode

send EWDBNAMEP1, status


GGSCI (server1) 3> send RW12345PB1, getlag

Sending GETLAG request to REPLICAT RWDBNAME1 ...


Last record lag 1,218 seconds.

view report EXT02

info REPNAME detail

check the table name , add "HANDLECOLLISIONS" & "NOHANDLECOLLISIONS" before and after the MAP
statement in parameterfile and restart the EXTRACT/REPLICAT

Once the LAG is zero , stop the replicat & remove the "HANDLECOLLISIONS" & "NOHANDLECOLLISIONS" from
parameter file. Then start the replicat

START EXTRACT <extract name>, DETAIL

view params mgr


view params EXTPROCESS

$GRID_HOME/bin/crsctl stat res -w "TYPE = xag.goldengate.type" -p


crsctl status res xag.ggate_uat.goldengate -f
agctl config goldengate ggate_uat
more debuggin in memory

SGA Dynamic allocation

Free/Used SGA

memory utilization in SGA by shared pool

Determine PGA and Process Memory in use by Process

Total PGA used ( MB )

PGA Memory used by Each Process


Total Memory used

PGA memory usage by sql id

PGA Memery used by a particular spid

PGA Memery used by a Background processes

MAX Memory used by a person or process


Memory used by each user (pga,uga)

session memory used in the PGA

I /O Process

amount of session memory used in the shared pool for all sessions
Free memory in Shared pool

Finding statement/s which use lots of shared pool memory:

Memory issue (MOSC Note:146599.1, Diagnosing and Resolving Error ORA-04031)

From when are you getting ORA-4031 ERROR- HISTORY

troubleshoot Tool
https://coskan.wordpress.com/2007/09/14/what-i-learned-about-shared-pool-management/
http://yong321.freeshell.org/computer/SharedPoolPurging.html

select component,current_size/1024/1024 || 'M' from v$sga_dynamic_components;

column TOTAL_SGA for a20


column USEED for a20
column FREE for a20
select round(sum(bytes)/1024/1024,2)||' MB' total_sga,
round(round(sum(bytes)/1024/1024,2) - round(sum(decode(name,'free
memory',bytes,0))/1024/1024,2))||' MB' used,
round(sum(decode(name,'free memory',bytes,0))/1024/1024,2)||' MB' free
from v$sgastat;
select * from ( select POOL, NAME, BYTES, BYTES/1048576 as MBytes from v$sgastat
where pool='shared pool' order by BYTES desc ) where rownum <= 25;

set lines 110


col unm format a30 hea "USERNAME (SID,SERIAL#)"
col pus format 999,990.9 hea "PROC KB|USED"
col pal format 999,990.9 hea "PROC KB|MAX ALLOC"
col pgu format 99,999,990.9 hea "PGA KB|USED"
col pga format 99,999,990.9 hea "PGA KB|ALLOC"
col pgm format 99,999,990.9 hea "PGA KB|MAX MEM"

select s.username||' ('||s.sid||','||s.serial#||')' unm, round((sum(m.used)/1024),1) pus,


round((sum(m.max_allocated)/1024),1) pal, round((sum(p.pga_used_mem)/1024),1) pgu,
round((sum(p.pga_alloc_mem)/1024),1) pga, round((sum(p.pga_max_mem)/1024),1) pgm
from v$process_memory m, v$session s, v$process p
where m.serial# = p.serial# and p.pid = m.pid and p.addr=s.paddr and
s.username is not null group by s.username, s.sid, s.serial# order by unm;

select sum(pga_used_mem)/1024/1024 pga from v$process;

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 se1.sid=114
AND ssn.paddr = bgp.paddr (+)
AND ssn.paddr = prc.addr (+);
from
(
select SQL_ID,sum(DELTA_PGA_MB) PGA_MB ,(ratio_to_report(sum(DELTA_PGA_MB))
over ())*100 percent,rank() over(order by sum(DELTA_PGA_MB) desc) rank
from
(
select
select (sga+pga)/1024/1024 as "sga_pga"
SESSION_ID,SESSION_SERIAL#,sample_id,SQL_ID,SAMPLE_TIME,IS_SQLID_CURR
from
ENT,SQL_CHILD_NUMBER,PGA_ALLOCATED,
(select sum(value) sga from
greatest(PGA_ALLOCATED v$sga),
- first_value(PGA_ALLOCATED) over (partition by
(select sum(pga_used_mem) pga
SESSION_ID,SESSION_SERIAL# from
order byv$process);
sample_time rows 1
preceding),0)/power(1024,2) "DELTA_PGA_MB"
from
v$active_session_history
where
IS_SQLID_CURRENT='Y'
and sample_time > sysdate-&seconds/86400
order by 1,2,3,4
)
group by sql_id
having sum(DELTA_PGA_MB) > 0
)
where rank < (&top+1)
order by rank
/

SELECT spid, program,


pga_max_mem max,
pga_alloc_mem alloc,
pga_used_mem used,
pga_freeable_mem free
FROM V$PROCESS
WHERE spid = 7735;

select
PID,SPID,serial#,USERNAME,PROGRAM,PGA_USED_MEM,PGA_ALLOC_MEM,PGA_F
REEABLE_MEM,PGA_MAX_MEM from v$process order by PGA_USED_MEM desc;

set linesize 750


set pagesize 250
column box format a20
column username format a7
column program format a20
column os_user format a20

select s.sid, p.pid, p.spid,substr(s.machine,1,20) box,s.logon_time logon_date,to_char


(s.logon_time, 'hh24:mi:ss') logon_time,
substr(s.username,1,7) username,
substr(s.osuser,1,20) os_user,
substr(s.program,1,35) program from v$session s, v$process p where s.paddr = p.addr
and
s.sid=(select s.sid from v$session s where paddr=(select addr from v$process where
pga_used_mem=(select max(pga_used_mem) from v$process)));
select s.osuser osuser,s.username,s.program,s.serial# serial,se.sid,n.name,
max(se.value) maxmem
from v$sesstat se,
v$statname n
,v$session s
where n.statistic# = se.statistic#
and n.name in ('session pga memory','session pga memory max',
'session uga memory','session uga memory max')
and s.sid=se.sid
group by n.name,se.sid,s.osuser,s.username,s.program,s.serial#
order by 2
;

set pages 999


column pga_size format 999,999,999
select
1048576+a.value+b.value pga_size
from
v$parameter a,
v$parameter b
where
a.name = 'sort_area_size'
and
b.name = 'hash_area_size';

COL ts FORMAT a10 HEADING "Tablespace";


COL reads FORMAT 9999900;
COL writes FORMAT 9999900;
COL br FORMAT 9999900 HEADING "BlksRead";
COL bw FORMAT 9999900 HEADING "BlksWrite";
COL rtime FORMAT 9999900;
COL wtime FORMAT 9999900;
SELECT ts.name AS ts, fs.phyrds "Reads", fs.phywrts "Writes"
, Fs.phyblkrd AS br, fs.phyblkwrt AS bw
, Fs.readtim "RTime", fs.writetim "WTime"
FROM v$tablespace ts, v$datafile df, v$filestat fs
WHERE ts.ts# = df.ts# AND df.file# = fs.file#
UNION
SELECT ts.name AS ts, ts.phyrds "Reads", ts.phywrts "Writes"
, Ts.phyblkrd AS br, ts.phyblkwrt AS bw
, Ts.readtim "RTime", ts.writetim "WTime"
FROM v$tablespace ts, v$tempfile tf, v$tempstat ts
WHERE ts.ts# = tf.ts# AND tf.file# = ts.file# ORDER BY 1;

select SUM(value)/1024/1024||' Mb' "Total session memory"


from v$sesstat, v$statname
where name = 'session uga memory'
and v$sesstat.statistic# = v$statname.statistic#;
SELECT * FROM v$sgastat
WHERE name = 'free memory';

set lines 1000 pages 9999


col stmt for a150
SELECT substr(sql_text,1,150) "Stmt", count(*),
sum(sharable_mem) "Mem",
sum(users_opening) "Open",
sum(executions) "Exec"
FROM v$sql
GROUP BY substr(sql_text,1,150)
HAVING sum(sharable_mem) > 20000
order by sum(sharable_mem);

http://www.dbas-oracle.com/2013/05/5-Easy-Step-to-Solve-ORA-04031-with-Oracle-
Support-Provided-Tool.html

For 10g:
set pages 999
set lines 130
col component for a25 head "Component"
col status format a10 head "Status"
col initial_size for 999,999,999,999 head "Initial"
col parameter for a25 heading "Parameter"
col final_size for 999,999,999,999 head "Final"
col changed head "Changed At"

select component, parameter, initial_size, final_size, status,


to_char(end_time ,'mm/dd/yyyy hh24:mi:ss') changed
from gv$sga_resize_ops
order by 6
/

Metalink ID 559339.1
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 se1.sid=&sid
AND ssn.paddr = bgp.paddr (+)
AND ssn.paddr = prc.addr (+); <--For a Single sid
https://bdrouvot.wordpress.com/2013/03/19/link-huge-pga-temp/
The output from this data dictionary query shows that every
connected Oracle session will about 2.5 megabytes of RAM
memory for the Oracle PGA

See all the data file i / o, and if too many files, can be rewritten
for the top 10 select * (order by xx desc) where rownum <= 10
http://www.dba-oracle.com/t_x$ksmlru_x$ksmsp_shared_pool_monitoring.htm

For 11g:
set pages 999
set lines 130
col component for a25 head "Component"
col status format a10 head "Status"
col initial_size for 999,999,999,999 head "Initial"
col parameter for a25 heading "Parameter"
col final_size for 999,999,999,999 head "Final"
col changed head "Changed At"

select component, parameter, initial_size, final_size, status,


to_char(end_time ,'mm/dd/yyyy hh24:mi:ss') changed
from gv$memory_resize_ops
order by 6
/
patching post activity

pdb violations

applied patch versions

patch validation
Patch check

componenets status

invalid components error messages

invalid components after all procedure


/opt/oracle/product/12.1.0.2.PSUAPR2017/OPatch
./datapatch -verbose

col CAUSE for a15


col MESSAGE for a30
select name,cause,message, STATUS from pdb_plug_in_violations;

select PATCH_ID, ACTION, ACTION_TIME, DESCRIPTION, STATUS, LOGFILE from registry$sqlpatch;

datapatch -db db_name -prereq

select
PATCH_ID,PATCH_UID,VERSION,ACTION,ACTION_TIME,STATUS,DESCRIPTION,BUNDLE_SERIES,BUNDLE
_ID,BUNDLE_DATA from dba_registry_sqlpatch;

Database PSUs
CRS PSUs
GI (Grid Infrastructure) PSUs
Enterprise Manager Agent PSUs
col COMP_ID for a25
col COMP_NAME for a60
set lines 700
select COMP_ID,COMP_NAME,VERSION,STATUS from dba_registry;

set lines 750 pages 9999


col text for a80
SELECT e.owner, e.name, TO_CHAR(e.line) || '/' || TO_CHAR(e.position) "POSITION", e.text
FROM dba_errors e
ORDER BY e.owner, e.name, e.sequence;

delete from obj$ where name in (select OBJECT_NAME from dba_objects where status ='INVALID' and owner
='XDB');
commit;
set serveroutput on
execute sys.dbms_regxdb.validatexdb;
select comp_name, version, status from dba_registry where comp_id='XDB';
<-- status should be SUCCESS
opatch lsinventory -bugs_fixed | egrep -i 'PSU|DATABASE PATCH SET UPDATE'
opatch lsinventory -bugs_fixed | grep -i 'TRACKING BUG' | grep -i 'PSU'
opatch lsinventory -bugs_fixed | grep -i 'GRID INFRASTRUCTURE PATCH SET UPDATE'
opatch lsinventory -bugs_fixed | grep -i 'ENTERPRISE MANAGER' | grep -i 'AGENT'
scheduled job run details

scheduled job logs

DBA JOBS

SCHEDULED JOBS
select
LOG_ID,LOG_DATE,OWNER,JOB_NAME,STATUS,ERROR#,REQ_START_DATE,ACTU
AL_START_DATE,RUN_DURATION,SESSION_ID,CPU_USED,ADDITIONAL_INFO from
DBA_SCHEDULER_JOB_RUN_DETAILS;

select LOG_ID,LOG_DATE,OWNER,
JOB_NAME,STATUS,USER_NAME,CLIENT_ID,GLOBAL_UID,ADDITIONAL_INFO from
DBA_SCHEDULER_JOB_LOG;

SELECT LOG_USER,SCHEMA_USER,LAST_DATE, LAST_SEC,THIS_DATE,THIS_SEC,


NEXT_DATE,
NEXT_SEC,TOTAL_TIME,BROKEN,INTERVAL,FAILURES,WHAT,INSTANCE FROM D
BA_JOBS;

SELECT OWNER,JOB_NAME,CLIENT_ID, PROGRAM_OWNER,


PROGRAM_NAME,SCHEDULE_OWNER,START_DATE
END_DATE,ENABLED,STATE,RUN_COUNT,LAST_START_DATE,LAST_RUN_DURATIO
N,
NEXT_RUN_DATE, MAX_RUN_DURATION,COMMENTS FROM
DBA_SCHEDULER_JOBS;
X$ Views

List the hidden parameters in the oracle database


undocumented init parameters:
how to find all x$views list

Hidden parameter default value


Reading Alert log
v$ views

sp file parameter difference between two rac instances


Database started time
Database current time
DNS lookup in oracle
Service Name

Database Characterset
Finding DBNAME as a normal user
How to see oracle Enterprise edition or not

Showing Current user

My current session sid & spid


generate random password
Tablespace

General database comparision


others
spool with pdb name

Creating Oracle Alert log table

ORA-00600: internal error code, arguments: [kdourp_inorder2],


[44], [0], [48], [44], [], [], []
ORA-08007: Further changes to this block by this transaction
not allowed
Doing block recovery for file 21 block 456408
SMON: Parallel transaction recovery slave got internal error
SMON: Downgrading transaction recovery to serial

Blocking or terminating Development tools

Flash Recover area full .Unable to archive…


Change the archive log ___location

Getting oracle_home from sql*plus

Database 32bit or 64bit

DBV
External table in oracle for excel sheet
Create and drop db link as another user

ORA-28547: connection to server failed, probable Oracle Net admin error


$ sqlplus
Error 6 initializing SQL*Plus
Message file sp1<lang>.msb not found
SP2-0750: You may need to set ORACLE_HOME to your Oracle software directory
Exit 1

ERROR at line 1:
ORA-01565: error in identifying file
Creating Big table
'/ora10gsoft/10.2.0/oradata/sambaar/users01.dbf'
ORA-27037: unable to obtain file status
Linux Error: 2: No such file or directory
Additional information: 3
ORA-06512: at line 16

ORA-01139: RESETLOGS option only valid after an incomplete database recovery

one redo log file deleted on os side.(redolog group contains only one member)

Oracle internal

Writinh own message in Alertlog

License Usage report

Profile for OS
dissassembling_the_data_block

Freezing the oracle database(If we want to suspend all i/o operations.)

Restrict the database logins (To put our database in a single user mode )

Quiescing Oracle Database

create snapshot

Tricks

Hiding user id's


Executing some script without logging as that user

Get your name & database name in sqlprompt

Connect to other user without password

column separator
ipv6 connectivity

Magical Faster secret query

case insensitive search

DBMS-insufficient privileges

put lines inside oracle datbase

time zone of the database

Database home options check

Check the option

Product/Component
Automated Storage Management
Oracle Data Mining
Database Vault
Oracle OLAP
Oracle Label Security
Oracle Partitioning
Real Application Cluster
Real Application Testing

Enabling & disabling the options

Product/Component
Oracle Data Mining
Database Vault
Oracle OLAP
Oracle Label Security
Oracle Partitioning
Real Application Testing
set lines 750 pages 9999
column KSPPINM format a50
column KSPPSTVL format a50
select a.ksppinm, b.ksppstvl FROM x$ksppi a, x$ksppcv b WHERE a.indx=b.indx;
SELECT * FROM SYS.X$KSPPI WHERE SUBSTR(KSPPINM,1,1) = '_';
select distinct table_name from V$INDEXED_FIXED_COLUMN where table_name like 'X$%';

select ksppstvl from x$ksppi join x$ksppcv using (indx) where ksppinm='_high_priority_processes';
select message_text from X$DBGALERTEXT where rownum <= 20;

SELECT p1.name, p1.value, p2.value FROM gv$parameter p1


JOIN gv$parameter p2 ON p1.name = p2.name
WHERE p1.inst_id = 1
AND p2.inst_id = 2
AND p1.value != p2.value
AND p1.name NOT IN ('instance_number', 'instance_name', 'local_listener');
SELECT to_char(startup_time,'DD-MON-YYYY HH24:MI:SS') "DB Startup Time" FROM sys.v_$instance;
SELECT to_char(sysdate,'DD-MON-YYYY HH24:MI:SS') "sysdate" FROM dual;
SELECT utl_inaddr.get_host_name('68.180.206.184') from dual;
select value from v$parameter where name='service_names';

SELECT value$ FROM sys.props$ WHERE name = 'NLS_CHARACTERSET' ;


select ora_database_name from dual
select * from product_component_version;

select sys_context( 'userenv', 'current_schema' ) from dual;

select
s.sid, p.spid, substr(s.username,1,20) username, s.terminal, p.Program
from
v$session s, v$process p
where
s.paddr = p.addr
and
s.sid = (select sid from v$mystat where rownum=1)
;

select DBMS_RANDOM.string('x',10) PASSWD from dual


select name from ts$;

SELECT t1.* FROM v$session t1 WHERE NOT EXISTS


(SELECT 1 FROM V$session@dblink_prod t2 WHERE t1.sid = t2.sid and t1.serial#=t2.serial# and
t1.AUTH_TYPE_ID=t2.AUTH_TYPE_ID
and t1.APP_VERSION=t2.APP_VERSION and t1.CREATE_TIME=t2.CREATE_TIME ) )
column dbname new_value dbname noprint
create directory BDUMP as '/u01/app/oracle/admin/mysid/bdump';
select name dbname from v$pdbs;
SET MARKUP HTML ON
create table
spool C:\Oracle\login-db\tkdst\&dbname..xls
alert_log ( msg varchar2(80) )
select * from all_db_links;
organization external (
spool off
type oracle_loader
SET MARKUP HTML OFF
default directory BDUMP
CREATE OR REPLACE
access parameters ( TRIGGER block_tools_from_prod
AFTER LOGON
records ON DATABASE
delimited by newline
DECLARE
)
v_program sys.v_$session.program%TYPE;
___location('alrt_mysid.log')
BEGIN
)
SELECT
reject limitprogram
1000; INTO v_program
FROM sys.v_$session
select
WHERE audsid = USERENV('SESSIONID')
segment_name,
AND audsid != 0 - Don't Check SYS Connections
status
AND ROWNUM = 1; - Parallel processes will have the same AUDSID's
from
dba_rollback_segs
IF UPPER(v_program ) LIKE '%TOAD%' OR UPPER(v_prog) LIKE '%T.O.A.D%' OR - Toad
where
UPPER(v_program ) LIKE '%SQLNAV%' OR - SQL Navigator
tablespace_name='undotbs_corrupt'
UPPER(v_program ) LIKE '%PLSQLDEV%' OR - PLSQL Developer
and
UPPER(v_program ) LIKE '%BUSOBJ%' OR - Business Objects
status = 'NEEDS RECOVERY';
UPPER(v_prog) LIKE '%EXCEL%' - MS-Excel plug-in
THEN
RAISE_APPLICATION_ERROR(-20000, 'Development tools are not allowed here.');
CREATE
END IF; OR REPLACE FUNCTION get_java_system_property (prop IN VARCHAR2) RETURN VARCHAR2 IS
LANGUAGE
END; JAVA
name
/ 'java.lang.System.getProperty(java.lang.String) return java.lang.String';
/SHOW ERRORS

SELECT object_type FROM user_objects WHERE object_name = 'GET_JAVA_SYSTEM_PROPERTY';

CREATE OR REPLACE VIEW v$oracle_home AS


SELECT get_java_system_property('user.dir') AS oracle_home FROM dual;
SQL> SELECT * FROM V$RECOVERY_FILE_DEST;
SELECT * FROM v$oracle_home;
drop function get_java_system_property;
drop view v$oracle_home;

select
length(addr)*4 || '-bits' word_length
from
v$process
where
ROWNUM =1;

dbv file=/usr/acct/dba/dbs/dbf/data1/smp_data.dbf blocksize=4096 feedback=100


CREATE OR REPLACE DIRECTORY costtoserve_dir AS '/work/oracle/costtoserve';
grant read,write on directory costtoserve_dir to costtoserve;
CREATE TABLE costtoserve.costtoserve
(
parent VARCHAR2(10),
host_to VARCHAR2(30),
child VARCHAR2(30)
)
ORGANIZATION EXTERNAL
(
TYPE oracle_loader
DEFAULT DIRECTORY costtoserve_dir
ACCESS PARAMETERS
(
RECORDS DELIMITED BY NEWLINE
badfile costtoserve_dir:'upload_costtoserv_file.bad'
logfile costtoserve_dir:'upload_costtoserv_file.log'
FIELDS TERMINATED BY ','
MISSING FIELD VALUES ARE NULL
(
parent,
host_to,
child
))
LOCATION ('hosttoserver.csv')
)REJECT LIMIT UNLIMITED;
SQL> show user
USER is "SYS"
SQL> exec scott.create_db_link

PL/SQL procedure successfully completed.

SQL> select * from dba_db_links where OWNER='SCOTT';

OWNER DB_LINK USERNAME HOST CREATED


------------------------------ -------------------- ------------------------------ -------------------- ---------
SCOTT LINK1 SCOTT testdb 04-NOV-11

SQL> drop database link scott.LINK1;


drop database link scott.LINK1
*
ERROR at line 1:
ORA-02024: database link not found

SQL> CREATE PROCEDURE scott.drop_db_link AS


BEGIN
EXECUTE IMMEDIATE 'drop database link LINK1';
END drop_db_link; 2 3 4
5/

Procedure created.

SQL> exec scott.drop_db_link

PL/SQL procedure successfully completed.

SQL> select * from dba_db_links where OWNER='SCOTT';

no rows selected

SQL>

In my case, I comment out one line starting PROGRAM from listener.ora, and after restarting listener. I can connect
successfully.

SID_LIST_KOREA =
(SID_LIST =
(SID_DESC =
(GLOBAL_DBNAME=korea)
(SID_NAME = KOREA)
(ORACLE_HOME = D:\Applications\oracle\product\10.2.0)
# (PROGRAM = extproc)
)
)
ORA-00350:
while (l_cntlog 1 of instance sambaar (thread 1) needs to be archived
< l_rows)
ORA-00312:
loop online log 1 thread 1:
and we check/*+ its opened*/file descriptors
'/ora10gsoft/10.2.0/oradata/sambaar/redo01a.log'
insert APPEND into bigtab for our file:
ls -l /proc/2661/fd |
select rownum+l_cnt,grep test_rm
lrwx------ 1OWNER,
oracle dba 64 Mar 26 14:02
OBJECT_NAME, 66 -> /var/tmp/test_rm.dbf (deleted)
SUBOBJECT_NAME,
SQL> OBJECT_ID, DATA_OBJECT_ID,
SQL> OBJECT_TYPE, CREATED, LAST_DDL_TIME,
here
SQL>it alter
is: TIMESTAMP,
system checkpoint;STATUS, TEMPORARY,
ls -l /proc/2661/fd/66
GENERATED, SECONDARY
lrwx------
System 1 oracle dba 64 Mar 26 14:02 /proc/2661/fd/66 -> /var/tmp/test_rm.dbf (deleted)
altered.
Run this from bigtab
where rownum <= l_rows-l_cnt;
l_cnt := l_cnt + sql%rowcount;
$ cd $ORACLE_HOME/install
commit;
$ ./changePerm.sh
end loop;
In
SQL>
end;some other
alter unix, lsof
database dropmay be needed
logfile group 1;to map the file descriptor with the deleted file name
alter
/ database drop logfile group 1
*
ERROR
alter table atbigtab
line 1:add constraint
first we set a log
ORA-00350: symbolic link so that
1 key(id);
of instance oracle(thread
sambaar can see1)itneeds
as it was before
to be the delete:
archived
bigtab_pk primary
ln -s /proc/2661/fd/66 /var/tmp/test_rm.dbf
ORA-00312: online log 1 thread 1:
'/ora10gsoft/10.2.0/oradata/sambaar/redo01a.log'

here
SQL>data is accessible, but that will be lost if dbwriter closes it file handle (i.e if the database is closed)
SQL> ALTER DATABASE CLEAR UNARCHIVED LOGFILE GROUP 1;

RECOVERaltered.
Database DATABASE UNTIL CANCEL
alter database open resetlogs
SQL> SQL> SQL> SQL> alter database drop logfile group 1;
.export
Template ORACLE_HOME=/opt/oracle/product/11.1.0/db7
___location
Database altered.
PATH=/usr/bin:/etc:/usr/sbin:/usr/ucb:$HOME/bin:/usr/bin/X11:/sbin:.:/usr/local/bin:${ORACLE_HOME}:$
-------------------
select
{ORACLE_HOME}/bin:${ORACLE_HOME}/OPatch:/oracle/dba/bin
c:\oracle\product\10.2.0\db_1\assistants\dbca\templates
samp.dbid,
SQL>
OEM Scripts
fu.name,
export PATH
------------
samp.version,
export HISTFILE=$HOME/.histdir/$(tty|sed 's-/-_-g')
\\networkdrive\k$\oracle\product\10.2.0\db_1\sysman\admin\emdrep\sql
detected_usages,
export
Database DBA_INIT_INI=/oracle/dba/funcs/dba_init.ini
Creation
total_samples,
-------------------
decode(to_char(last_usage_date, 'MM/DD/YYYY, HH:MI:SS'),
# NMON variable
C:\WINDOWS\system32\cmd
NULL, to stop oslevel
'FALSE', checking
/c call K:\oracle\product\10.2.0\db_1/bin/dbca.bat -progress_only -createDatabase
export NMONAIX=5.2.0.0
-templateName General_Purpose.dbc
to_char(last_sample_date, -gdbNameHH:MI:SS'),
'MM/DD/YYYY, test -sid test'TRUE',
-sysPassword 05f6050bc031e3dc104db3b733a0228c44
-systemPassword
'FALSE') 05f6050bc031e3dc104db3b733a0228c44 -sysmanPassword 05c5f468c03129e8c2b5ed24021b2f7200
export EDITOR=vi 05c5f468c03129e8c2b5ed24021b2f7200 -emConfiguration LOCAL -datafileJarLocation
-dbsnmpPassword
currently_used,
export FPATH=/oracle/dba/funcs
K:\oracle\product\10.2.0\db_1\assistants\dbca\templates
first_usage_date, -datafileDestination K:\oracle\product\10.2.0\oradata
export TNS_ADMIN=/var/opt/oracle
-responseFile
last_usage_date,NO_VALUE -characterset WE8MSWIN1252 -obfuscatedPasswords true -sampleSchema true
export ORACLE_BASE=/opt/oracle
-recoveryAreaDestination
aux_count, NO_VALUE
export ORACLE_ASK=YES
feature_info,
export ORACLE_OWNER=oracle
last_sample_date,
begin
last_sample_period,
sys.dbms_system.ksdwrt(2,
export 'My own message');
NLS_LANG=AMERICAN_AMERICA.UTF8
sample_interval,
end;
export NLS_DATE_FORMAT='YYYY/MM/DD HH24:MI'
mt.description
/
from
ninswri$_dbu_usage_sample samp,
. .kshrc
wri$_dbu_feature_usage fu,
wri$_dbu_feature_metadata mt
#where
Set up machine independent variables
stty erase '^H' =killfu.dbid
samp.dbid "^U" intr
and"^C" eof "^D"
umask 002
samp.version = fu.version and
export
fu.name JAVA_COMPILER=NONE
= mt.name and
export
fu.name HOST=$(uname -n)
not like '_DBFUS_TEST%' and /* filter out test features */
export PWD=`pwd`
bitand(mt.usg_det_method, 4) != 4 /* filter out disabled features */;
export PS1='$ORACLE_SID@$HOST: $PWD> '
if [ -s "$MAIL" ] # This is at Shell startup. In normal
then echo "$MAILMSG" # operation, the Shell checks
fi # periodically.
Sql> alter system suspend;
Sql> select database_status from v$instance;

Database_status
-----------------
Suspended
http://www.orafaq.com/papers/dissassembling_the_data_block.pdf
SQL> select active_state
Sql> alter system resume;from v$instance;

ACTIVE_ST
Sql> select database_status from v$instance;
---------
NORMAL
Database_status
-----------------
SQL>
Active ALTER SYSTEM QUIESCE RESTRICTED;
Sql>startup restrict;
System altered.
Sql>alter system disable restricted session;
Sql> alter system enable restricted session;
SQL> select active_state from v$instance;

ACTIVE_ST
---------
QUIESCED

SQL> select bq.sid, username, osuser, program, machine from v$blocking_quiesce bq, v$session s where bq.sid = s.sid;

no rows selected

SQL> ALTER SYSTEM UNQUIESCE;

System altered.

EXEC DBMS_WORKLOAD_REPOSITORY.create_snapshot;

update sys.user$ set name='NEW' where user#=N and name='OLD';


http://www.gokhanatil.com/2011/02/syssystem-users-and-ora-01031-prior-to-oracle-9-2.html

set termout off


define gname=idle
column global_name new_value gname
select lower(user)||'@' ||substr(global_name,1,decode(dot,0,length(global_name),dot-1)) global_name from (select
global_name, instr(global_name,'.') dot from global_name);
set sqlprompt '&gname>'
set termout on

(connect as SYSTEM)
SQL> alter user APEX_030200 grant connect through system;
User altered.
SQL> alter user apex_030200 account unlock;
User altered.
SQL> connect system[apex_030200]/systempassword
Connected.
SQL> select user from dual;
APEX_030200

SET COLSEP '|'


connect arup/arup@[fe80::219:21ff:febb:9aa5]/D112D1

jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)
(HOST=[fe80::219:21ff:febb:9aa5]) (PORT=1526))
(CONNECT_DATA=(SERVICE_NAME=D112D1)))

select /*+ richs_secret_hint */ ename, job

SELECT * FROM TABLE WHERE REGEXP_LIKE (TABLE.NAME,'IgNoReCaSe','i');

GRANT CREATE JOB, MANAGE SCHEDULER, MANAGE ANY QUEUE TO USER1;

set serveroutput on
set heading off
set feedback off
select sysdate from dual;
exec dbms_output.put_line('------------------------------');
select sysdate from dual;

SELECT EXTRACT(TIMEZONE_HOUR FROM SYSTIMESTAMP)||':'||


EXTRACT(TIMEZONE_MINUTE FROM SYSTIMESTAMP)
FROM dual;

http://m.blog.itpub.net/17252115/viewspace-1160554/

cd $ORACLE_HOME/rdbms/lib
ar -tv libknlopt.a | grep -c kkxwtp.o
ar -tv libknlopt.a | grep -c kfoff.o
ar -tv libknlopt.a | grep -c ktd.o
ar -tv libknlopt.a | grep -c kxmwsd.o
ar -tv libknlopt.a | grep -c kciwcx.o
ar -tv libknlopt.a | grep -c sllfls.o
ar -tv libknlopt.a | grep -c kprnts.o
ar -tv libknlopt.a | grep -c xsnoolap.o
ar -tv libknlopt.a | grep -c kdzof.o
ar -tv libknlopt.a | grep -c kecnr.o
ar -tv libknlopt.a | grep -c dmndm.o
ar -tv libknlopt.a | grep -c kkpoban.o
ar -tv libknlopt.a | grep -c kcsm.o
ar -tv libknlopt.a | grep -c jox.o
ar -tv libknlopt.a | grep -c kzlilbac.o
ar -tv libknlopt.a | grep -c kzvidv.o

Short Name
ASM
DM
DV
OLAP
OLS
PART
RAC
RAT

chopt enable partitioning


chopt disable partitioning

Option
dm
dv
olap
lbac
partitioning
rat
SELECT
a.ksppinm Param ,
b.ksppstvl SessionVal ,
c.ksppstvl InstanceVal,
a.ksppdesc Descr
FROM
x$ksppi a ,
x$ksppcv b ,
x$ksppsv c
WHERE
a.indx = b.indx AND
select name, value from sys.V$PARAMETER where name like '\_%' escape '\' and ISDEFAULT='FALSE';
a.indx = c.indx AND
a.ksppinm LIKE '/_adg%' escape '/'
ORDER BY
1
/

select * from database_properties where property_name like


'%CHARACTERSET'; SELECT * FROM NLS_DATABASE_PARAMETERS;
select global_name from global_name;

SELECT sys_context('USERENV', 'HOST') FROM dual;


SELECT sys_context('USERENV', 'INSTANCE') FROM dual; https://www.morganslibrary.org/reference/sys_context.htm
I created the tablespace with this SQL

create undo tablespace undotbs2 datafile


'/u02/oracle/oradata/test/undotbs2.dbf' size 500m;

Alter the database to use the new UNDO tablespace.


SQL> select t.ts#, s.header_file, s.header_block
alter system set undo_tablespace=undotbs2 scope=both;
from v$tablespace t, dba_segments s
where s.owner = 'SCOTT'
and s.segment_name='DEPARTMENT'
and t.name = s.tablespace_name;
Then take the original UNDO tablespace offline
TS# HEADER_FILE HEADER_BLOCK
alter tablespace undotbs1 offline;
----------
SELECT----------- ------------
utl_inaddr.get_host_address('yahoo.com') FROM dual;
Next drop the corrupted segment.
15 12 9
drop rollback segment "_SYSSMU22$";
Once these three data items are retrieved, the dbv command can
be applied to a particular segment:
Then finally drop the old UNDO tablespace

alter tablespace undotbs1 offline;


dbv userid=scott/tiger segment_id=15.12.9

alter system set log_archive_dest_1='___location=/ora10gsoft/archsam


reopen';
Total Pages Examined
col ORIGINATING_TIMESTAMP : 4 for a40
The last step in resolving
col MESSAGE_TEXT for a80 ORA-00257 is to change the logs for
Total Pages
verification Processed
using:
set linesize 500 (Data) : 3 SELECT
SELECT originating_timestamp,
Total
SQL>Pages Failingswitch
alter system
originating_timestamp, (Data) :0
logfile; message_text
message_text FROM
Total
FROMPages Processed (Index): 0 sys.x$dbgalertext
sys.x$dbgalertext WHERE
Total
WHERE Pages Failing (Index): 0 message_text LIKE '%Instance
message_text LIKE '%Starting up%'; shutdown complete%';
Total Pages Processed (Other): 0

Total Pages Processed (Seg) : 1

Total Pages Failing (Seg) : 0

Total Pages Empty :0

Total Pages
Solaris Marked Corrupt-kv: 0
--> /usr/bin/isainfo cd $ORACLE_HOME/bin
Linux --> uname -m file oracl*
Total Pages Influx :0

Automating dbv
http://www.oracle.com/technetwork/articles/saternos-tables-090560.html
http://dbaoracletips.blogspot.com/2011/11/how-to-dropcreate-database-link-from.html
http://www.orafaq.com/wiki/ChangePerm_sh

This is used when when we loss our all redologs.


U can connect as user called OLD. But if u query it will show only
user as NEW. U can't connect as NEW also.

If you want to display your SID, your connected USER name


instead of “SQL>” you’ve to change “glogin.sql” in your
$ORACLE_HOME/sqlplus/admin directory as below

Revoking that privilege


ALTER USER apex_030200 REVOKE CONNECT THROUGH
system;
948061.1

General All

ar -tv libknlopt.a

kfon.o
dmwdm.o
kzvidv.o
xsyeolap.o
kzlilbac.o
kkpoban.o
kcsm.o
kecwr.o

make -f ins_rdbms.mk option_switch


<== 11g 10g ioracle
==> cd $ORACLE_HOME/rdbms/lib
make -f ins_rdbms.mk part_off ioracle

Database Option ON

Data Mining dm_on


Data Mining Scoring Engine dmse_on
Database Vault dv_on
Label Security lbac_on
Partitioning part_on
Real Application Clusters rac_on
Spatial sdo_on
Real Application Testing rat_on
OLAP olap_on
Automatic Storage Management asm_on
Context Management Text ctx_on
ABASE_PARAMETERS;

org/reference/sys_context.html
OFF

dm_off
dmse_off
dv_off
lbac_off
part_off
rac_off
sdo_off
rat_off
olap_off
asm_off
ctx_off
Pwd verify function extract password

Backdoor Entry to oracle database

oracle password hack

extract dblink password

spoof OSUSER in v$session

Wallet
--ORA-28365: wallet is not open

Auditing

who locked my account

user audit info

audited privileges
Mask password in shell script

user creation time

CREATE statement

Profile creation time

when was my table last changed

When was the table last accessed

when was the password changed for a user

Oracle database vault

checking it is enabled or not

disable
enable
http://orafaq.com/node/58

# sqlplus -prelim / as sysdba


(or)
# sqlplus /nolog
SQL> set _prelim on
SQL> conn / as sysdba
Prelim connection established

http://www.soonerorlater.hu/index.khtml?article_id=513
http://www.petefinnigan.com/weblog/archives/00001103.htm

works under 11.2.0.2


select passwordx from sys.link$ where name='mydblink';

set serveroutput on
declare
db_link_password varchar2(500);
begin
db_link_password :=
'06D05F5E36F13A08FD3C5FE489EB89B094701C114FF156A92D84A5724EF5FC2BA4F25BF
BE99146C22075BEF3012D0F9DC6231FBD1A5EFBFA97DCD8FD13737243992EA16AD5A23
B7DC823346DEB4CD69FE6F20B3F15821FEFF9F44430EE40C78CAEE37DF25F25C2BEDE
D1DD2A61C72351E462BF1B844B2599E5125AE0135EAF7';

dbms_output.put_line ('Plain password: ' || utl_raw.cast_to_varchar2 ( dbms_crypto.decrypt


( substr (db_link_password, 19) , dbms_crypto.DES_CBC_PKCS5 , substr (db_link_password,
3, 16) ) ) );
end;
/

https://oraganism.wordpress.com/2009/10/06/spoofing-vsession-osuser/
Connect to container and check whether WALLET is OPEN or not ? If it is in OPEN state then
connect to PDB and check the same
--ORA-28365: wallet is not open
select status from v$encryption_wallet;
If the wallet is closed at Contaner DB then OPEN it using below command (run in container):

ADMINISTER KEY MANAGEMENT SET KEYSTORE open IDENTIFIED BY abc123


container=all;

If the WALLET IS OPENED in container but CLOSED in PDB level, then run below at container
level

ADMINISTER KEY MANAGEMENT SET KEYSTORE close IDENTIFIED BY abc123


container=all;
ADMINISTER KEY MANAGEMENT SET KEYSTORE open IDENTIFIED BY abc123
container=all;

Now check the wallet status at Container and PBD level:


select status from v$encryption_wallet;

set lines 750 pages 9999


column USERNAME format a20
column OS_USERNAME format a20
column USERHOST format a40
column EXTENDED_TIMESTAMP format a60

SELECT USERNAME, OS_USERNAME, USERHOST, EXTENDED_TIMESTAMP,returncode


FROM SYS.DBA_AUDIT_SESSION WHERE returncode != 0 and username =
'&Account_Locked'
and EXTENDED_TIMESTAMP > (systimestamp-1) order by 4;

select 'standard audit', sessionid,


proxy_sessionid, statementid, entryid, extended_timestamp, global_uid,
username, client_id, null, os_username, userhost, os_process, terminal,
instance_number, owner, obj_name, null, new_owner,
new_name, action, action_name, audit_option, transactionid, returncode,
scn, comment_text, sql_bind, sql_text,
obj_privilege, sys_privilege, admin_option, grantee, priv_used,
ses_actions, logoff_time, logoff_lread, logoff_pread, logoff_lwrite,
logoff_dlock, session_cpu
from
dba_audit_trail;

SELECT * FROM dba_stmt_audit_opts union SELECT * FROM dba_priv_audit_opts;


http://www.tek-tips.com/viewthread.cfm?qid=1605767
http://www.idevelopment.info/data/Unix/Linux/LINUX_CryptCommand.shtml

select a.* from sys.aud$ a, dba_users b


where a.action# = 51 --corresponds to CREATE USER
and a.OBJ$NAME = b.username;

select * From dba_audit_trail


where action_name like '%ALTER USER%'
or action_name like '%CREATE USER%';

select * From dba_audit_trail


where action_name like '%ALTER PROFILE%'
or action_name like '%CREATE PROFILE%';

http://blog.tanelpoder.com/2009/02/07/when-was-a-table-last-changed/
select INSERTS,UPDATES,DELETES,TABLE_NAME,to_char(TIMESTAMP,'DD-MM-YY
HH24:MI') from dba_tab_modifications where table_owner not like '%SYS%' order by
TIMESTAMP desc;
but for the above statement the table level monitoring should be enabled
http://blog.tanelpoder.com/2009/02/07/when-was-a-table-last-changed/

set lines 750 pages 9999


select USER#,NAME, TO_CHAR(ptime, 'DD-MON-YYYY HH24:MI') from user$ order by 1;

http://oradb-srv.wlv.ac.uk/E16655_01/server.121/e17608/dvdisabl.htm

SELECT PARAMETER, VALUE FROM V$OPTION WHERE PARAMETER = 'Oracle Database Vault';

EXEC DVSYS.DBMS_MACADM.DISABLE_DV;
EXEC DVSYS.DBMS_MACADM.ENABLE_DV;
SELECT VALUE FROM V$OPTION WHERE PARAMETER = 'Oracle Label Security';
EXEC LBACSYS.CONFIGURE_OLS;
EXEC LBACSYS.OLS_ENFORCEMENT.ENABLE_OLS;
https://taliphakanozturken.wordpress.com/2012/06/12/the-backdoor-entry-to-oracle-database/

http://murty4all.blogspot.ch/2013/11/decrypting-oracle-database-db-link_29.html
elseadminister key management set keystore close;https://blog.dbi-services.com/encryption-in-oracle-public-cloud/

ORA-01017: invalid username/password; logon denied


ORA-28000: the account is locked
http://blog.tanelpoder.com/2009/02/07/when-was-a-table-last-changed/#more-198

Database Vault';

Oracle Label security must be enabled before you can use Database Vault. If it is not enabled, then this q
restart required
If it is not enabled, then this query returns  FALSE.
tools

oswatcher gui

Notepad++ to add "'," at the end of each table in notepad++

asqlmon for visual explain plan in putty

putty autologin script

set sql prompt

simulate ORA-600 error

getting input
reset the input value

Burning the CPU 100% usage from db level


http://www.oraclerealworld.com/best-oracle-performance-tools/
http://ba6.us/node/177
http://windows.podnova.com/trends/oracle_performance_trace.html

server123:$java -jar -Xmx1024m oswg.jar -is /work/oracle/server123_OSW/osw/archive

ctrl + H, select "regular expression " in search mode ,


find with [\r]+
replace with ',
then replace all
incase if you need all the tables in one line use [\r\n]+

http://blog.tanelpoder.com/2013/03/17/asqlmon-sql-sql-monitoring-like-execution-plan-line-level-drilldown-into-sql-response-tim
Dim UserName
Dim Passwrd
ServerName = InputBox("Please Enter Your Servername:")
Passwrd = InputBox("Please Enter Your RSA TOKEN:")
If ServerName ="" Then
Wscript.Quit
Else
Set shell = WScript.CreateObject("WScript.Shell")
pcmd = "C:\Program Files (x86)\Putty\putty.exe "&Servername & " -pw firstpwd"&Passwrd
Set exec = shell.Exec(pcmd)
Set pout = exec.StdOut
End If

set sqlprompt "_user '@' _connect_identifier >"

execute dbms_system.ksdwrt(2,'ORA-600: test');

accept sid default '' -


prompt 'Please provide the sid: '
undefine sid

DECLARE
L_n NUMBER;
BEGIN
WHILE (TRUE)
LOOP
L_ n:= dbms_random.random();
END LOOP;
END;
/
start of line
------------------ place ur mouse at the start of the
ctrl + H, select "regular expression " in search mode , first line in ur list.
find with ^ Press Alt + "C"
replace with ' A window gets opened. Enter the
END OF LINE text that u want to add under
----------------- "Text to Insert" and press OK.
ctrl + H, select "regular expression " in search mode , Apply the same procedure for
find with $ adding text at the end of all the
replace with ', lines. https://stackoverflow.com/ques

-level-drilldown-into-sql-response-time/

https://blog.dbi-services.com/oracle-11g-instance-caging-limit-database-cpu-consumption/
Oracle Hacking

Tracing User session

Monitoring scripts

Oracle University Books

RAC Performance issue

RAC

DB Parameter to Oracle Compile-Time Constant Mappin

secret functions of oracle

sql query writing Best practices

check this url before tuning database

forcing parallel in sql without code change

All important scripts (Performance Tuning)

optimizer Magic

Optimizer bug fix control


http://theinterw3bs.com/wiki/index.php?title=Hacking_Oracle

http://www.scribd.com/doc/2966777/oracle-cheat-SQLPlus-Commands
http://www.oracle-base.com/articles/10g/SQLTrace10046TrcsessAndTkprof10g.php

http://www.blacksheepnetworks.com/security/resources/www.think-forward.com/sqltips.htm

http://www.colestock.com/blogs/labels/Monitoring.html

http://allr1.blackapplehost.com/
http://goodies.dale-emmons.com/Documentation/books/Oracle/
http://search.4shared.com/q/10/oracle%2011g

http://www.slideshare.net/karlarao/performance-scenario-diagnosing-and-resolving-sudden-slow-down-on-two-node-rac

http://www.morganslibrary.com/reference/rac.html

http://yong321.freeshell.org/oranotes/DbParam_CompTimeConst_Map.txt

http://www.perfvision.com/papers.php

http://beginner-sql-tutorial.com/sql-query-tuning.htm
http://sql-tuning.com/oracle-sql-performance-tuning/
https://gavinsoorma.com/2012/11/ash-and-awr-performance-tuning-scripts/

http://dbaclass.com/article/change-the-execution-plan-without-changing-the-sql-query/

http://guyharrison.squarespace.com/opsgsamples/

http://optimizermagic.blogspot.com/

https://coskan.wordpress.com/2011/02/14/plan-stability-through-upgrade-why-is-my-plan-changed-bugfixes-1/
Super
Scenarios

TYPE LEVELS OPTIONS


RMAN Clone Same server Same diskgroup
Different diskgroup

Different server Same diskgroup


Different diskgroup

RMAN Restore Same server Same diskgroup


Different diskgroup

Different server Same diskgroup


Different diskgroup

EXP Table Level Single Table


Multiple Table

Schema Level Single Schema


Multiple Schema

Database FULL DB

IMP Table Level Single Table


Multiple Table

Schema Level Single Schema


Multiple Schema

Database FULL DB

EXPDP Table Level Single Table


Multiple Table

Schema Level Single Schema

Multiple Schema

Database FULL DB

IMPDP Table Level Single Table


Multiple Table

Schema Level Single Schema


Multiple Schema

Database FULL DB

Network Direct IMPORT


Features

scp algorithm

exclude Table

Exclude Common

Remap Schema

Remap Tablespace

Remap Table

TABLE_EXISTS_ACTION

12c

expdp in Background

check free space on importing


tablespace
Script

cat > expdp_table_refresh.par <<EOF


userid='/ as sysdba'
directory=DATA_PUMP_DIR
dumpfile=TABLE1_%U.dmp
logfile=TABLE1.log
tables=SCHEMA.TABLE1
parallel=8
EOF nohup expdp parfile=testfile.par &
cat > expdp_table_refresh.par <<EOF
userid='/ as sysdba'
directory=DATA_PUMP_DIR
dumpfile=TABLE1_%U.dmp
logfile=TABLE1.log
tables=SCHEMA1.TABLE1,SCHEMA2.TABLE2
parallel=8
EOF

cat > expdp_schema_refresh.par <<EOF


userid='/ as sysdba'
directory=DATA_PUMP_DIR
dumpfile=SCHEMA_NOBIGTABLES_%U.dmp
logfile=SCHEMA_NOBIGTABLES.log
schemas=SAMPLE_SCHEMA
exclude=table:"IN('TABLE1','TABLE2','TABLE3')"
parallel=8
EOF

cat > expdp_schema_refresh.par <<EOF


userid='/ as sysdba'
directory=DATA_PUMP_DIR
dumpfile=SCHEMA_NOBIGTABLES_%U.dmp
logfile=SCHEMA_NOBIGTABLES.log
schemas=SAMPLE_SCHEMA1,SAMPLE_SCHEMA2
exclude=table:"IN('TABLE1','TABLE2','TABLE3')"
parallel=8
EOF

cat > expdp_schema_refresh.par <<EOF


userid='/ as sysdba'
directory=DATA_PUMP_DIR
dumpfile=SCHEMA_NOBIGTABLES_%U.dmp
logfile=SCHEMA_NOBIGTABLES.log
FULL=Y
parallel=8
EOF
scp -c arcfour -r
myuserid@sourceserver:/explocation/dumpfile.dmp .

exclude=table:"IN('TABLE1','TABLE2','TABLE3')" http://www.acehints.com/2012/11
exclude=TABLE:"LIKE 'EXAM%'"
exclude=TABLES:">'F'"

exclude=SEQUENCE,PROCEDURES,INDEXES,TABLES:"IN ('EMP1','DEPT')"

REMAP_SCHEMA=SCHEMA1:DUPSCHEMA2
TABLE_EXISTS_ACTION=SKIP

SELECT table_name, tablespace_name FROM


dba_tables WHERE owner='HR';
REMAP_TABLESPACE =
USERS:EXP_TBS1,USERS2:EXP_TBS2

Same Schema
remap_table=emp:emp_bkup
different schema
REMAP_SCHEMA=SCHEMA1:DUPSCHEMA2
remap_table=emp:emp_bkup

APPEND, REPLACE, [SKIP] and TRUNCATE

TRANSFORM=DISABLE_ARCHIVE_LOGGING:Y

nohup expdp parfile=testfile.par &


tail -200f nohup.out

SELECT tablespace_name,
SUM (bytes) / (1024 * 1024) "FREE(MB)"
FROM dba_free_space where
tablespace_name=UPPER('&TABLESPACE_NAME')
GROUP BY tablespace_name;
http://www.acehints.com/2012/11/data-pump-impdp-remaptable-option-to.html
Issue
ADR Different Methods to Create IPS Package (Doc ID )
Quick Steps for ADRCI
ORA-04031: troubleshoot Tool
XDB Component has INVALID
SRDC - How to Collect Standard Information for a SQL Performance Problem
TFA Collector - TFA with Database Support Tools Bundle
ID
411.1
443529.1
559339.1
1552438.1
1594386.1
1513912.1

You might also like