You are on page 1of 520

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

find all files containing specific text on Linux?


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 between two folders including all files inside

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

Find a file name contain a particular string

Screen Command

Password encryption

Grep Command to display two lines above and below


Folder size including hidden folders

file occupied by whom


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
find . -type f | xargs grep dc7h92zrnpbnq
find . -type f -exec grep -l "dc7h92zrnpbnq" {} \;

uuencode file.txt file.txt | mailx testmail@domain.com


uuencode file.txt file.txt | mailx -s "this mail has attachments" testmail@domain.com
mailx -a textfile.txt testmailreceiver@domain.com
mailx -s "Test email `hostname`" testmail@domain.com < /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 -r folder1 folder2

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


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

find . -type f -exec grep -l "DBMS_STATS: GATHER_STATS_JOB: Stopped by Scheduler." {} \;

screen -S Patching ( Starting New session with Name incase of multiple screen session going to open)
screen -ls ( To list the existing screen sessions )
screen -r -d screen_name ( For attaching a existing screen name)
screen -r ( Attaching the existing screen automatically if only one session found )
screen -x Screen_name ( Attaching Multiple display Screen )

CTRL ad ( dettaching your screen without terminating )

echo -e mypwd | base64

grep -A 2 FAILED file_name


grep -B 2 FAILED file_name
grep -C 2 FAILED file_name
du -sch .[!.]* * |sort -h

/usr/sbin/lsof +L1 /opt/oracle


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
grep -rnw /location -e "dc7h92zrnpbnq"

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
Just to brief the changes use below command

diff --brief -r folder1 folder2


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

display below 2 lines


display Above 2 lines
display above and below 2 lines
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 {} ;
play-two-files-side-by-side
prstat -Z
Host CPU utilization report from DATABASE

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
Server maintenance

Now that you confirmed the process 16514 is consuming a lot of memory, you
can "freeze" it—but not kill it—using the skill command.

Network Waitevent by database


max(decode(to_char(END_TIME,'HH24'),'13',AVERAGE,0)) "13",
max(decode(to_char(END_TIME,'HH24'),'14',AVERAGE,0)) "14",
max(decode(to_char(END_TIME,'HH24'),'15',AVERAGE,0)) "15",
max(decode(to_char(END_TIME,'HH24'),'16',AVERAGE,0)) "16",
max(decode(to_char(END_TIME,'HH24'),'17',AVERAGE,0)) "17",
max(decode(to_char(END_TIME,'HH24'),'18',AVERAGE,0)) "18",
max(decode(to_char(END_TIME,'HH24'),'19',AVERAGE,0)) "19",
max(decode(to_char(END_TIME,'HH24'),'20',AVERAGE,0)) "20",
max(decode(to_char(END_TIME,'HH24'),'21',AVERAGE,0)) "21",
max(decode(to_char(END_TIME,'HH24'),'22',AVERAGE,0)) "22",
max(decode(to_char(END_TIME,'HH24'),'23',AVERAGE,0)) "23"
from DBA_HIST_SYSMETRIC_SUMMARY
where METRIC_NAME like 'Host CPU Utilization%' and INSTANCE_NUMBER = &inst_num
group by to_char(BEGIN_TIME,'DD-Mon');

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
ARCn:
ps Redo
-ef|grep log archivers
pmon | awk '{print $8}'|grep -v "grep"| grep -v "ASM"| cut -d"_" -f3
CJQn: Job scheduler coordinator
Dnnn:
ps -eafDispatchers
| grep _pmon_ | grep -v grep | grep -v + | grep -v "^#" | awk '{print $NF}' | cut -c 10-
DIA0:
echo 'select count(*)process
Diagnosibility 0 | sqlplus / as sysdba
from tab;'
ACMS: Atomic controlfile
DIAG: Diagnosibility to memory server
coordinator
CKPT:
FDBA: Checkpoint
Flashback data archiver process
DBRM:
Jnnn: Job Resource
schedulermanager process
processes
DBWn:
PING:
ps Database
grep ora_ |writer
-ef |Interconnect processes
latency
grep measurement
orcl2 | awk '{print $2}' | while read PID
LGWR:
Qnnn:
do Redo log
Queue writerprocesses
cleanup
LMDn:
QMNC:
kill -STOP Global
Queue
$PIDenqueue service daemons
coordinator
LMON:
RECO: Global enqueue
done Distributed recovery service monitor
process
MMAN:
Snnn: Memory
Shared manager
servers
ps -ef | grep <keyword> | grep -v grep | awk '{print $2}' | xargs kill -9
PMON:
SMCO: Process monitor
Space management coordinator
PSPn: Process spawners
Wnnn: Space management processes
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
# ------------------------------------------------------------------------
sqlplus
# A simple -s "/ as sysdba"
kornshell 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

col c1 heading
chmod 755 osprecheck.sh
'end|time' format a10
col c2 heading 'wait|class' format a20
./osprecheck.sh
col c3 heading 'time|waited'
| tee presnap.txt
format 999,999,999,999

break on c1 skip 2

select
trunc(end_interval_time) c1,
wait_class
Freeze => c2,
skill -STOP 1
sum(time_waited) c3
Continue => skill -CONT 16514
from
skill -STOP oracle
dba_hist_service_wait_class
skill
join -STOP rman
dba_hist_snapshot USING(snap_id)
where
wait_class = 'Network'
group by
trunc(end_interval_time),
wait_class
order by
trunc(end_interval_time),
c3 desc;
Comments

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

for linux

Solaris
do
export
ORACLE
_SID=$i
sqlplus
-s /nolog
<<EOF
>/tmp/tem
p.sql
set head
off echo
off
conn / as
sysdba
ps -eo comm| grep -v grep|grep pmon|sed s/ora_pmon_//
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
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

#!/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

https://www.oracle.com/technetwork/articles/linux/part2-085179.html

You can use a user, a PID, a command or terminal id as argument. The following stops all rman commands
As you can see, skill decides that argument you entered—a process ID, userid, or command—and acts appropriately. This may
|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/....$//'`

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
cts appropriately. This may cause an issue in some cases, where you may have a user and a command in the same name. The best examp
me name. The best example is the "oracle" process, which is typically run by the user "oracle". So, when you want to stop the process called
to stop the process called "oracle" and you issue:
Identify the Exadata Box type

cell versions

offloading saved

exadata resource manager plans

Exadata Serial Numbers

% Saved from exadata Storage

Session waiting for CPU -


Resource manager

Dcli
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)

/opt/oracle.SupportTools/CheckHWnFWProfile -S

select inst_id,sql_id,
decode(IO_CELL_OFFLOAD_ELIGIBLE_BYTES,0,'No','Yes') Offloaded,
decode(IO_CELL_OFFLOAD_ELIGIBLE_BYTES,0,0,
100*(IO_CELL_OFFLOAD_ELIGIBLE_BYTES-
IO_INTERCONNECT_BYTES)/
IO_CELL_OFFLOAD_ELIGIBLE_BYTES) "IO_SAVED_%"
from gv$sql
where sql_id='&sql_id';

SELECT s.sid sess_id, g.name consumer_group,


s.state, s.consumed_cpu_time cpu_time, s.cpu_wait_time, s.queued_time,
(s.CURRENT_SMALL_READ_MEGABYTES+s.CURRENT_LARGE_READ_MEGABYTES)
read_MB,
(s.CURRENT_SMALL_WRITE_MEGABYTES+s.CURRENT_LARGE_WRITE_MEGABYTES)
write_mb
FROM v$rsrc_session_info s, v$rsrc_consumer_group g
WHERE s.current_consumer_group_id = g.id

dcli -l root -g dbs_group "ls -ltr / | grep -i acfs_u01"


HP => High Performance
HC => High Capcity

http://oradwstories.blogspot.com/2015/02/detecting-change-in-

run as root
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 mg for a55
forformat
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 offormg
a10on v$asm_disk
from inst where header_status='CANDIDATE' or
col FAILGROUP
whenever sqlerrorforexit
header_status='FORMER' a20 1 order by 1 ;
set pages
lines 750 0 feed
pages 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 file_type, c.bytes
a15 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.0in 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' S
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 format TEST
a6 INCLUDING CONTENTS;
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


kfod asm_diskstring='ORCL:*' disk=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
srvctl config database -db PRODDB | grep -i pass
. oraenv +ASM1
asmcmd --privilege sysdba pwcopy +DATA1/PRODDB/orapwPRODDB /tmp/orapwPRODDB

scp /tmp/orapwPRODDB userid@server.domain.com:/tmp

BCP:
----
. oraenv +ASM1
asmcmd --privilege sysdba pwcopy --dbuniquename STBYDB /tmp/orapwPRODDB
+DATA1/STBYDB/PASSWORD/orapwSTBYDB
(or)
ASMCMD> pwcopy /tmp/orapwPRODDB.295.999492555 +DATA1/STBYDB

. oraenv STBYDB
srvctl modify database -db STBYDB -pwfile
+DATA1/STBYDB/PASSWORD/pwdSTBYDB.3087.999923145
srvctl config database -db STBYDB | grep -i pass

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, mg from (
b.path, b.header_status
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…

0050768018E027998000000000010F6d0s0' 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/

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

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

Role based service check


/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'

crsctl stat res ora.dbname.service_name.svc -p | egrep '(USR_ORA


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

Primary --> primary role


physical_standby --> standby role
/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

Standby DB Name
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

Restore Archivelog Backups taken on the Primary Database to


the Standby Database

Standby Realtime apply enabled or not ( run this on stby)


Full details of the DG db details from dgmgrl
Run this at Primary
-------------------
select
set pagesdistinct
1000error from gv$archive_dest ;
set
set lines
lines 120
160
column DEST_NAME format
col STBY_BEHIND_BY a20
for a20
column DESTINATION format a35
select (select sysdate from dual)"TIMESTAMP",s.thread#,s.MAX_SEQ#, a.MAX_APP_SEQ#, ' '||
column ARCHIVER format a10
(s.MAX_SEQ#-a.MAX_APP_SEQ#)||' sequences' "STBY_BEHIND_BY" from
column
( select TARGET format a15
thread#,max(sequence#) "MAX_SEQ#" from v$archived_log where activation#=(select activation#
column status format
from v$database) a10by thread# ) s,
group
column error format a15
(select thread#,max(sequence#) "MAX_APP_SEQ#" from v$archived_log where activation#=(select
select DEST_ID,DEST_NAME,DESTINATION,TARGET,STATUS,ERROR
activation# from v$database )and applied='YES' group by thread#) a where from v$archive_dest
a.thread#=s.thread#;
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 (select name from v$database) PRIMARY ,DB_UNIQUE_NAME STANDBY_NAME from
v$archive_dest where TARGET='STANDBY' and status='VALID';
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 PARALLEL
set log_archive_dest_2='service="stbydbname",LGWR 8 DISCONNECT
ASYNC NOAFFIRM delay=0FROM
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 8 HH24: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;
}

$rman target sys/pass@<connect_string> catalog rcvcat/rcvcat@<connect_string> auxiliary /

run {
set archivelog destination to '/data/archivelog';
restore clone archivelog from sequence 55 until sequence 56;
}

select DEST_ID,dest_name,status,type,srl,recovery_mode from v$archive_dest_status where dest_id=1;


dgmgrl > validate database verbose db_name
onprimary
http://sanzdbaworld.blogspot.com/2012/09/how-query-dataguard-status-physical.html
--------------
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# order by
s.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
run {
allocate channel prmy1 type disk;
allocate channel prmy2 type disk;
allocate channel prmy3 type disk;
allocate channel prmy4 type disk;
allocate auxiliary channel stby1 type disk;
allocate auxiliary channel stby2 type disk;
allocate auxiliary channel stby3 type disk;
allocate auxiliary channel stby4 type disk;
duplicate target database for standby
from active database section size 10G dorecover;
}
onprimary
us-physical.html
--------------
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#;

d_log where applied='NO' order by sequence#;


L-broker-with-example
Sessions

Total user count on database

Users Details Session

v$sql_monitor

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

SQL Monitor report for sql_id for a specific snap_id

Real-Time SQL Monitoring - AWR(FULL_CAPTURE)

Sid Level Debug

Long Running query - long ops

Wait event for a SID


Wait event for a SID

RealTime Monitoring for sid

Sql details

Currently running SQL query's

RealTime Monitoring for sql_id

SQL History

Top 50 sql's where running at a particular snapshot time

Identify
Identify

statistics of objects of a specific sql id

PGA/TEMP Used by a SQL_ID

How to check the Run time changes of


sql execution Plans due to adaptive 12c features

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

Worst and best PLAN_HASH_VALUE calulator for a sql_id


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

Sql_text that is rolling back

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/flush the old plan hash value from memory

flush a cursor /sql_id from shared_pool'

Sql profile All in All

Sql_doctor script
AAS - Average active session from history/AWR

aas-per-min.sql

aas-per-hour.sql (AWR)

Unstable Plans/ More than one Plan Hash Value PHV

Forensic Analysis of sql


History of all sql between two sample times

Min and Max execution time for a sql_id based on PHV

Optimizer details for a sql_id ( DBA_HIST_SQL_STAT )

explain plan for the sqlid with specific PHV

explain pan for PHV ( dba_hist_sql_plan )


History of histogram changes

Automatic tuning advice for a specified SQL_ID


set lines 750 pages 9999
set linesize
break 750 pages 9999
on report
column box
compute SUM format
of tota30
on report
column
compute spid
SUM format
of a10 on report
active
set lines
column 1000 pages
username format9999
a30
compute
column SUM
sid formatof inactive
9999 a30 on report
column
col program
username for format
a50
column
column serial
os_user forformat
999999 a20
select
column DECODE(username,NULL,'INTERNAL',USERNAME)
status format a15
col LOGON_TIME
Username, for a20
column username format a10
columncount(*)
sql_textTOT, format a80
select b.inst_id,b.sid,b.serial#,a.spid,
COUNT(DECODE(status,'ACTIVE',STATUS)) substr(b.machine,1,30)
ACTIVE,
column module
box,to_char format a30 'dd-mon-yyyy hh24:mi:ss')
(b.logon_time, logon_time,
col COUNT(DECODE(status,'INACTIVE',STATUS))
program for a30 INACTIVE
substr(b.username,1,30)
from gv$session username,
col SQL_EXEC_START
substr(b.osuser,1,20) for a20
os_user,
where status in ('ACTIVE','INACTIVE')
substr(b.program,1,30)
group by username; program,status,b.last_call_et AS
SELECT * FROM
last_call_et_secs,b.sql_id
from(SELECT
gv$session status,inst_id,sid,SESSION_SERIAL#
b,gv$process a as
Serial,username,sql_id,SQL_PLAN_HASH_VALUE,
where b.paddr = a.addr
andMODULE,program,
a.inst_id = b.inst_id
TO_CHAR(sql_exec_start,'dd-mon-yyyy hh24:mi:ss') AS
and type='USER'
sql_exec_start,
SELECT
order by SNAP_ID,report_id
b.inst_id,b.sid; Rid,
ROUND(elapsed_time/1000000) AS "Elapsed (s)",
ROUND(cpu_time /1000000)
EXTRACTVALUE(XMLType(report_summary),'/report_repository_sumAS "CPU (s)",
substr(sql_text,1,30)
mary/sql/@sql_id') sql_id, sql_text
columnFROMtext_line format a254
gv$sql_monitor where status='EXECUTING' and module
set lines 750 pages
not like '%emagent%' 9999
EXTRACTVALUE(XMLType(report_summary),'/report_repository_sum
set long
ORDER20000 BYlongchunksize
mary/sql/@sql_exec_id') sql_exec_start 20000
desc
sql_exec_id,
select);
dbms_sqltune.report_sql_monitor_list() text_line
EXTRACTVALUE(XMLType(report_summary),'/report_repository_sum
from dual;
mary/sql/@sql_exec_start') sql_exec_start
FROM dba_hist_reports
select
WHERE component_name = 'sqlmonitor' and
dbms_sqltune.report_sql_monitor() text_line
(EXTRACTVALUE(XMLType(report_summary),'/report_repository_sum
from dual;
mary/sql/@sql_id'))='&sql_id' and snap_id=&snap_id;
specific
set snap_id
linesize 750 pages 9999
column box format a30
column spid format a10
set long 10000000 longchunksize 10000000 pages 0
column username format a20
SELECT
column program format a30
DBMS_AUTO_REPORT.REPORT_REPOSITORY_DETAIL(RID =>
column os_user format a20
&RID, TYPE => 'text') FROM dual;
col LOGON_TIME for a20

select b.inst_id,b.sid,b.serial#,a.spid, substr(b.machine,1,30)


box,to_char (b.logon_time, 'dd-mon-yyyy hh24:mi:ss') logon_time,
substr(b.username,1,20) username,
DBMS_AUTO_REPORT.START_REPORT_CAPTURE;
substr(b.osuser,1,20) os_user,
DBMS_AUTO_REPORT.FINISH_REPORT_CAPTURE;
substr(b.program,1,30) program,status,b.last_call_et AS
gv$session
last_call_et_secs,b.sql_id
from gv$session b,gv$process a
SELECT
where b.paddr = a.addr
a.sid,RPAD(a.opname,30),a.sofar,a.totalwork,a.ELAPSED_SECONDS
and a.inst_id = b.inst_id
,ROUND(((a.sofar)*100)/a.totalwork,3) "%_COMPLETED",
and type='USER' andusername,a.SQL_HASH_VALUE,B.STATUS
RPAD(a.username,10) b.sid=&sid
order by
FROM logon_time;
gV$SESSION_LONGOPS a, gv$session b
WHERE a.sid=b.sid
and a.sid=&sid
--AND b.status='ACTIVE'
AND a.sofar<> a.totalwork
/
Currently waiting ?
COL ap_secs HEA 'App Secs|Per Exec';
SELECT
'999,990.000')
FROM sw.inst_id,NVL(s.username,
TO_CHAR(ROUND(h.iowait_total
ap_secs_per_exec, '(oracle)') AS username,
/ h.executions_total / 1e6, 3),
COL cc_secs HEA 'Conc Secs|Per Exec';
s.sid,
'999,990.000') io_secs_per_exec,
TO_CHAR(ROUND(h.ccwait_total / h.executions_total / 1e6, 3),
COL(SELECT
pl_secs HEA status,'PLSQL Secs|Per Exec';
s.serial#,
TO_CHAR(ROUND(h.clwait_total
'999,990.000')
--username, cc_secs_per_exec, / h.executions_total / 1e6, 3),
COL ja_secs HEA 'Java Secs|Per Exec';
sw.event,
'999,990.000')
sql_id, cl_secs_per_exec,
TO_CHAR(ROUND(h.plsexec_time_total / h.executions_total /
SELECT 'SQLAREA' source,h.inst_id,(1111/1111) snap_id,
1e6,sw.wait_class,
TO_CHAR(ROUND(h.apwait_total
3), '999,990.000')
sql_exec_id, pl_secs_per_exec,
TO_CHAR(LAST_LOAD_TIME, 'DD-MON-YYYY HH24:MI') / h.executions_total / 1e6, 3),
sw.wait_time,
'999,990.000') ap_secs_per_exec,
TO_CHAR(ROUND(h.javexec_time_total
TO_CHAR(sql_exec_start,'dd-mon-yyyy /hh24:mi:ss')
h.executions_total
AS /
set lines
snap_time, 1500 pages 9999
1e6, sw.seconds_in_wait,
TO_CHAR(ROUND(h.ccwait_total
3), / h.executions_total / 1e6, 3),
column sid format 9999ja_secs_per_exec
'999,990.000')
sql_exec_start,
TO_CHAR(LAST_ACTIVE_TIME, 'DD-MON-YYYY HH24:MI')
FROM sw.state
'999,990.000') cc_secs_per_exec,
dba_hist_sqlstat
column
end_time, username format h,
ROUND(elapsed_time/1000000) a15 AS "Elapsed (s)",
FROM gv$session_wait
dba_hist_reports
ROUND(cpu_time s sw,
TO_CHAR(ROUND(h.plsexec_time_total /1000000) format a15 / h.executions_total
AS "CPU (s)", /
column PARSING_SCHEMA_NAME
h.sql_id,
1e6,
WHERE gv$session
3), h.sql_ids = '&sql_id'
'999,990.000')
buffer_gets, pl_secs_per_exec,
column SQL_EXEC_START
h.plan_hash_value, for a21
WHERE
AND s.sid
h.sql_id = =sw.sid and s.inst_id=sw.inst_id
TO_CHAR(ROUND(h.javexec_time_total
ROUND(physical_read_bytes /(1024*1024)) andASs.sid=&sid
/ h.executions_total
"Phys reads /
column sql_text format a50
h.executions,
ORDER
1e6,
set 3),
lines BY
1000 sw.seconds_in_wait
'999,990.000')
pages DESC;
ja_secs_per_exec
9999
(EXTRACTVALUE(XMLType(s.report_summary),'/report_repository_su
(MB)",
column module format a35
TO_CHAR(ROUND(h.rows_processed ), '999,999,999,999')
FROM
COL dba_hist_sqlstat
instance_number
Elapsed/CPU/Read/Write
mmary/sql/@sql_id'))
select FOR h,
MB9999 HEA 'Inst';
ROUND(physical_write_bytes/(1024*1024)) AS "Phys writes
rows_processed,
COL
AND
(MB)" dba_hist_snapshot
end_time
s.snap_id HEA 'Ends Time';
= h.snap_id
a.inst_id,a.sid,a.username,b.PARSING_SCHEMA_NAME,a.module,a.
TO_CHAR(ROUND(h.elapsed_time / 1e6, 3), '999,990.000')
WHERE
COL
AND FROM h.sql_id
plan_hash_value
s.dbid = '&sql_id'
= h.dbid
gv$sql_monitor
sql_id,a.sql_child_number HEAchild,b.plan_hash_value,to_char
'Plan|Hash
where sid=&sidValue';and inst_id=&inst_id
et_secs,
AND
col sql_ids.snap_id
for a15 =
s.instance_number
ORDER
(a.sql_exec_start, BY h.snap_id
elapsed_time = h.instance_number
DESC
'dd-Mon-yyyy hh24:mi:ss')
TO_CHAR(ROUND(h.cpu_time / 1e6, 3),sql_exec_start,(sysdate-
'999,990.000')
AND
col
UNION ) s.dbid
ALL = h.dbid
SQL_PROFILE
sql_exec_start)*24*60*60 for a30
cpu_secs,
AND
COL
SELECT
WHERE h.executions_total
executions_total
'SQLAREA'
rownum<=20; FOR> 999,999
0 HEA 'Execs|Total';
source,h.inst_id,(1111/1111)
SECS,b.rows_processed,a.status,substr(b.sql_text,1,50) SNAP_ID,
TO_CHAR(ROUND(h.USER_IO_WAIT_TIME / 1e6, sql_text
3),
AND
COL s.instance_number
rows_per_exec
TO_CHAR(LAST_LOAD_TIME,
from gv$session HEA
a,gv$sqlarea b = h.instance_number
'Rows |Per Exec';
'DD-MON-YYYY HH24:MI:SS')
'999,990.000') io_secs,
UNION
COL
start_time,
where ALL
et_secs_per_exec
a.sql_hash_value HEA 'Elap Secs|Per Exec'; / 1e6, 3),
= b.hash_value
TO_CHAR(ROUND(h.CLUSTER_WAIT_TIME
SELECT
COL
and 'SQLAREA'
cpu_secs_per_exec
TO_CHAR(TO_CHAR((select
a.sql_address source,h.inst_id,(1111/1111)
HEA
= b.address 'CPU Secs|Per Exec';
max(sql_exec_id) snap_id,
from
'999,990.000')
v$sqlarea/v$sql cl_secs,
( ALL )
COL TO_CHAR(LAST_LOAD_TIME,
io_secs_per_exec
gv$sql_monitor where HEA 'IO
sql_id='&sql_id'
and TO_CHAR(ROUND(h.APPLICATION_WAIT_TIME
a.module not like '%emagent%' 'DD-MON-YYYY
Secs|Per ))) Exec';
sql_exec_id, HH24:MI')
/ 1e6, 3),
snap_time,
COL cl_secs_per_exec
h.sql_id,
and a.module ap_secs, HEA 'Clus
not like '%oraagent.bin%' Secs|Per Exec';
'999,990.000')
and TO_CHAR(LAST_ACTIVE_TIME,
COL ap_secs_per_exec
h.plan_hash_value,
sql_text HEA 'App Secs|Per
not like '%b.PARSING_SCHEMA_NAME%'
TO_CHAR(ROUND(h.CLUSTER_WAIT_TIME
'DD-MON-YYYY
Exec'; / 1e6, HH24:MI')
3),
end_time,
COL cc_secs_per_exec
h.executions,
and a.username is not null HEA 'Conc Secs|Per Exec';
'999,990.000') cc_secs,
orderh.sql_id,
COL pl_secs_per_exec
h.rows_processed,
by a.status;
TO_CHAR(ROUND(h.PLSQL_EXEC_TIME HEA 'PLSQL Secs|Per Exec'; / 1e6, 3),
COL h.plan_hash_value,
ja_secs_per_exec
TO_CHAR(ROUND(h.elapsed_time HEA 'Java Secs|Per Exec';
/ h.executions / 1e6, 3),
'999,990.000')
v$sqlarea/v$sql pl_secs,
( sql_id )
COL h.executions,
DISK_READS_TOTAL
'999,990.000') et_secs_per_exec, HEA 'Disk|reads';
TO_CHAR(ROUND(h.JAVA_EXEC_TIME / 1e6, 3),
COL TO_CHAR(ROUND(h.rows_processed
BUFFER_GETS_TOTAL
TO_CHAR(ROUND(h.cpu_time HEA 'Buffer|gets'; / h.executions),
/ h.executions / 1e6, 3),
'999,990.000') ja_secs
'999,999,999,999')
'999,990.000') rows_per_exec,
cpu_secs_per_exec,
FROM gv$sqlarea h
select TO_CHAR(ROUND(h.elapsed_time
* from (0SELECT / h.executions
h.instance_number,h.SNAP_ID,
TO_CHAR(ROUND(h.USER_IO_WAIT_TIME / 1e6, 3), / 1e6,
/ h.executions
WHERE
set pagesize h.sql_id echo= '&sql_id'
off timing off linesize 1000 trimspool on trim on
'999,990.000')
3), '999,990.000') et_secs_per_exec,
h.sql_id,sql_profile,io_secs_per_exec,
order2000000
long by source,snap_id,snap_time,end_time
longchunksize 2000000 ;
TO_CHAR(ROUND(h.cpu_time
h.plan_hash_value,
TO_CHAR(ROUND(h.CLUSTER_WAIT_TIME / h.executions / 1e6, 3),
h.executions /
select
Sql_monitor report
'999,990.000')
1e6, 3), cpu_secs_per_exec,
h.executions_total,
'999,990.000') cl_secs_per_exec,
DBMS_SQLTUNE.REPORT_SQL_MONITOR(
TO_CHAR(ROUND(h.USER_IO_WAIT_TIME
TO_CHAR(ROUND(h.rows_processed_total
TO_CHAR(ROUND(h.APPLICATION_WAIT_TIME / h.executions
/ h.executions_total),
/ h.executions / 1e6,/
sql_id=>'&sql_id',
3),
1e6,'999,990.000')
'999,999,999,999')
3), '999,990.000') io_secs_per_exec,
rows_per_exec,
ap_secs_per_exec,
report_level=>'ALL',
TO_CHAR(ROUND(h.CLUSTER_WAIT_TIME
TO_CHAR(ROUND(h.elapsed_time_total / h.executions //
/ h.executions_total
type=>'TEXT')
1e6, 3), '999,990.000') cl_secs_per_exec,
cc_secs_per_exec,
et_secs_per_exec,
from dual;
TO_CHAR(ROUND(h.APPLICATION_WAIT_TIME
TO_CHAR(ROUND(h.PLSQL_EXEC_TIME
TO_CHAR(ROUND(h.cpu_time_total / h.executions_total/ h.executions
/ h.executions 1e6, /
/ /1e6,
All
1e6,in 3),
one'999,990.000') ap_secs_per_exec,
3), '999,990.000') pl_secs_per_exec,
cpu_secs_per_exec,
TO_CHAR(ROUND(h.CLUSTER_WAIT_TIME
TO_CHAR(ROUND(h.iowait_total
TO_CHAR(ROUND(h.JAVA_EXEC_TIME / h.executions_total / h.executions
/ h.executions / 1e6, / 3),
3),
/ 1e6,
1e6, 3), '999,990.000')
'999,990.000') cc_secs_per_exec,
io_secs_per_exec,
ja_secs_per_exec
FROM TO_CHAR(ROUND(h.PLSQL_EXEC_TIME
TO_CHAR(ROUND(h.clwait_total
gv$sqlarea_plan_hash h / h.executions
/ h.executions_total / 1e6,/ 1e6,
3),
3), '999,990.000')
'999,990.000')
WHERE h.sql_id pl_secs_per_exec,
cl_secs_per_exec,
= '&sql_id'
TO_CHAR(ROUND(h.JAVA_EXEC_TIME
orderTO_CHAR(ROUND(h.apwait_total
by source,snap_id,start_time ; / h.executions/ 1e6,
/ h.executions_total / 1e6,3),3),
'999,990.000') ja_secs_per_exec
ap_secs_per_exec,
FROM gv$sqlarea_plan_hash h
TO_CHAR(ROUND(h.ccwait_total / h.executions_total / 1e6, 3),
WHERE h.sql_id
'999,990.000') = '&sql_id'
cc_secs_per_exec,
ANDTO_CHAR(ROUND(h.plsexec_time_total
h.executions > 0 / h.executions_total /
order3),
1e6, by'999,990.000')
source,snap_id,snap_time,end_time
pl_secs_per_exec, ;
TO_CHAR(ROUND(h.javexec_time_total / h.executions_total /
1e6,
TOP3), '999,990.000')
CPU Used ja_secs_per_exec,
DISK_READS_TOTAL ,BUFFER_GETS_TOTAL
FROM dba_hist_sqlstat h
WHERE
h.snap_id = 11706
AND h.executions_total > 0
order by et_secs_per_exec desc ) where rownum <=50;
sql_id
sample_time,
set linessql_exec_start,
300 set pages 300
DELTA_READ_IO_BYTES,
col table_name for a40
col ownersql_exec_id,
for a30
select greatest(PGA_ALLOCATED
distinct owner, table_name,- STALE_STATS,first_value(PGA_ALLOCATED)
last_analyzed, over
(partition
stattype_locked by sql_id,sql_exec_id order by sample_time rows 1
preceding),0)
from DELTA_PGA,
dba_tab_statistics
col exact_matching_signature for 99999999999999999999999999
greatest(TEMP_SPACE_ALLOCATED
where (owner, table_name) in -
col sql_text for a50
first_value(TEMP_SPACE_ALLOCATED)
(select distinct owner, table_name over (partition by
select sql_id,to_char (LAST_LOAD_TIME, 'dd-mon-yyyy hh24:mi:ss')
sql_id,sql_exec_id
from dba_tables order by sample_time rows 1 preceding),0)
LAST_LOAD_TIME, exact_matching_signature, SQL_TEXT from
DELTA_TEMP where ( table_name)
v$sqlarea where UPPER(sql_text) like '%DUMMY%' order by
from
in ( select object_name
UPPER(sql_text);
v$active_session_history
from gv$sql_plan
where where upper(sql_id) = upper('&sql_id') and object_name is
not null))sql_exec_start is not null
andSTALE_STATS='YES'
--and IS_SQLID_CURRENT='Y'
/ )
group by sql_id,SQL_EXEC_ID,sql_exec_start
PGA/TEMP ( current )
order by sql_id
)
SELECT sql_plan_hash_Value,
where sql_id = 'b4tmgwbcjawp5'sql_full_plan_hash_Value,
sql_adaptive_plan_resolved
order by sql_id, run_time_sec desc
,FETCH
COUNT(DISTINCT sql_exec_id),
FIRST 10 ROWS ONLY; COUNT(*)
FROM dba_hist_active_Sess_history
WITH snaps
WHERE sql_id = '4dszd9dysry0c'
GROUP AS (SELECT /*+ materialize */ sql_full_plan_hash_value,
BY sql_plan_hash_value,
dbid, SNAP_ID
sql_adaptive_plan_resolved
col sql_textFROM fordba_hist_snapshot
a60 s
/SELECT rows_processed "Total Rows Processed",
select WHERE (begin_interval_time BETWEEN sysdate-&1 AND
ROUND((SYSDATE
sysdate)) - TO_DATE(first_load_time, 'yyyy-mm-dd
SQL_ID,PLAN_HASH_VALUE,ELAPSED_TIME,PHYSICAL_READ_B
hh24:mi:ss')) * 24 * 60, 1) "Total Time (Min)",
select * from (
YTES,PHYSICAL_WRITE_BYTES,DISK_READS,DIRECT_WRITES,B
SELECT TRUNC(rows_processed
t.*, row_number () over /((SYSDATE
(orderfrom - TO_DATE(first_load_time,
by impact_secs desc ) seq#
UFFER_GETS,ROWS_PROCESSED
'yyyy-mm-dd hh24:mi:ss')) * 24 * 60)) v$sqlstats where
"Rows/Min",
FROM (
sql_id='&sql_id';
TRUNC(rows_processed
SELECT DISTINCT sql_id /((SYSDATE - TO_DATE(first_load_time,
'yyyy-mm-dd hh24:mi:ss'))
, execs executions* 24 * 60 * 60)) "Rows/Sec" ,
SUBSTR(sql_text, 1, 60) sql_text
, FIRST_VALUE (plan_hash_value) OVER (PARTITION BY
FROM
select
sql_id gv$sqlarea
sess_io.inst_id,
ORDER BY pln_avg DESC) worst_plan
WHERE SQL_ID='&SQL_ID'
sess_io.sid,, ROUND (MAX (pln_avg) OVER (PARTITION BY sql_id),
2)AND open_versions > 0
sesion.sql_id,
worst_plan_et_secs
select rows_processed
ANDsess_io.block_gets,
instance_number
, FIRST_VALUE > 0; (plan_hash_value) OVER (PARTITION BY
sess_io.consistent_gets,
inst_id,SESSION_ID,USER_ID,PROGRAM,sql_id,SQL_CHILD_NUMB
sql_id ORDER BY pln_avg ASC) best_plan
sess_io.physical_reads,
ER,sql_plan_hash_value,to_char
, ROUND (MIN (pln_avg) (sql_exec_start,
OVER (PARTITION 'dd-Mon-yyyy
BY sql_id), 2)
sess_io.block_changes,
hh24:mi:ss')
best_plan_et_secs sql_exec_start from
sess_io.consistent_changes
dba_hist_active_sess_history
, ROUND ( (MAX (pln_avg) where OVER (PARTITION BY sql_id) -
from gv$sess_io
MINsql_id='&sql_id';
(pln_avg) OVERsess_io, gv$session
(PARTITION sesion * execs) impact_secs
BY sql_id))
where sesion.sid = sess_io.sid and
, ROUND (MAX (pln_avg) OVER (PARTITION BY sql_id) /
sess_io.inst_id
MIN
select (pln_avg) = sesion.inst_id
OVER
sesion.sid,sql_text (PARTITION andBY sql_id),
from v$sqltext 2) v$session
sqltext, times_fastersesion
sesion.sql_id='&sql_id'
whereFROM (SELECT PARSING_SCHEMA_NAME
sesion.sql_hash_value = sqltext.hash_value and
and sesion.username
sesion.sql_address, sql_id is not null ;
= sqltext.address and sesion.username is not
null , plan_hash_value
, AVG (elapsed_time_delta / 1000000 / executions_delta)
order by sqltext.piece;
OVER (PARTITION BY sql_id, plan_hash_value) pln_avg
, SUM (executions_delta) OVER (PARTITION BY sql_id)
execs
FROM DBA_HIST_SQLSTAT h
WHERE sql_id='0dghnwz6zbud0' and (dbid, SNAP_ID) IN
(SELECT dbid, SNAP_ID FROM snaps)
AND NVL (h.executions_delta, 0) > 0)
)t
)
where seq# < 11
ORDER BY seq#
/
Wait Ratio

SELECT METRIC_NAME, VALUE


FROM V$SYSMETRIC
WHERE METRIC_NAME IN ('Database CPU Time Ratio',
set lines 750Wait
'Database pages 9999
Time Ratio') AND
col
INTSIZE_CSEC = for a35
OBJECT_NAME
select
(select * from (
max(INTSIZE_CSEC) from V$SYSMETRIC);
SELECT
A.inst_id,
A.CURRENT_OBJ#,
D.OBJECT_NAME,
A.SQL_ID,
select
D.OBJECT_TYPE,
event,
A.EVENT,
time_waited "time_waited(s)",
SUM(A.WAIT_TIME
case when time_waited + A.TIME_WAITED)
= 0 then TOTAL_WAIT_TIME
FROM 0
gV$ACTIVE_SESSION_HISTORY
else A,
DBA_OBJECTS
SELECT D 'ON CPU')
round(time_waited*100
NVL(a.event, / sum(time_waited)
AS event, Over(), 2)
WHERE
end "percentage"
COUNT(*) AS total_wait_time
A.CURRENT_OBJ#
from
FROM = D.OBJECT_ID
v$active_session_history a
GROUP
(
WHERE BY
a.sample_time > SYSDATE - 5/(24*60) -- 5 mins
A.inst_id,
GROUP select
BYevent, sum(time_waited) time_waited
a.event
A.CURRENT_OBJ#,
ORDER fromBY v$active_session_history
total_wait_time DESC;
D.OBJECT_NAME,
where sql_id = '&SQL_ID'
A.SQL_ID,
group by event
D.OBJECT_TYPE,
)
A.EVENT
order by
ORDER BY
time_waited desc;
TOTAL_WAIT_TIME DESC
)
where rownum<=20
/
" @?/rdbms/admin/utlxplp.sql
(or)
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY('','','+COST
+BYTES -PREDICATE'));

SELECT * FROM
TABLE(DBMS_XPLAN.DISPLAY_CURSOR('&sql_id',&childnumber,'A
LLSTATS LAST +PEEKED_BINDS +PROJECTION +ALIAS
+OUTLINE +PREDICATE +COST +BYTES'));

(OR)

select * from
table(dbms_xplan.display_cursor('&sql_id',&childnumber,'ADVANCED')
);

(OR)

set pagesize 0 echo off timing off linesize 1000 trimspool on trim on
long 2000000 longchunksize 2000000
select
DBMS_SQLTUNE.REPORT_SQL_MONITOR(
sql_id=>'&sql_id',
report_level=>'ALL',
type=>'TEXT')
from dual;

select spid,p.pid, s.sid, s.serial#, p.program from v$session s,


v$process p where paddr=addr and p.pid=30849 order by p.pid;
select s.sid, s.serial#, s.username,
to_char(s.logon_time,'DD-MON HH24:MI:SS') logon_time,
select spidoraclepid,
p.pid "host-pid",p.pid, s.sid, s.serial#,
p.spid "ServerPID", p.program,
s.process s.machine from
"ClientPID",
gv$session
s.program clientprogram, s.module, s.machine, s.osuser, order
s, gv$process p where paddr=addr and s.sid=&sid
by p.pid;
s.status, s.last_call_et
from gv$session s, gv$process p
where p.spid=nvl('&unix_process',' ')
and s.paddr=p.addr
order by s.sid
select sys_context ( 'USERENV' , 'SID' ) OwnSID from dual;
select sys_context('USERENV','SESSION_USER')
current_user,sys_context('USERENV','SESSION_SCHEMA')
current_schema from dual;

alter session set events 'immediate crash';


/ (SELECT DECODE (VALUE, 0, 1, VALUE)
FROM v$sesstat
WHERE STATISTIC# = 583 AND v$sesstat.SID =
v$session.sid),
2)
AS "Hard Parse, %",
(SELECT ROUND (VALUE / 1024 / 1024, 2)
select 'alter system kill session ' || '''' || sid || ',' || serial# ||',@'|| inst_id ||
FROM v$sesstat
'''' || ' immediate;' from gv$session where sid='&sid';
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 system STATISTIC# = 590
kill session AND v$sesstat.SID =
'''||sid||''','''||serial#||''',''@'||inst_id||'''
v$session.sid)
immediate; '
AS "Received
from gv$session wherefrom client, ininMB",
username ('SCHEMA1','SCHEMA2') and
(SELECT ROUND (VALUE / 1024 / 1024, 2)
logon_time < sysdate -1 and status='INACTIVE';
FROM v$sesstat
WHERE STATISTIC# = 589 AND v$sesstat.SID =
v$session.sid)
AS "Sent to client, in MB",
SID,
SERIAL#,
v$session.STATUS,
PROGRAM,
USER#,
ps -efUSERNAME,
| grep "oracleinstname (LOCAL=NO)"
COMMAND,
OWNERID,
OSUSER,
SELECT PROCESS,
a.sid, a.username, b.xidusn rollback_seg_no,
b.used_urecMACHINE, undo_records, b.used_ublk undo_blocks
FROMOBJECT_NAME
gv$session a, gv$transaction b
WHEREFROMa.saddr v$session
= b.ses_addr;
LEFT OUTER JOIN
DBA_OBJECTS
ON v$session.ROW_WAIT_OBJ# = dba_objects.object_ID
WHERE v$session.LOGON_TIME BETWEEN TRUNC (SYSDATE)
AND SYSDATE
AND v$session.sid = &sid;

SELECT o.inst_id,o.sid,
o.sql_text,
o.address,
o.hash_value,
o.user_name,
s.schemaname,
o.sql_id
FROM gv$open_cursor o, gv$session s
WHERE o.saddr = s.saddr AND o.sid = s.sid AND (O.SID = &sid)
and o.inst_id=s.inst_id;
ELSE 'WAITING'
CE_NAME,
END AS state,
CURRENT_UTILIZATION
CASE WHEN state != "CURRENT",MAX_UTILIZATION "MAX"
'WAITING' THEN 'On CPU / runqueue'
FROM WRH$_RESOURCE_LIMIT
ELSE event A, WRM$_SNAPSHOT B
WHERE ENDA.RESOURCE_NAME
AS sw_event LIKE '%session%'
AND A.SNAP_ID=B.SNAP_ID
FROM
ANDv$session
A.INSTANCE_NUMBER= B.INSTANCE_NUMBER
AND
WHERE((A.INSTANCE_NUMBER=1
ANDtypeB.BEGIN_INTERVAL_TIME
= 'USER' > (SELECT STARTUP_TIME FROM
GV$INSTANCE WHERE
AND status = 'ACTIVE' INSTANCE_NUMBER=1)) OR
(A.INSTANCE_NUMBER=2
GROUP BY AND B.BEGIN_INTERVAL_TIME >
(SELECT STARTUP_TIME FROM GV$INSTANCE
CASE WHEN state != 'WAITING' THEN 'WORKING' WHERE
INSTANCE_NUMBER=2)))
ELSE 'WAITING'
order by A.INSTANCE_NUMBER,A.SNAP_ID;
END,
SELECT
CASESQL_ID, SQL_FULLTEXT,
WHEN state != 'WAITING'PLAN_HASH_VALUE, PARSING_SCHEMA_NAME, ELAPSED_TIME FROM V$SQL WH
THEN 'On CPU / runqueue'
ELSE event
END
ORDER BY
1 DESC, 2 DESC
/

-- Purge explain plan from shared pool, must be done on each RAC
node
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 sql_text
from v$sqlarea
where address = (select sql_address from v$session where sid in
(select SID
from v$transaction,dba_rollback_segs,v$session
where SADDR=SES_ADDR and
XIDUSN=SEGMENT_ID and
flag=7811));

select xidusn, xidsqn from v$transaction;


column category format a10
column hint format a70 wrap word

break on plan_name skip 1 on signature skip 1 on opt_type skip 1 on


category skip 1 on plan_id skip 1

spool sql_profile_baseline_11g

declare
select
v_sql CLOB;
prf.plan_name,
beginprf.signature,
select sql_text into v_sql from dba_hist_sqltext where
decode(
sql_id='5273fz2cqkk80';
obj_type,
sys.dbms_sqldiag_internal.i_create_patch(
1,'Profile',
sql_text => v_sql,
2,'Baseline',
hint_text => 'DYNAMIC_SAMPLING(4)',
3,'Patch',
name 'Other'
=> '5273fz2cqkk80_patch');
end; ) opt_type,
/ prf.category,
prf.plan_id,
checkextractvalue(value(hnt),'.') hint
from
(
select
/*+ no_eliminate_oby */
so.name plan_name,
so.signature,
so.category,
so.obj_type,
select NAME,SIGNATURE ,STATUS,FORCE_MATCHING from dba_sql_
check so.plan_id,
sod.comp_data
from
sqlobj$ so,
sqlobj$data sod
select SQL_HANDLE,
where PLAN_NAME, ENABLED, ACCEPTED,
FIXED ,sql_textso.name from dba_sql_plan_baselines;
= '&m_plan_name'
and sod.signature = so.signature
and sod.category = so.category
select * fromand sod.obj_type = so.obj_type
table(dbms_xplan.display_sql_plan_baseline(plan_name=>'SQL_PLA
and sod.plan_id = so.plan_id
N_b7pnq6yp8da6a29d0d9b7'));
order by
All in one script signature, obj_type, plan_id
) prf,
table (
select
xmlsequence(
extract(xmltype(prf.comp_data),'/outline_data/hint')
)
Resolutionfrom normally, is to fix the execution plan in 11g by running
dual
variable
) x hnt
number
begin
;
:x :=
dbms_spm.load_plans_from_cursor_cache(
sql_id=>'&sql_id',
plan_hash_value=>&plan_hash,
fixed=>'YES');
end;
/
script.
PROMPT Explain Plan from AWR
and other_xml
REM
PROMPT is not null script is automatically executed after
The PRVTPOOL.PLB
================================
)
DBMSPOOL.SQL runs.
)
REM These scripts are not run by as part of standard database
d;
creation.
select * from table(dbms_xplan.display_awr('&sql_id', NULL, null,
SPO flush_cursor_&&sql_id..txt;
'ALLSTATS LAST'));
----------------------------------
PRO *** before flush ***
Taking
SELECT
PROMPT SQL HINTS
inst_id, from PLAN_TABLE
loaded_versions,
================================ invalidations, address, hash_value
----------------------------------
FROM gv$sqlarea
PROMPT Sql Profiles WHERE sql_id = '&&sql_id.' ORDER BY 1;
SELECT
PROMPT
BEGIN inst_id, child_number, plan_hash_value,
================================ executions,
SELECT
FOR i INregexp_replace(extractvalue(value(d),
is_shareable '/hint'),'''','''''') plan_hint
(SELECT address, hash_value
FROM
set from
linesgv$sql
1000 WHERE
pages sql_idsql_id
9999 = '&&sql_id.' ORDER BY 1, 2;
FROM gv$sqlarea WHERE = '&sql_id.')
BEGIN
col xmltable('/*/outline_data/hint'
name for a30
LOOP
FOR
col passing ( address,
i IN (SELECT
task_exec_name for a16 hash_value
SYS.DBMS_SHARED_POOL.PURGE(i.address||','||i.hash_value, 'C');
FROM
col gv$sqlarea
category forselect
a10 WHERE sql_id = '&&sql_id.')
END LOOP;
LOOP
col
END; created for a30 xmltype(other_xml) as xmlval
/ sql_text for from a150 plan_table
SYS.DBMS_SHARED_POOL.PURGE(i.address||','||i.hash_value,
col 'C');
END LOOP; where other_xml
col signature for 9999999999999999999999999 is not null
END; and plan_id = (select max(plan_id) from plan_table)
and rownum=1 as child , prof.name, prof.category,
/select sql.sql_id,sql.child_number
PRO *** after flush ) ***
prof.created,prof.task_exec_name,prof.FORCE_MATCHING,prof.statu
SELECT ) d;
inst_id,
s,prof.SIGNATURE loaded_versions, invalidations, address, hash_value
FROM
from gv$sqlarea WHERE sql_id = '&&sql_id.' ORDER BY 1;
SELECT inst_id, prof,
dba_sql_profiles child_number, plan_hash_value, executions,
----------------------------------
is_shareable
gv$sql sql
Taking
where SQL
FROM sql.sql_id
gv$sql HINTS
WHEREin from PROFILES
sql_id
('&sql_id') = '&&sql_id.' ORDER BY 1, 2;
----------------------------------
UNDEF sql_id;
-- and sql.child_number=child_number
SPO
-- andOFF; sql.force_matching_signature=prof.SIGNATURE
order by
select hint as outline_hints
created;
from (select p.name, p.signature, p.category, row_number()
over (partition by sd.signature, sd.category order by sd.signature)
row_num,
PROMPT extractValue(value(t),
================ '/hint') hint
from sqlobj$data
PROMPT sd, dba_sql_profiles p,
Sql Baselines
PROMPT table(xmlsequence(extract(xmltype(sd.comp_data),
================
'/outline_data/hint'))) t
where sd.obj_type = 1
coland p.signature =for
SQL_HANDLE sd.signature
a30
coland p.category
origin for a16 = sd.category
coland p.name likefor
last_modified ('&profile_name'))
a30
order by row_num;
col last_verified for a30

select sql_handle, plan_name, origin, created, last_modified,


last_verified,ENABLED,ACCEPTED,FIXED,REPRODUCED
from dba_sql_plan_baselines
where signature in (select force_matching_signature
from gv$sql
where sql_id='&sql_id'
and inst_id=&inst_id);

undef sid
undef sql_id
undef inst_id
spool off;

"
sample_minute,
and
round(avg(sub1.on_cpu),1) as cpu_avg,
stat_end.stat_name = stat_start.stat_name
round(avg(sub1.waiting),1) as wait_avg,
)
round(avg(sub1.active_sessions),1) as act_avg,
and
-- filter for the statistic we are interested in
round( (variance(sub1.active_sessions)/avg(sub1.active_sessions)),1)
--
as act_var_mean
stat_end.stat_name
column = 'DB time'
sample_hour format a16
from
and
select
( -- sub1: one row per second, the resolution of SAMPLE_TIME
-- join stat_start to snap on FK
to_char(round(sub1.sample_time, 'HH24'), 'YYYY-MM-DD HH24:MI')
select
as--sample_hour,
sample_id,
( stat_start.snap_id = snap.snap_id
round(avg(sub1.on_cpu),1) as cpu_avg,
sample_time,
and
round(avg(sub1.waiting),1) as wait_avg,
sum(decode(session_state, 'ON CPU', 1, 0)) as on_cpu,
stat_start.dbid = snap.dbid
round(avg(sub1.active_sessions),1) as act_avg,
sum(decode(session_state, 'WAITING', 1, 0)) as waiting,
and
count(*)
155 as active_sessions
set stat_start.instance_number
lines = snap.instance_number
round( (variance(sub1.active_sessions)/avg(sub1.active_sessions)),1)
col) from
execs for 999,999,999
as act_var_mean
col v$active_session_history
min_etime for 999,999.99
order
from by
where
colstat_start.snap_id
max_etime for 999,999.99
( -- sub1: one row per second, the resolution of SAMPLE_TIME
col sample_time
avg_etime > sysdate - (&minutes/1440)
for 999,999.999
; select
col group
avg_liobyfor 999,999,999.9
sample_id,
sample_id, for 999,999.9999
col norm_stddev
sample_time,
sample_time
col begin_interval_time for a30
sum(decode(session_state, 'ON CPU', 1, 0)) as on_cpu,
col) sub1
node for 99999
sum(decode(session_state, 'WAITING', 1, 0)) as waiting,
group on
break by plan_hash_value on startup_time skip 1
count(*) as active_sessions
round(sub1.sample_time,
select * from ( 'MI')
from
order by
select sql_id, sum(execs), min(avg_etime) min_etime, max(avg_etime)
dba_hist_active_sess_history
round(sub1.sample_time,
max_etime, 'MI')
stddev_etime/min(avg_etime) norm_stddev
where
;
from (
sample_time > sysdate - (&hours/24)
select sql_id, plan_hash_value, execs, avg_etime,
group by
stddev(avg_etime) over (partition by sql_id) stddev_etime
sample_id,
from (
sample_time
select sql_id, plan_hash_value,
) sub1
sum(nvl(executions_delta,0)) execs,
group by
(sum(elapsed_time_delta)/decode(sum(nvl(executions_delta,0)),0,1,su
round(sub1.sample_time, 'HH24')
m(executions_delta))/1000000) avg_etime
order by
--
round(sub1.sample_time, 'HH24')
sum((buffer_gets_delta/decode(nvl(buffer_gets_delta,0),0,1,executions
;
_delta))) avg_lio
from DBA_HIST_SQLSTAT S, DBA_HIST_SNAPSHOT SS
where ss.snap_id = S.snap_id
and ss.instance_number = S.instance_number
and executions_delta > 0
and elapsed_time_delta > 0
and s.snap_id > nvl('&earliest_snap_id',0)
group by sql_id, plan_hash_value
)
)
group by sql_id, stddev_etime
)
where norm_stddev > nvl(to_number('&min_stddev'),2)
and max_etime > nvl(to_number('&min_etime'),.1)
order by norm_stddev
/

https://orastory.wordpress.com/2009/12/29/plans-gone-awry-an-invashtigation/
select to_char(sample_time,'HH24:MI:SS') time, session_id sid
, session_serial# s#, user_id usr, session_state state
, time_waited waited, blocking_session blk_by,
blocking_session_status blk_stat
, sql_id, sql_child_number child_id, sql_plan_hash_value hash
, sql_plan_operation plan_op
, event, p1text, p1, p2text, p2, p3text p3, wait_class
, top_level_sql_id top_id, sql_exec_start ex_start
, plsql_entry_object_id pl_obj, plsql_entry_subprogram_id pl_prog
from dba_hist_active_sess_history
where sample_time between <start_time> and <end_time>
order by time desc;

select sql_plan_hash_value, COUNT(*), MIN(sql_exec_start),


MAX(sql_exec_start)
from dba_hist_active_sess_history
where sql_id = <sql_id>
group by sql_plan_hash_value;

select plan_hash_value, optimizer_cost, optimizer_mode,


optimizer_env_hash_value, buffer_gets_delta/executions_delta
from dba_hist_sqlstat
where sql_id = <sql_id>
and executions_delta > 0;

SELECT * FROM
TABLE(DBMS_XPLAN.DISPLAY_AWR(<sql_id>,<plan_hash_value>,<
db_id>,<format>));

select
id xms_id,
lpad(' ',depth*1,' ')||operation || ' ' || options xms_plan_step,
object_name xms_object_name,
cost xms_opt_cost,
cardinality xms_opt_card,
bytes xms_opt_bytes,
optimizer xms_optimizer
from
dba_hist_sql_plan
where
plan_hash_value = <plan_hash>
order by id
select
OBJ#,INTCOL#,SAVTIME,NULL_CNT,MINIMUM,MAXIMUM,DISTCNT
,DENSITY,LOWVAL,HIVAL,SAMPLE_DISTCNT,SAMPLE_SIZE
from WRI$_OPTSTAT_HISTHEAD_HISTORY
where OBJ#=925718 and INTCOL#=5
order by SAVTIME;

else
:plsql_call := '[No SQL profile to apply]';
:plsql_backout := '[No SQL profile to back out]';
end if;
end if;
end;
/

set term on
set feed off

select :recommendations "Recommendations:" from dual;

set heading off

prompt
prompt Execute the following PL/SQL block to apply the recommended
SQL profile:
select :plsql_call from dual;
prompt
prompt
prompt To back out this change, execute the following PL/SQL block:
select :plsql_backout from dual;
prompt
prompt

set term off


begin
dbms_lob.freetemporary(:recommendations);
end;
/

undefine 1
undefine sql_id
@sqlplus_settings.sql
set term on
set pages 500
set
set lines 1000
linesize 750pages 9999
column
column box format9999
sid format a30
column
column serial for 999999
spid format a10
column
column status
username format a15 a30
format
column
column username
program formatformata30
a10
column
column sql_text
os_user format
format a80
a20
column module format a30
col program
select for a30
b.sid,b.serial#,a.spid, substr(b.machine,1,30)
col SQL_EXEC_START
box,b.logon_time for a20
logon_date , to_char
(b.logon_time, 'hh24:mi:ss') logon_time,
SELECT * FROM
substr(b.username,1,30) username,
(SELECT status,inst_id,sid,SESSION_SERIAL#
substr(b.osuser,1,20) os_user,
as
substr(b.program,1,30) program,status,b.last_call_et
Serial,username,sql_id,SQL_PLAN_HASH_VALUE,
AS last_call_et_secs,b.sql_id
MODULE,program,
from v$session b,v$process a
whereTO_CHAR(sql_exec_start,'dd-mon-yyyy
hh24:mi:ss') AS sql_exec_start,
b.paddr = a.addr
<-- For cluster ROUND(elapsed_time/1000000)
and type='USER'
for standalone --> AS "Elapsed
order (s)",
by b.sid;
ROUND(cpu_time /1000000)
AS "CPU (s)",
substr(sql_text,1,30) sql_text
FROM gv$sql_monitor where module not like
overall --> '%emagent%'
set pagesize
<-- ONLY 0 echo off timing off linesize 1000
EXECUTING ORDER BY sql_exec_start desc
trimspool on trim on long 2000000 longchunksize )
2000000 WHERE rownum<=20;
select
set lines 1000 pages 9999
DBMS_SQLTUNE.REPORT_SQL_MONITOR(
SELECT SNAP_ID,report_id Rid,
column sid50000
formatlines
setsql_id=>'&sql_id',
pages 999932767
column
col serial for
report_level=>'ALL',
OPNAME for a10 999999 Missing statements in SQL Monitoring -->
EXTRACTVALUE(XMLType(report_summary),'/report
column
col status
type=>'TEXT')
SID form 9999 format a15
_repository_summary/sql/@sql_id') sql_id,
column
fromSERIAL
col username
dual; format a20
form 9999999
column
col sql_text for
PROGRAM format
a10 a80
EXTRACTVALUE(XMLType(report_summary),'/report
Completed (or)a33 ERROR you can rewrite the sql using below hint
col
col program
USERNAME for for a10
_repository_summary/sql/status') status
col
col SQL_EXEC_START
SQL_TEXT for a40 for a20
FROM dba_hist_reports TO_NUMBER(EXTRACTVALUE(XMLTyp
col START_TIME
WHERE component_name for a10 = 'sqlmonitor' and
SELECT
col * FROM
LAST_UPDATE_TIME for a10 e(report_summary),'/report_repository_su
(EXTRACTVALUE(XMLType(report_summary),'/repor
col (SELECTfor
TARGET status,inst_id,sid,SESSION_SERIAL#
a25 mmary/sql/stats/stat[@name="elapsed_ti
COLUMN sid FORMAT 99999
t_repository_summary/sql/@sql_id'))='&sql_id' and
as
col MESSAGE for a25 me"]'))
COLUMN serial# FORMAT 9999999
snap_id=&snap_id;
Serial,username,sql_id,SQL_PLAN_HASH_VALUE,p
alter session set nls_date_format = 'DD-MM-YYYY COLUMN machine FORMAT A30
rogram,
HH24:MI:SS'; COLUMN progress_pct FORMAT 99999999.00
SELECT TO_CHAR(sql_exec_start,'dd-mon-yyyy
inst_id,sid, serial#, sql_id, opname, COLUMN elapsed FORMAT A10
hh24:mi:ss')target,
username, AS sql_exec_start,
sofar, totalwork, COLUMN remaining FORMAT A10
ROUND(elapsed_time/1000000)
start_time,last_update_time,round(time_remaining/60
AS
,2) "Elapsed (s)",
"REMAIN MINS", round(elapsed_seconds/60,2) SELECT s.sid,
https://community.toadworld.com/platforms/oracle/w/wiki/11372.real-time-sql-monitoring-12c-part-ii
"ELAPSED ROUND(cpu_time
gv$sql_monitor MINS", /1000000) AS s.serial#,
"CPU (s)",
round((time_remaining+elapsed_seconds)/60,2) s.machine,
"TOTAL substr(sql_text,1,30)
MINS", sql_text ROUND(sl.elapsed_seconds/60) || ':' ||
FROM gv$sql_monitor where module not like
ROUND(SOFAR/TOTALWORK*100,2) MOD(sl.elapsed_seconds,60) elapsed,
'%emagent%'
"%_COMPLETE", and message
sid=&sid ROUND(sl.time_remaining/60) || ':' ||
ORDER BY
FROM gv$session_longops sql_exec_start desc MOD(sl.time_remaining,60) remaining,
WHERE ); OPNAME NOT LIKE 'RMAN%' AND ROUND(sl.sofar/sl.totalwork*100, 2)
OPNAME NOT LIKE '%aggregate%' AND progress_pct
TOTALWORK != 0 AND sofar<>totalwork AND FROM gv$session s,
time_remaining > 0 gv$session_longops sl
/ WHERE s.sid = sl.sid
AND s.serial# = sl.serial#;
Overall Waits Time model
col BI for 990
'999,999,990.000'), 18) cpu_secs,
COL
"I/O se.total_waits,
executions_total
instance_number
wait FOR
FOR999,999
9999 HEA HEA 'Execs|
'Inst'; COL end_time HEA 'End Time';
col BS for(s)",
9999 RPAD(LPAD (' ', 2*p.plan_DEPTH) ||
SELECTse.total_timeouts,
Total';
COL end_time
'DBA_HIST'HEA 'End Time'; COL plan_hash_value || ' ' || HEA 'Plan|Hash Value';
col ROUND(application_wait_time/1000000,3)
PI for 99
LPAD(TO_CHAR(ROUND(user_io_wait_time/1e6, AS 3), p.plan_operation p.plan_options,60,'.') ||
COL se.time_waited,
rows_per_exec
plan_hash_value
source,h.instance_number,h.SNAP_ID,
"Appli waitfor (s)", HEAHEA 'Rows Per Exec';
'Plan|Hash Value'; col NVL2(p.plan_object_owner||p.plan_object_name,
sql_id for a15
col status
'999,999,990.000'), a10 18) user_io_wait_secs,
COL
col se.average_wait,
et_secs_per_exec
sql_id for a15 HEA 'Elap Secs|Per Exec'; col
'(' || SQL_PROFILE for a30'.' || p.plan_object_name ||
col ROUND(concurrency_wait_time/1000000,3)
seconds_in_wait for 9990
LPAD(TO_CHAR(ROUND(cluster_wait_time/1e6, AS p.plan_object_owner||
COL se.max_wait,
cpu_secs_per_exec 18)HEA
EXTRACTVALUE(XMLType(s.report_summary),'/repo
col SQL_PROFILE
"Concurrency
col '999,999,990.000'),
PSID for a5 wait for
(s)", a30 'CPU Secs|Per Exec'; COL
') ', '') executions_total
|| FOR 999,999 HEA 'Execs|
3), cluster_wait_secs,
COL se.time_waited_micro
io_secs_per_exec HEA999,999
rt_repository_summary/sql/@sql_exec_start')
executions_total 'IO /1000000,3)
Secs|Per Exec';
select a.inst_id i, a.sid,FOR
ROUND(cluster_wait_time a.serial#, HEA"PSID",
b.qcsid 'Execs|
AS Total';
NVL2(p.plan_COST,'Cost:' || p.plan_COST,'') || ' '
FROM
COL v$session_event
cl_secs_per_exec se,
start_time,
Total';
"Cluster wait a.osuser,
a.username, (s)", a.machine,a.status, Exec';
HEA
LPAD(TO_CHAR(ROUND(application_wait_time/1e6, 'Clus Secs|Per COL
|| rows_per_exec HEA 'Rows |Per Exec';
COL v$session
ap_secs_per_exec
rows_per_exec s
ROUND(physical_read_bytes HEA HEA
'Rows 'App
|PerSecs|Per
Exec'; Exec';
/(1024*1024)) AS select
COL stat_name, value HEA 'Elap Secs|Per Exec';
et_secs_per_exec
NVL2(p.plan_bytes||p.plan_CARDINALITY,'(' ||
sql_id,
3), sql_child_number
'999,999,990.000'), 18)cld, event,
appl_wait_secs,a.last_call_et/60
WHERE s.sid
cc_secs_per_exec= se.sid HEA
EXTRACTVALUE(XMLType(s.report_summary),'/repo
COL et_secs_per_exec HEA 'Conc
'Elap Secs|Per Exec'; from V$SESS_TIME_MODEL
"Phys reads
"RunT (MB)",
(M)",seconds_in_wait/60 "Seconds Exec';
Secs|Per COL cpu_secs_per_exec HEA 'CPU Secs|Per Exec';
p.plan_bytes || ' bytes, ' || p.plan_CARDINALITY || '
AND
COL s.sid = &Session_ID
pl_secs_per_exec
cpu_secs_per_exec HEA
rt_repository_summary/sql/@sql_exec_id')
ROUND(physical_write_bytes HEA 'PLSQL
'CPU Secs|PerExec';
Secs|Per
/(1024*1024)) Exec';
AS where
COL
rows)','') sid|| =' ' &sid
io_secs_per_exec
|| HEA 'IO Secs|Per Exec';
Wait(M)",a.blocking_session
LPAD(TO_CHAR(ROUND(concurrency_wait_time/1e BS,a.blocking_instance
ORDER
COL
sql_exec_id,
"Phys BY se.time_waited
ja_secs_per_exec
io_secs_per_exec
writes (MB)", HEA DESC
'Java
'IO Secs|Per
Secs|Per Exec';
Exec'; order
COL by value desc;
cl_secs_per_exec
NVL2(p.plan_partition_start HEA 'Clus || Secs|Per Exec';
BI 3), '999,999,990.000'), 18) conc_wait_secs,
6,
/ buffer_gets
SELECT
COL h.instance_number,h.SNAP_ID,
cl_secs_per_exec HEA 'ClusAS Secs|Per Exec'; COL ap_secs_per_exec HEA 'App|| Secs|Per Exec';
fromh.sql_id,
gv$session a, gv$px_session
LPAD(TO_CHAR(ROUND(plsql_exec_time/1e6, b "Buffer gets", p.plan_partition_stop,'
column my_sid format PStart:' 999
COL TO_CHAR(CAST(s.begin_interval_time AS
Each'999,999,990.000'), 18) plsql_exec_secs, Exec';
where
3), ap_secs_per_exec
h.plan_hash_value,sql_profile,
Layer time spend
ROUND(plsql_exec_time/1000000,3) HEA 'App Secs|Per AS COL
Explain cc_secs_per_exec
Plan waiting
p.plan_partition_start
column my_ser formatsteps ' HEA
||99999
PStop:''Conc
|| Secs|Per Exec';
DATE),
COL
"Plsql 'DD-MM-YYYY
cc_secs_per_exec
h.executions_total,
exec (s)",
a.last_call_et >0 HH24:MI')
HEA 'Conc snap_time,
Secs|Per Exec'; COL pl_secs_per_exec
p.plan_partition_stop,'')
column my_state format||a30 HEA 'PLSQL Secs|Per AS
LPAD(TO_CHAR(ROUND(java_exec_time/1e6, SELECT ROUND(elapsed_time /1000000)
COL h.sql_id,sql_profile,
pl_secs_per_exec
ROUND(java_exec_time
--and a.status = 'ACTIVE' HEA
TO_CHAR(ROUND(h.rows_processed_total 'PLSQL Secs|PerAS
/1000000,3) Exec';
/ Exec';
column program
NVL2(p.plan_time,
column my_blkr format a30
p.plan_time || '(s)','') AS PLAN
3), '999,999,990.000'), 18) java_exec_secs, "Elapsed (s)", format 999
COL
"Java h.plan_hash_value,
ja_secs_per_exec
h.executions_total),
exec (s)" HEA 'Java
'999,999,999,999')
--andLPAD(TO_CHAR(io_cell_offload_eligible_bytes,
a.username in ('DELPHI') Secs|Per Exec'; COL
column
selectFROMja_secs_per_exec
username format
gv$sql_plan_monitor
to_char(a.sample_time,/1000000,3)HEA
a30 'Java
p Secs|Per
'HH24:MI:SS') Exec';
ROUND(cpu_time AS "CPU
COL h.executions_total,
DISK_READS_TOTAL
rows_per_exec,
FROM HEA 30) 'Disk|reads'; COL
column DISK_READS_TOTAL
sql_id format a13 HEA 'Disk|reads';
--and * gv$sql_monitor
Machine in
'999,999,999,999,999,999,990'),
SELECT WHERE
MY_TIME,a.session_id
(s)", sid=&sid MY_SID,a.session_serial#
COL TO_CHAR(ROUND(h.rows_processed_total
BUFFER_GETS_TOTAL
TO_CHAR(ROUND(h.elapsed_time_total
WHERE sid=&sid and inst_id=&inst_id;
('phxengsas03.ssd.star','phxengsas04.ssd.star') HEA 'Buffer|gets'; / / COL
SELECT BUFFER_GETS_TOTAL
ORDER BY p.plan_line_id, HEA
query_runs.*,
MY_SER,SQL_PLAN_HASH_VALUE,SQL_CHILD_ 'Buffer|gets';
p.plan_parent_id;
io_cell_offload_eligible_bytes,
FROM ROUND(queuing_time /1000000,3) AS
h.executions_total),
h.executions_total
and a.username / '999,999,999,999')
1e6,
is not null 3), '999,990.000') ROUND
NUMBER,(s)", ( (end_time - start_time) * 24, 2) AS
LPAD(TO_CHAR(io_interconnect_bytes,
(SELECT status, "Queuing
rows_per_exec,
select * from
et_secs_per_exec,
and event not( inSELECT
('Streams AQ: waiting select
duration_hrs* from ( SELECT
'999,999,999,999,999,999,990'),
--username, 30) for messages DECODE(a.session_state,
ROUND(application_wait_time/1000000,3) 'WAITING' ,a.event, AS
in theTO_CHAR(ROUND(h.elapsed_time_total
h.instance_number,h.SNAP_ID,
TO_CHAR(ROUND(h.cpu_time_total
v$sqlarea queue')
io_interconnect_bytes,
sql_id, ( ALL ) / / h.instance_number,h.SNAP_ID,
FROM
a.session_state)
ASH wait (s)", MY_STATE,a.xid, a.sql_id,
"Appli
h.executions_total
h.sql_id,sql_profile,
and a.inst_id / 1e6,
= b.inst_id (+) 3), '999,990.000') h.sql_id,sql_profile,
(SELECT u.username, MY_BLKR
a.blocking_session
CASE
sql_exec_id, ROUND(concurrency_wait_time/1000000,3) AS
et_secs_per_exec,
h.plan_hash_value,
cpu_secs_per_exec,
and a.sid = b.sid (+) h.plan_hash_value,
ash.program,
from gv$active_session_history a, dba_users u
WHEN io_cell_offload_eligible_bytes
TO_CHAR(sql_exec_start,'dd-mon-yyyy > "Concurrency wait (s)",
TO_CHAR(ROUND(h.cpu_time_total
orderh.executions_total,
TO_CHAR(ROUND(h.iowait_total
by last_call_et desc / / col
where execs
ash.sql_id, for 999,999,999
h.executions_total,
u.user_id = a.user_id
io_interconnect_bytes
hh24:mi:ss') THEN
AS sql_exec_start, ROUND(cluster_wait_time /1000000,3) AS
h.executions_total
/ / 1e6, 3), '999,990.000')
TO_CHAR(ROUND(h.rows_processed_total / col avg_etime for 999,999
TO_CHAR(ROUND(h.rows_processed_total
ASH.SQL_PLAN_HASH_VALUE
and a.sql_id AS /
LPAD(TO_CHAR(ROUND(
ROUND(elapsed_time/1000000) "Cluster wait =(s)", '&sql_id'
cpu_secs_per_exec,
h.executions_total),
io_secs_per_exec, '999,999,999,999') col avg_lio
h.executions_total),
plan_hash_value, for
andROUND(user_io_wait_time 999,999,999'999,999,999,999')
a.sample_time > SYSTIMESTAMP-(2/1440);
AS "Elapsed(io_cell_offload_eligible_bytes
(s)", - /1000000,3) AS
TO_CHAR(ROUND(h.iowait_total
rows_per_exec,
TO_CHAR(ROUND(h.clwait_total / colASH.SESSION_ID
avg_pio for 999,999,999
rows_per_exec, AS sess#,
io_interconnect_bytes)
v$sql ROUND(cpu_time
( sql_id ) * 100 /
/1000000) AS "User io wait (s)",
TO_CHAR(ROUND(h.elapsed_time_total
h.executions_total / 1e6, 3), '999,990.000') / colASH.SESSION_SERIAL#
begin_interval_time
TO_CHAR(ROUND(h.elapsed_time_total for a30 / AS
AS sess_ser,
io_cell_offload_eligible_bytes
"CPU (s)", ROUND(physical_read_bytes /(1024*1024))
io_secs_per_exec,
h.executions_total / 1e6, colCASTnode (MIN for 99999
cl_secs_per_exec,
, 2), '990.00')||'
buffer_gets, %',3),
8) '999,990.000')
END io_saved h.executions_total
"Phys reads (MB)", / 1e6,
(ASH.SAMPLE_TIME) 3), '999,990.000') AS DATE) AS
TO_CHAR(ROUND(h.clwait_total
et_secs_per_exec,
TO_CHAR(ROUND(h.apwait_total // break on plan_hash_value on startup_time skip 1
et_secs_per_exec,
start_time,
FROM gv$sql
ROUND(physical_read_bytes /(1024*1024)) AS ROUND(physical_write_bytes /(1024*1024)) AS
h.executions_total / 1e6,
TO_CHAR(ROUND(h.cpu_time_total 3), '999,990.000') / select ss.snap_id, ss.instance_number
TO_CHAR(ROUND(h.cpu_time_total
CAST (MAX (ash.sample_time) AS DATE) node,
/ AS
WHERE
"Phys sql_id
reads = '&sql_id'
(MB)", "Phys writes (MB)",
cl_secs_per_exec,
h.executions_total begin_interval_time, sql_id, plan_hash_value,
BY 1, 2; / 1e6, 3), '999,990.000')
ap_secs_per_exec,
ORDER ROUND(physical_write_bytes/(1024*1024)) AS h.executions_total
end_time
buffer_gets / 1e6, 3), '999,990.000')
AS "Buffer gets",
TO_CHAR(ROUND(h.apwait_total
cpu_secs_per_exec,
TO_CHAR(ROUND(h.ccwait_total // nvl(executions_delta,0)
cpu_secs_per_exec,
FROM dba_hist_active_sess_history execs, ash, AS
"Phys writes (MB)"
Elapsed/CPU/Read/Write MB Each ROUND(plsql_exec_time/1000000,3)
Layer time spend
TO_CHAR(ROUND(h.iowait_total
h.executions_total / 1e6, 3),where
'999,990.000') / (elapsed_time_delta/decode(nvl(executions_delta,0)
TO_CHAR(ROUND(h.iowait_total
dba_users u /
FROM gv$sql_monitor sql_id='&sql_id' "Plsql exec (s)",
ap_secs_per_exec,
h.executions_total
cc_secs_per_exec / 1e6, 3), '999,990.000') ,0,1,executions_delta))/1000000
h.executions_total
WHERE u.user_id / 1e6,
= 3), avg_etime,
'999,990.000')
ASH.USER_ID
and inst_id=&inst_id ROUND(java_exec_time /1000000,3) AS
FROMTO_CHAR(ROUND(h.ccwait_total
io_secs_per_exec,
dba_hist_sqlstat h, / (buffer_gets_delta/decode(nvl(buffer_gets_delta,0),0
io_secs_per_exec,
AND exec ash.sql_id
ORDER BY elapsed_time DESC "Java (s)" = lower(trim('&sql_id'))
h.executions_total
dba_hist_reports / 1e6,
TO_CHAR(ROUND(h.clwait_total s 3), '999,990.000') / ,1,executions_delta))
GROUPTO_CHAR(ROUND(h.clwait_total
BY u.username, avg_lio, /
) FROM gv$sql_monitor
cc_secs_per_exec,
h.executions_total
WHERE h.sql_id =/ '&sql_id'
1e6, 3), '999,990.000') ROUND(disk_reads_delta/DECODE(executions_delt
h.executions_total
ash.program, / 1e6, 3), '999,990.000')
WHERE rownum<=20; WHERE sql_id='&sql_id' and inst_id=&inst_id;
TO_CHAR(ROUND(h.plsexec_time_total
cl_secs_per_exec,
AND h.sql_id = / a,0,1, executions_delta),1) avg_pio,
cl_secs_per_exec,
ash.sql_id,
AWR data (More detailed)
h.executions_total / 1e6, 3), '999,990.000') SHORT Report
ROUND(rows_processed_delta/DECODE(execution
(EXTRACTVALUE(XMLType(s.report_summary),'/rep
TO_CHAR(ROUND(h.apwait_total / ASH.SQL_PLAN_HASH_VALUE,
TO_CHAR(ROUND(h.apwait_total /
pl_secs_per_exec,
h.executions_total / 1e6, 3), '999,990.000')
ort_repository_summary/sql/@sql_id')) s_delta,0,
h.executions_total
ASH.SESSION_ID,1, executions_delta), 1) avg_rows,
/ 1e6, 3), '999,990.000')
ANDTO_CHAR(ROUND(h.javexec_time_total
ap_secs_per_exec,
s.snap_id = h.snap_id / round(px_servers_execs_delta/decode(executions_
ap_secs_per_exec,
ASH.SESSION_SERIAL#
h.executions_total
AND s.dbid = h.dbid / 1e6, 3), '999,990.000')
TO_CHAR(ROUND(h.ccwait_total / delta,0,1, executions_delta), 1) avg_px /
TO_CHAR(ROUND(h.ccwait_total
) query_runs
ja_secs_per_exec
h.executions_total
AND s.instance_number / 1e6, 3),= '999,990.000')
h.instance_number from DBA_HIST_SQLSTAT
BY sql_id,/ 1e6, 3), S,
h.executions_total
ORDER '999,990.000')
FROM dba_hist_sqlstat
cc_secs_per_exec,
order by h,
source,snap_id,start_time ; DBA_HIST_SNAPSHOT
cc_secs_per_exec,
start_time; SS
dba_hist_snapshot s
TO_CHAR(ROUND(h.plsexec_time_total / where sql_id = nvl('&sql_id','4dqs2k5tynk61') /
TO_CHAR(ROUND(h.plsexec_time_total
WHERE h.sql_id =/ '&sql_id'
h.executions_total 1e6, 3), '999,990.000') and ss.snap_id = S.snap_id
h.executions_total / 1e6, 3), '999,990.000')
AND s.snap_id = h.snap_id
pl_secs_per_exec, and ss.instance_number = S.instance_number
pl_secs_per_exec,
AND s.dbid = h.dbid
TO_CHAR(ROUND(h.javexec_time_total / and executions_delta >0
TO_CHAR(ROUND(h.javexec_time_total /
AND s.instance_number
h.executions_total / 1e6, 3),= '999,990.000')
h.instance_number order by 1, 2, 3
h.executions_total / 1e6, 3), '999,990.000')
order by SNAP_ID;
ja_secs_per_exec, /ja_secs_per_exec,
TopDISK_READS_TOTAL
I/O Used ,BUFFER_GETS_TOTAL TopDISK_READS_TOTAL
DISK Read ,BUFFER_GETS_TOTAL
FROM dba_hist_sqlstat h FROM dba_hist_sqlstat h
WHERE WHERE
h.snap_id = 11706 h.snap_id = 11706
AND h.executions_total > 0 AND h.executions_total > 0
order by io_secs_per_exec desc ) where rownum order by DISK_READS_TOTAL desc ) where
<=50; rownum <=50;
sql_text bind_variable
greatest(PGA_ALLOCATED
instr(plan_table_output,
run_time))/60 '|', 1, 3)+2, - (
set lines 750 run_time_MIN,
pages 9999
first_value(PGA_ALLOCATED)
(instr(plan_table_output,
READ_IO_BYTES, '|', 1, over (partition by
4)- select
select sql_text from gv$sqlarea where sql_id =
sql_id,sql_exec_id
instr(plan_table_output,
PGA_ALLOCATED '|', order by sample_time
1, 3)-2)), ' ')
PGA_ALLOCATED_BYTES, rows 1 SESSION_ID,SESSION_SERIAL#,sample_id,SQL_I
'&SQL_ID';
preceding),0)
fromTEMP_ALLOCATED
( DELTA_PGA, D,SAMPLE_TIME,IS_SQLID_CURRENT,SQL_CHIL
greatest(TEMP_SPACE_ALLOCATED
SELECT plan_table_output
TEMP_ALLOCATED_BYTES - D_NUMBER,PGA_ALLOCATED,
first_value(TEMP_SPACE_ALLOCATED)
FROM
from ( over greatest(PGA_ALLOCATED -
column sql_text format a800
(partition
select by sql_id,sql_exec_id order by sample_time first_value(PGA_ALLOCATED) over (partition by
TABLE(DBMS_XPLAN.DISPLAY_CURSOR('&sql_id',
rows
null, 1 preceding),0) DELTA_TEMP
'BASIC'))
sql_id, SESSION_ID,SESSION_SERIAL# order by
SELECT sql_text col VALUE_STRING for a50
UNIONfrom ALL
max(sample_time - sql_exec_start) run_time, sample_time rows 1 preceding),0)/power(1024,2)
FROM gv$sql_monitor where SELECT
dba_hist_active_sess_history
SELECT * FROM and
max(sample_time) end_time, "DELTA_PGA_MB"
status='EXECUTING' module not like '%emagent NAME,POSITION,DATATYPE_STRING,VALUE_ST
where
TABLE(dbms_xplan.display_awr('&sql_id',
sql_exec_start starting_time, null, null, from
%' sample_time >= to_date ('2013/04/16 RING FROM gv$sql_bind_capture WHERE
'ALL')) sum(DELTA_READ_IO_BYTES) v$active_session_history
and sql_text not like '%BEGIN%'; sql_id='&sql_id';
00:00:00','YYYY/MM/DD
)
READ_IO_BYTES, HH24:MI:SS') where
where and sample_time
plan_table_output < to_date
sum(DELTA_PGA) PGA_ALLOCATED,like ('2013/04/16
'%INDEX%' IS_SQLID_CURRENT='Y'
03:10:00','YYYY/MM/DD
) sum(DELTA_TEMP)HH24:MI:SS') TEMP_ALLOCATED and sample_time > sysdate-&seconds/86400
ORDER and
fromBYsql_exec_start is not nullindex_name
owner, table_name, order by 1,2,3,4
/ and
( IS_SQLID_CURRENT='Y' )
) group
PGA/TEMP select sql_id,
( History ) PGA by sql_id
groupsample_time,
by sql_id,SQL_EXEC_ID,sql_exec_start having sum(DELTA_PGA_MB) > 0
ordersql_exec_start,
by sql_id )
) DELTA_READ_IO_BYTES, where rank < (&top+1)
wheresql_exec_id,
sql_id = 'btvk5dzpdmadh' order by rank
select s.sid, s.serial#, p.spid, s.username,
ordergreatest(PGA_ALLOCATED
by sql_id, run_time_sec desc; - /
s.program,
first_value(PGA_ALLOCATED) over (partition by t.xidusn, t.used_ublk, t.used_urec, sa.sql_text from
sql_id,sql_exec_id order by sample_time rows 1 v$process p,v$session s, v$sqlarea sa,
preceding),0) DELTA_PGA, v$transaction t
greatest(TEMP_SPACE_ALLOCATED - where s.paddr=p.addr
http://blog.go-faster.co.uk/2016/11/ash-analysis-detecting-and-profiling.html
first_value(TEMP_SPACE_ALLOCATED) over and s.taddr=t.addr
(partition by sql_id,sql_exec_id order by sample_time and s.sql_address=sa.address(+)
rows
select1sql_text,rows_processed
preceding),0) DELTA_TEMP from v$sql and s.sql_hash_value=sa.hash_value(+)
from
where USERS_EXECUTING>0; order by s.sid
dba_hist_active_sess_history /
where
sample_time >= trunc(sysdate)
--and sample_time < to_date ('2013/04/16
03:10:00','YYYY/MM/DD HH24:MI:SS')
and sql_exec_start is not null
selectand sess_io.inst_id,
IS_SQLID_CURRENT='Y'
sess_io.sid,
)
group sess_io.block_gets,
by sql_id,SQL_EXEC_ID,sql_exec_start
order sess_io.consistent_gets,
by sql_id
) sess_io.physical_reads,
where sess_io.block_changes,
sql_id = '&sql_id'
ordersess_io.consistent_changes
by sql_id, run_time_MIN desc;
from gv$sess_io sess_io, gv$session sesion
where sesion.sid = sess_io.sid and
sess_io.inst_id = sesion.inst_id
and sesion.username
select a.sid,b.sql_fulltextisfrom not null ;
V$Session a,
V$SQLAREA b where a.sql_id=b.sql_id and
a.status='ACTIVE';

http://www.artoftuning.net/sql-plan-comparison/
SELECT WAIT_CLASS, SELECT wait_class time_cat, ROUND((time_secs),
TOTAL_WAITS, 2) time_secs,
round(100 * (TOTAL_WAITS / SUM_WAITS),2) ROUND((time_secs) * 100 / SUM(time_secs)
PCT_TOTWAITS, OVER (), 2) pct
ROUND((TIME_WAITED / 100),2) FROM (SELECT wait_class wait_class,
TOT_TIME_WAITED, SUM(time_waited_micro) / 1000000
SET lines 750
round(100 pages 10000 / SUM_TIME),2)
* (TIME_WAITED time_secs
COLUMN
PCT_TIMEwait_class format a30 FROM gv$system_event
COLUMN
FROM event format a60 WHERE wait_class <> 'Idle' AND time_waited >
COLUMN total_waits format 999999
(select WAIT_CLASS, 0
COLUMN
TOTAL_WAITS,total_us%format
Wait Percentage (Only 999999999 WaitGROUP
wait events-NO CPU) PercentageBY wait_class
% (Only wait events-WITH CPU)
COLUMN
TIME_WAITED pct_time format 99.99 SELECTUNIONevent, total_waits,
COLUMN avg_us format 999999.99
FROM V$SYSTEM_WAIT_CLASS ROUND'CPU',
SELECT (time_waited_micro / 1000000)
ROUND((SUM(VALUE) / AS
SET
WHERE echoWAIT_CLASS
on != 'Idle'), time_waited_secs,
1000000), 2) time_secs
(select sum(TOTAL_WAITS) SUM_WAITS, ROUND
FROM (time_waited_micro * 100 /
gv$sys_time_model
SELECT wait_class,SUM_TIME
sum(TIME_WAITED) event, total_waits AS waits,
WHERESUM stat_name
(time_waited_micro) OVERcpu
IN ('background (),2)time',
AS
from V$SYSTEM_WAIT_CLASS / 1000) AS
ROUND (time_waited_micro pct_time
'DB CPU'))
total_ms,
where WAIT_CLASS != 'Idle') FROMBY
ORDER (SELECT
time_secs event, total_waits,
DESC;
ORDER ROUND (time_waited_micro
BY PCT_TIME DESC; * 100 / SUM
time_waited_micro
(time_waited_micro) OVER (), FROM v$system_event
2 WHERE wait_class <> 'Idle'
) AS pct_time, UNION
select
set lines
ROUND ((time_waited_micro / total_waits) / 750 pages
SELECT 9999 NULL, VALUE
stat_name,
1000, 2) AS avg_ms event,
select * FROM
from ( v$sys_time_model
FROM v$system_event time_waited
select WHERE"time_waited(s)",
stat_name IN ('DB CPU',
WHERE wait_class <> 'Idle' case whencpu
WAIT_CLASS
'background time_waited
,time')) = 0 then
ORDER BY time_waited_micro DESC; ORDER 0 BY 3 DESC;
EVENT,
else
count(sample_time) as EST_SECS_IN_WAIT
SELECT NVL(a.event, 'ON CPU') AS event, fromround(time_waited*100
v$active_session_history / sum(time_waited)
COUNT(*) AS total_wait_time Over(), 2)
where sample_time between sysdate - interval '1'
FROM v$active_session_history a hourend "percentage"
and sysdate
WHERE a.sample_time > SYSDATE - 60/2880 -- 30 from
group by WAIT_CLASS,EVENT
mins ( by count(sample_time) desc
order
GROUP BY a.event ) select event, sum(time_waited) time_waited
ORDER BY total_wait_time DESC; wherefromrownumdba_hist_active_sess_history
<6;
where sql_id = '&SQL_ID'
group by event
<-- shared pool (current) )
order by
From AWR --> time_waited desc;
select expl.*
from
gv$sql sql, v$session ses,
SELECT * FROM
TABLE(dbms_xplan.display_cursor(sql.sql_id,
TABLE(DBMS_XPLAN.DISPLAY('','','ALLSTATS
sql.child_number,format=>'typical +predicate')) expl
LAST +OUTLINE +PEEKED_BINDS +PROJECTION
where ses.sql_address = sql.address and ses.sid
+ALIAS +PREDICATE +COST +BYTES'));
= &&1
and sql.optimizer_cost is not null
/

select * from
table(dbms_xplan.display_awr('&sql_id', null, null,
'ALLSTATS LAST'));

SELECT * FROM
table(DBMS_XPLAN.DISPLAY_AWR('&sql_id',&plan
_hash_value));

<-- shared pool (current) SELECT * FROM


TABLE(DBMS_XPLAN.display_sql_plan_baseline(pl
From AWR --> an_name=>'SQL_PLAN_agz791au8s6jg30a4b3a6'))
;

SELECT tf.* FROM DBA_HIST_SQLTEXT ht, table


(DBMS_XPLAN.DISPLAY_AWR(ht.sql_id,null,
null, 'ALL' )) tf
WHERE ht.sql_id='&sql_id';

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


fg_pid,
vp.spid bg_pid
from v$session vs, v$process vp
<-- Killing a session ( Good Query ) where vs.paddr = vp.addr;

select sys_context('USERENV', 'IP_ADDRESS')


select distinct sid OwnSID from v$mystat; from dual;
begin
for x in (select
SID,Serial#,status,last_call_et,username from
v$session
where type='USER'
and status='INACTIVE'
and username = 'TESTER'
and last_call_et > 1200
) loop
select ' alter system kill session '''||sid||','||serial#||',@'|| execute 'Alter System Kill Session '''|| x.Sid
inst_id||''' immediate; ' -- 4 hours || ',' || x.Serial# || '''';
from gv$session where username in end loop;
('SCHEMA1','SCHEMA2','SCHEMA3') and end;
status='INACTIVE' and last_call_et > 4*60*60; /

for i in `ps -ef |grep "oracledb10g1 (LOCAL=NO)" |


grep -v grep | awk '{print $2}'`
Then kill the old sessions using kill -9 spid do
kill -9 `ps -ef|grep LOCAL=NO|grep oratst1|awk '{print echo kill -9 $i
$2}'` done

SELECT o.sid,
o.sql_text,
o.address,
o.hash_value,
o.user_name,
s.schemaname,
o.sql_id
FROM v$open_cursor o, v$session s
WHERE o.saddr = s.saddr AND o.sid = s.sid AND
(O.SID = &sid)
PARSING_SCHEMA_NAME, ELAPSED_TIME FROM V$SQL WHERE UPPER(PARSING_SCHEMA_NAME) ='SYS' ORDER BY ELAPSE

https://asktom.oracle.com/pls/asktom/f?p=100:11:::::P11_QUESTION_ID:7143624535091

select t.inst_id
,s.sid
,s.serial#
,s.username
,s.machine
,s.status
,s.lockwait If it returns a value, it means there is a pending
,t.used_ublk transaction.
,t.used_urec
,t.start_time Here is the query:
from gv$transaction t
inner join gv$session s on t.addr = s.taddr; select dbms_transaction.step_id from dual;
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 for
col name => a30
'PATCH',
FORCE_MATCH for
col task_exec_name => a16
TRUE,
IS_PATCH =>
col category for a10 TRUE);
DBMS_LOB.FREETEMPORARY(sql_txt);
col created for a30
coldbms_output.put_line(output);
sql_text for a150
colEND;
signature for 9999999999999999999999999
https://avdeo.com/2012/12/14/oracle-sql-patch-i/ /
select sql.sql_id,sql.child_number as child ,
ENABLE/DISABLE/DROP prof.name,
sql Profilesprof.category,
for a sql_id prof.created,
prof.task_exec_name,prof.FORCE_MATCHING,
EXEC prof.status, prof.SIGNATURE,prof.SQL_TEXT
DBMS_SQLTUNE.ALTER_SQL_PROFILE('coe_5273 from
fz2cqkk80_3455548535','STATUS','DISABLED'); dba_sql_profiles prof,
gv$sql sql
exec where sql.sql_id in ('&sql_id')
dbms_sqltune.drop_sql_profile('coe_5273fz2cqkk80_ order by
3455548535'); created;
Drop load from cursor
set serveroutput on
DECLARE
i NATURAL;
BEGIN
i :=
SELECT chr(9)||chr(9)||''''|| variable chr(9)||chr(9)||''''||
SELECT sqlid number;
dbms_spm.drop_sql_plan_baseline('SQL_b3d69637a
regexp_replace(extractvalue(value(d), execute :sqlid
regexp_replace(extractvalue(value(d),
a86a8ca');
'/hint'),'''','''''')||''',' :=DBMS_SPM.LOAD_PLANS_FROM_CURSOR_C
'/hint'),'''','''''')||''','
dbms_output.put_line(i);
from ACHE(sql_id=>'5qbbnv0abm2vx',
from
END;
xmltable('/*/outline_data/hint' PLAN_HASH_VALUE=>
xmltable('/*/outline_data/hint' 4197102931,
/passing ( SQL_HANDLE
passing ( => 'SQL_d3318f33dfac7bc2');
Taking
select SQL HINTS from memory Taking
select SQL HINTS from AWR
xmltype(other_xml) as xmlval xmltype(other_xml) as xmlval
from from
v$sql_plan -- v$sql_plan
To see the hints from sql_profile
where dba_hist_sql_plan
select
sql_idhint
like from (
nvl('&sql_id',sql_id) where
select s.sql_id, sd.obj_type,
and child_number = &child_no sql_id like nvl('&sql_id',sql_id)
row_number()
and other_xmlover (partition
is not null by sd.signature, and other_xml is not null
sd.category
) order by sd.signature) row_num, )
extractValue(value(t),
) '/hint') hint )
from
d; sqlobj$data sd, v$sql s, d;
table(xmlsequence(extract(xmltype(sd.comp_data),
'/outline_data/hint'))) t
where sd.obj_type = 1
and s.exact_matching_signature = sd.signature
and s.sql_id = '&sql_id')
order by row_num
/ http://intermediatesql.com/oracle/what-are-sql-profiles-and-why-do-we-
http://expertoracle.com/2015/07/08/flush-bad-sql-plan-from-shared-pool/
AGE,0)) "16",
max(decode(to_char(END_TIME,'HH24'),'17',AVER
AGE,0)) "17",
max(decode(to_char(END_TIME,'HH24'),'18',AVER
AGE,0)) "18",
max(decode(to_char(END_TIME,'HH24'),'19',AVER
AGE,0)) "19",
max(decode(to_char(END_TIME,'HH24'),'20',AVER
AGE,0)) "20",
set pages 100 max(decode(to_char(END_TIME,'HH24'),'21',AVER
select INSTANCE_NUMBER, AGE,0)) "21",
SUM(value), max(decode(to_char(END_TIME,'HH24'),'22',AVER
to_char(trunc(end_time,’HH’),’dd-mm-yyyy hh24:mi’) AGE,0)) "22",
as sample_time max(decode(to_char(END_TIME,'HH24'),'23',AVER
from dba_hist_sysmetric_history AGE,0)) "23"
where metric_name=’Average Active Sessions’ from DBA_HIST_SYSMETRIC_SUMMARY
and end_time between sysdate -1 and sysdate where metric_name='Average Active Sessions' and
group by trunc(end_time,’HH’), INSTANCE_NUMBER INSTANCE_NUMBER = &inst_num
order by 3,1; group by to_char(END_TIME,'DD-Mon');

http://kerryosborne.oracle-guy.com/2008/10/unstable-plans/

y-an-invashtigation/
https://yasu-khan.github.io/Forensic-investigation-sql-performance

http://www.williamrobertson.net/documents/automated-sql-tuning-advice-sqlid.html
Test it before using
Name , program path 'program'
..... ......................................: '||
, plan_hash path 'plan_hash' , px_servers_allocated path
s.SCHEMANAME,
, is_cross_instance path 'px_servers_allocated'
'Program ...............................................:
'is_cross_instance' , duration path
'||s.program,
, dop.................................................:
path 'dop' 'stats/stat[@name="duration"]'
'Module
, instances path 'instances' , elapsed_time path
'|| s.module,
, px_servers_requested path 'stats/stat[@name="elapsed_time"]'
'Action .................................................: '||
'px_servers_requested' , cpu_time path
s.action,
, px_servers_allocated path 'stats/stat[@name="cpu_time"]'
'Terminal ...............................................: '||
'px_servers_allocated' , user_io_wait_time path
s.terminal,
, duration path 'stats/stat[@name="user_io_wait_time"]'
'Client
'stats/stat[@name="duration"]' , application_wait_time path
Machine .........................................: '||
, elapsed_time path 'stats/stat[@name="application_wait_tim
s.machine,
'stats/stat[@name="elapsed_time"]' e"]'
'LAST_CALL_ET ......................................
, cpu_time path , concurrency_wait_time path https://ma
.....: '||s.last_call_et,
'stats/stat[@name="cpu_time"]' 'stats/stat[@name="concurrency_wait_ti uro-
'S.LAST_CALL_ET/3600 ..........................
, user_io_wait_time me"]' pagano.c
..........: '||s.last_call_et/3600path
'stats/stat[@name="user_io_wait_time"]' , cluster_wait_time path SELECT om/2015/
from v$session s, v$process p
, application_wait_time 'stats/stat[@name="cluster_wait_time"]' report_id, 05/04/hist
where p.addr=s.paddr and path
'stats/stat[@name="application_wait_time , plsql_exec_time path key1 orical-sql-
s.sid=nvl('&sid',s.sid) and
"]' 'stats/stat[@name="plsql_exec_time"]' sql_id, monitor-
p.spid=nvl('&spid',p.spid) and
, concurrency_wait_time path , other_wait_time path key2 reports-
nvl(s.process,-1) =
'stats/stat[@name="concurrency_wait_tim 'stats/stat[@name="other_wait_time"]' sql_exec in-12c/
nvl('&ClientPid',nvl(s.process,-1)); http://allappsdba.blogspot.com/2012/04/queries-to-get-session-information.html
e"]' , buffer_gets path _id, key3
, cluster_wait_time path 'stats/stat[@name="buffer_gets"]' sql_exec http://ww
'stats/stat[@name="cluster_wait_time"]' , read_reqs path _start w.toadwor
, plsql_exec_time path 'stats/stat[@name="read_reqs"]' FROM ld.com/pl
'stats/stat[@name="plsql_exec_time"]' , read_bytes path dba_hist_ atforms/or
, other_wait_time path 'stats/stat[@name="read_bytes"]' reports acle/w/wi
'stats/stat[@name="other_wait_time"]' ) x1 WHERE ki/11372.r
, buffer_gets path where x1.elapsed_time/1000000 > 200 compone eal-time-
ALTER SESSION SET
'stats/stat[@name="buffer_gets"]' and t.COMPONENT_NAME = nt_name sql-
"_SQLMON_MAX_PLAN"=4020;
, read_reqs path 'sqlmonitor' = monitorin
ALTER SESSION SET
'stats/stat[@name="read_reqs"]' order by 5 'sqlmonito g-12c-
"_SQLMON_MAX_PLANLINES"=4000;
, read_bytes path / r'; part-ii
'stats/stat[@name="read_bytes"]'
) x1
where x1.elapsed_time/1000000 > 200
and t.COMPONENT_NAME =
'sqlmonitor'
order by 5
/

SELECT SID, SERIAL#, OPNAME, column username format a20


TARGET, SOFAR, TOTALWORK, UNITS, Select s.username, s.Sid, s.serial#,
TO_CHAR(START_TIME,'DD/MON/YYYY S.Sql_Id, round((Sysdate-
HH24:MI:SS') START_TIME, Sql_Exec_Start)*24*60*60/60,0)
TO_CHAR(LAST_UPDATE_TIME,'DD/M MINUTES, Sql_Text
ON/YYYY HH24:MI:SS') From V$Session S, V$Sqltext T
LAST_UPDATE_TIME, Where S.Sql_Id = T.Sql_Id
TIME_REMAINING, And Sql_Exec_Start Is Not Null And
ELAPSED_SECONDS, MESSAGE, Piece = 0
USERNAME And (Sysdate-Sql_Exec_Start)*24*60 >
FROM V$SESSION_LONGOPS 1
WHERE TIME_REMAINING != 0; order by MINUTES desc
/ ;
Stats
(ss.elapsed_time_delta/1000000)/DECO when begin_interval_time >= sql_id,
tions,0),0,1,executions)
,select st.parsing_schema_name
DE(ss.executions_delta,0,1,ss.executions avg_px, to_date('14-nov-2017 1100','dd-mon-
,to_char(sql_exec_start,'dd.mm.yyyy
_delta) optimizer_cost cost,
st.plan_hash_value
ela_per_exec, yyyy hh24mi') then s.executions_total sql_plan_
,LAST_LOAD_TIME
hh24:mi:ss') SUM(st.fetches_delta)
(ss.cpu_time_delta astimestamp,
/ fch else 0 hash_val
,parsing_schema_name
SQL_EXEC_START, SUM(rows_processed_delta) rws
1000000)/DECODE(ss.executions_delta, end) - ue,
,--FIRST_LOAD_TIME,
0,1,ss.executions_delta)SUM(executions_delta)
max(sample_time) - cpu_per_exec, execs sum(case
LAST_LOAD_TIME,
,SQL_EXEC_START ss.buffer_gets_delta as when begin_interval_time < to_date('14- event,sql
LAST_ACTIVE_TIME,
duration, select vsn.name, vst.value
ROUND(SUM(elapsed_time_delta)/1000/ SQL_PROFILE
/DECODE(ss.executions_delta,0,1,ss.exe nov-2017 1100','dd-mon-yyyy hh24mi') _exec_id,
from
1000) v$sesstat vst, v$statname vsn
gv$sqlarea_plan_hash
sql_exec_id,
elp
cutions_delta) lio_per_exec, then s.executions_total
,where vsn.statistic#
sql_id = vst.statistic#
= nvl(trim('&sql_id'),sql_id)
sql_plan_hash_value,
ss.disk_reads_delta else 0 sql_exec
and
UNION vst.value
module, != 0
ROUND(SUM(elapsed_time_delta)/1000/
/DECODE(ss.executions_delta,0,1,ss.exe end)) difference _start,
and
SELECT vst.sid = &sid
'dba_hist_sql_plan'
1000/NVL(NULLIF(SUM(executions_delta
cutions_delta) action, pio_per_exec source, null from
orderround(max(temp_space_allocated)
INST_ID,
),0),1),2) by vst.value;
t1.sql_id
elpe a150 sql_id, s, /
FROM
col PLAN dba_hist_snapshot
FOR dba_hist_sqlstat s, current_o
,t1.plan_hash_value
1024
SELECT / 1024
dba_hist_sqlstat ss/ 1024, plan_hash_value,
3) as max_temp_gb, dba_hist_snapshot sn bj#,
t2.avg_et_secs
ROUND(SUM(cpu_time_delta)/1000/100 avg_et_secs,
round(max(pga_allocated) t2.avg_px, where
WHERE RPAD('(' ss.dbid
|| p.plan_line_ID = s.dbid || ' ' || /
t1.cost
0)
1024
AND ss.instance_number cost, /t1.timestamp
/ cpu
1024 1024, 3) as max_pga_gb, timestamp,
NVL(p.plan_parent_id,'0') ||= ')',8) || '|' || sn.begin_interval_time between sql_plan_
NULL
,s.instance_number parsing_schema_name gets
SUM(buffer_gets_delta)
max(px_used) to_date('05-nov-2017 0001','dd-mon- line_id,
RPAD(LPAD (' ', 2*p.plan_DEPTH) ||
,FROM
ANDas
p.plan_operation
dba_hist_sql_plan
max_px_used
ss.snap_id || ' ' ||= s.snap_id
t1, yyyy hh24mi')
from(ss.sql_id
ROUND(SUM(iowait_delta)/1000/1000)
(select sql_exec_start,
https://blog.yannickjaquier.com/oracle/real-time-sql-monitoring.html
AND
p.plan_options,60,'.') =|| sql_exec_id, and sql_plan_
io
sql_plan_hash_value, SELECT sql_id,
NVL2(p.plan_object_owner||action,
nvl('&sql_id','4dqs2k5tynk61') module, to_date('05-nov-2017 2359','dd-mon- operation,
,plan_hash_value,
sample_id,
/* and ss.executions_delta
p.plan_object_name, '(' || > 0 */ yyyy hh24mi')
--round(SUM(elapsed_time_total)/decode
ROUND(SUM(clwait_delta)/1000/1000)
/* sum(temp_space_allocated)
check executions_delta
p.plan_object_owner||
AWR '.' || for 1 , if it is 0 and Time based sql_plan_
(SUM(executions_total),0,1,SUM(executi
justcl asconsider
temp_space_allocated,
only rows
p.plan_object_name || ')proceesed
', '') || and sn.snap_id=s.snap_id options
,ons_total))/1e6,2)
calculate total execution
NVL2(p.plan_COST,'Cost:'
avg_et_secs
sum(pga_allocated) time =||sum group by )
ROUND(SUM(ccwait_delta)/1000/1000)
as pga_allocated,
( executions_delta
p.plan_COST,'') || ' 1' ||+ executions_delta 0 s.sql_id order by
round(SUM(elapsed_time_total)/decode(
) */ cc count(distinct session_serial#) - order by count_1
NVL2(p.plan_bytes||
SUM(executions_total),0,1,SUM(executio
,1
ORDER as px_used,BY s.snap_id; || p.plan_bytes || difference desc; desc;
p.plan_CARDINALITY,'('
ns_total))/1e6/
ROUND(SUM(apwait_delta)/1000/1000) select x.*, (SELECT sql_text from
' bytes, ' ||sample_time p.plan_CARDINALITY || '
rows)','') apfrom || ' dba_hist_active_sess_history
' || dba_hist_sqltext t where t.sql_id =
,decode(SUM(px_servers_execs_total),0,
where sql_id =
NVL2(p.plan_partition_start || '&&1' x.sql_id and rownum = 1) txt
1,SUM(px_servers_execs_total))/decode(
ROUND(SUM(plsexec_time_delta)/1000/
and snap_id between &2 and from (
p.plan_partition_stop,' PStart:' ||
SUM(executions_total),0,1,SUM(executio
1000)
nvl('&&3', pl &&2) SELECT snap_id
p.plan_partition_start || ' PStop:' ||
,ns_total)),2) avg_et_secs,
ROUND(SUM(disk_reads_delta))
and sql_exec_id
p.plan_partition_stop,'') ||> 0 , sql_id
disk_reads
group by sql_exec_start,
NVL2(p.plan_time, p.plan_time sql_id,
|| , instance_number
Explain Plan waiting steps
SUM(px_servers_execs_total)/decode(S
,sql_exec_id, ROUND(SUM(direct_writes_delta))
'(s)','') AS PLAN sql_plan_hash_value, , parsing_schema_name
UM(executions_total),0,1,SUM(execution
module, direct_writes
action, sample_id, sample_time , plan_hash_value,
FROM gv$sql_plan_monitor p
s_total))
, WHERE avg_px
ROW_NUMBER()
having over
sum(temp_space_allocated) (PARTITION s.CPU_TIME_TOTAL,
sql_id='&sql_id'
is not
BY ORDERnull)FROM
sn.dbid, dba_hist_sqlstat
sn.snap_id,
BY p.plan_line_id, RANK() OVER (ORDER BY
group
st.instance_number
by WHERE
SQL_EXEC_START, (max(s.CPU_TIME_TOTAL/s.executions
p.plan_parent_id; https://blog.yannickjaquier.com/oracle/real-time-sql-monitoring.html
executions_total
sql_exec_id, sql_plan_hash_value,ORDER BY >0 _total)) DESC) cpu_rank,
AWR -- FULL Details
GROUP BY --check sql_id,rn Current Memory
module, action
SUM(elapsed_time_delta) desc) RANK() OVER (ORDER BY
plan_hash_value
FROM
--having dba_hist_snapshot
max(temp_space_allocated) sn / (max(s.ELAPSED_TIME_TOTAL/s.EXE
)/ t2
,1024dba_hist_sqlstat
1024 / 1024 > 2st-- GB CUTIONS_TOTAL)) DESC)
WHERE
order by 1st.dbid = sn.dbid SELECT
elapsed_rank *
<== Advanced Queries (Takes time)
AND
*/ t1.sql_id
st.snap_id = nvl(TRIM('&sql_id'),
= sn.snap_id FROM dba_hist_active_sess_history
from
t1.sql_id)
AND
/ sn.instance_number = WHERE sample_time
dba_hist_sqlstat s https://github.com/iusoltsev/sqlplus/blob/m
AND t1.depth = 0
st.instance_number BETWEEN
where '16-AUG-18
GROUP ANDBY t1.sql_id = t2.sql_id(+) 12.00.00.000000000
s.snap_id= 11706 AM'
AND t1.plan_hash_value =
sn.dbid AND '20-AUG-18
and 01.00.00.000000000
s.executions_total >0
,t2.plan_hash_value(+)
sn.snap_id AM' and
group by sql_id='74krhckhdm5f3'
,ordersn.end_interval_time
by avg_et_secs, cost ORDER BY sample_time ASC
snap_id
/, st.sql_id /, sql_id
,All inst.instance_number
one ,Rankinstance_number
Based
, st.parsing_schema_name , parsing_schema_name
, st.plan_hash_value , plan_hash_value,
)x s.CPU_TIME_TOTAL
WHERE rn = 5 )x
ORDER by snap_id DESC, where cpu_rank <=10 and
instance_number, rn; elapsed_rank<=10;
CURRENT,SQL_CHILD_NUMBER,temp_
space_allocated,
greatest(temp_space_allocated -
first_value(temp_space_allocated) over
(partition by
SESSION_ID,SESSION_SERIAL# order
by sample_time rows 1
preceding),0)/power(1024,2)
"DELTA_TEMP_MB"
from
v$active_session_history
where
IS_SQLID_CURRENT='Y'
and sample_time > sysdate-
&seconds/86400
order by 1,2,3,4
)
group
TEMP by sql_id
having sum(DELTA_TEMP_MB) > 0
)
where rank < (&top+1)
order by rank
/

exec
dbms_stats.flush_database_monitoring_i
nfo;

select inserts,updates,deletes from


user_tab_modifications where
table_name = '&table_name';
select * from (
select EVENT, WAIT_CLASS,
http://guyharrison.squarespace.com/opsgsamples/
SUM(TOTAL_WAITS),round
select
(sum(TIME_WAITED_micro)/1000000,0)
assql_id,
time_waited_secs from
event,
V$SYSTEM_EVENT
count(*),
where wait_class != 'Idle' group by
lpad(round(ratio_to_report(count(*))
EVENT, WAIT_CLASS
over
order()by
* 100)||'%',10,' ') percent
time_waited_secs desc ) where
from
rownum < 21;
dba_hist_active_sess_history h,
dba_objects o
where
h.snap_id=9018
group by
sql_id, event
order by
percent desc; <-- wait event for a specific snap_id
http://www.centroid.com/blog/monitoring-exadata-smart-scan

select * from
table(dbms_xplan.display('ASH_PLAN_T
ABLE','4dszd9dysry0c',null,'dbid=123456
and plan_hash_value = 3412983073'));

select * from
table(dbms_xplan.display('ASH_PLAN_T
ABLE','4dszd9dysry0c','+ADAPTIVE','dbid
=2783210685 and plan_hash_value =
3412983073')); https://hoopercharles.wordpress.com/2010/03/01/dbms_xplan-format-parameters/
http://blog.go-faster.co.uk/2016/11/ash-an
set pagesize 0
set linesize 30
spool kill_old_sess.sh
select '#!/bin/ksh' from dual;
select 'kill -9 ' || spid
select 'ALTER SYSTEM
from v$process KILL SESSION
p, v$SESSTAT
'''||SID||','||SERIAL#||'''IMMEDIATE;'
t,v$sess_io i ,v$session s from
v$session where
where i.sid=s.sid username = 'A' and
STATUS and =p.addr=paddr(+)
'ACTIVE'; http://www.tek-tips.com/viewthread.cfm?qid=1572803
and s.sid=t.sid
and t.statistic#=12
and s.program like 'oraagent%'
and logon_time < sysdate-1
and status <> 'ACTIVE'
order by logon_time desc
/
spool off
E) ='SYS' ORDER BY ELAPSED_TIME DESC
/
YES
SET SERVEROUTPUT ON
DECLARE
l_plans_altered PLS_INTEGER; variable sqlid number;
BEGIN exec :sqlid
l_plans_altered := :=DBMS_SPM.ALTER_SQL_PLAN_BA
DBMS_SPM.alter_sql_plan_baseline( SELINE ( SQL_HANDLE=>
sql_handle => 'SQL_d3318f33dfac7bc2', PLAN_NAME
'SYS_SQL_1447ba3a1d83920f', =>
plan_name => 'SQL_PLAN_d6ccg6ggusyy2ee7f0c12',
'SYS_SQL_PLAN_1d83920fae82cf72', ATTRIBUTE_NAME=> 'enabled',
attribute_name => 'ACCEPTED', ATTRIBUTE_VALUE => 'NO');
attribute_value => 'YES');

DBMS_OUTPUT.put_line('Plans Altered:
' || l_plans_altered); Now fix the plan of 31pux6bymf1d4 to
END;
<= My own sql Patch 5qbbnv0abm2vx
/

5qbbnv0abm2vx

SET SERVEROUTPUT ON variable sqlid number;


DECLARE execute :sqlid
l_plans_altered PLS_INTEGER; :=DBMS_SPM.LOAD_PLANS_FROM_
BEGIN CURSOR_CACHE(sql_id=>'5qbbnv0ab
l_plans_altered := m2vx', PLAN_HASH_VALUE=>
DBMS_SPM.alter_sql_plan_baseline( 4197102931, SQL_HANDLE =>
sql_handle => 'SQL_d3318f33dfac7bc2');
Enable/disable
'SQL_b3d69637aa86a8ca', Fix baseline of one sql_id to another
plan_name =>
'SQL_PLAN_b7pnq6yp8da6a29d0d9b7', SELECT * FROM
attribute_name => 'FIXED', TABLE(DBMS_XPLAN.DISPLAY_CUR
attribute_value
select => 'YES');
hint as outline_hints SOR('5qbbnv0abm2vx',&childnumber,'A
from (select p.name, p.signature, LLSTATS
SELECT LAST +PEEKED_BINDS
DBMS_OUTPUT.put_line('Plans
p.category, row_number() Altered:
+PROJECTION +ALIAS +OUTLINE
regexp_replace(extractvalue(value(d),
' || l_plans_altered);
over (partition by sd.signature, +PREDICATE
'/hint'),'''','''''') +COST +BYTES'));
plan_hint
END;
sd.category order by sd.signature) from
/row_num, xmltable('/*/outline_data/hint'
extractValue(value(t), '/hint') hint 4197102931 passing (
Taking SQL HINTSsd,
from sqlobj$data from PROFILES p,
dba_sql_profiles Taking SQL HINTS selectfrom PLAN_TABLE
xmltype(other_xml)
table(xmlsequence(extract(xmltype(sd.co as xmlval
mp_data), from plan_table
'/outline_data/hint'))) where other_xml is not
t null
where sd.obj_type = 1 and plan_id = (select
and p.signature = sd.signature max(plan_id) from plan_table)
and p.category = sd.category and rownum=1
and p.name like ('&profile_name')) )
order by row_num; ) d; https://jonathanlewis.wordpress.com/201

http://www.alfredokriegdba.com/2015/02/
http://www.nocoug.org/download/2008-08/a-tour-of-the-awr-tables.nocoug-Aug-21-2008.abercrombie.html#script-aas-exact
http://www.nocoug.org/download/2008-08/a-tour-of-the-awr-tables.nocoug-Aug-21-
g.go-faster.co.uk/2016/11/ash-analysis-detecting-and-profiling.html
nathanlewis.wordpress.com/2017/06/12/dbms_sqldiag/
Capacity Planning

Database/Table/tablespace/segment Growth Rate History

Tablespace growth Rate

Database Growth Trend/Rate


List object growth over last N days, sorted by growth desc

table size changes between two periods.

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

Transaction per second

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 object


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

Other DB Tuning
Avg Sql/Database Response Time

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
TUNING

sql profiles related to sql_id

histograms

STATISTICS

Table statistics
Index statistics
schema Statistics
Database statistics

Statistics collection for Dictionary

When was last analyzed


History of rowcount in table / History of table statistics

Statistics collection for all schema

Stale statistics

automatic stats collection enabled or not

automatic stats collection for database formula ( List stale more than
10% )

Automatic Stats Gathering Job - Parameters


Restore Old Statistics for DB/Schema/Table/Fixed Obj

Collecting historgram for a table

Histogram details for a table

statistics collection for schema including histogram


optimizer fraud- Manual stats setting

Statistics difference report

statistics of objects of a specific sql id

sql_profile details

sql base lines details

Top 10 statements

Top CPU consuming Session in last 5 minutes


Top Waiting Session in last 5 minutes

Top Waiting Event in last 5 minutes

Top SESSION by CPU usage, wait time and IO time in last 5 minutes

Top SQL by CPU usage, wait time and IO time in last 5 minutes
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

CPU Debug : resmgr:cpu quantum

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

Jobs/ Scheduler

Maintenance window time/Date

Command to change the default maintenance window

History of default maintenance job run status

Default jobs enabled or not

auot stats collection job details

Others

If we want to save every second ASH data to disk,By default, it save 1


second snapshot out of 10 seconds.
Cpu Starvation Calculation
AWR Related

Quick Cross-Period AWR Comparison

comparing top SQL in AWR across periods:


Load Profile query
with
a as (
select name,ts#,block_size
from v$tablespace,dba_tablespaces
where name = tablespace_name
),
c as (
select a.name,min(snap_id) Begin_snap_ID, max(snap_id) End_Snap_ID,
min(trunc(to_date(rtime,'MM/DD/YYYY HH24:MI:SS'))) begin_time,
max(trunc(to_date(rtime,'MM/DD/YYYY HH24:MI:SS'))) End_time
from dba_hist_tbspc_space_usage,a
where tablespace_id= a.ts#
group by a.name
),
d as (
select a.name,
round((dh.tablespace_size* A.BLOCK_SIZE)/1024/1024,2)
begin_allocated_space,
round((dh.tablespace_usedsize * A.BLOCK_SIZE)/1024/1024,2)
begin_Used_space
from
Heredba_hist_tbspc_space_usage dh,c,a --,b runaway query. It is based on data from v$sql_plan_statistics already mention
is a technique I use when troubleshooting
wheretremendous
dh.snap_id value
= c.Begin_snap_ID
and potentially a good alternative to 10046 traces. The biggest obstacle to a wide adoption is the horr
and a.ts# = dh.tablespace_id
“statistics_level=all” mode. But it is OK to do that at session level, even in production system. So, the execution of the query
and a.name = c.name statistics_level=all and recreate run environment. Here is the full sequence of a
),
e as ( – Find SQL_ID / Child_number of runway SQL from v$session;
select a.name, – Find plan_hash_value from v$sql using SQL_ID and CHILD_NUMBER;
round((tablespace_size*a.block_size)/1024/1024,2)
– Assuming the query is using bind variables, capture End_allocated_space,
bind variables from v$sql_bind_capture. There can be problems captur
round((tablespace_usedsize*a.block_size)/1024/1024,2) End_Used_spacebind variables, skip this step;
from dba_hist_tbspc_space_usage,c ,a – In a separate session “alter session set statistics_level=all”;
where snap_id = – c.End_Snap_ID
Start executing SQL in this session. If there were bind variables, set same values and, even more importantly
and a.ts# = dba_hist_tbspc_space_usage.tablespace_id
– If the query is absolutely hopeless, cancel execution (send break) after some time, even 10-15 s
and a.name
– Find = c.name
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;
select e.name,to_char(c.begin_time,'DD-MON-YYYY')
– Examine plan statistics from v$sql_plan_statistics. The beauty of plan statistics is that it provides data even on partial exec
Begin_time,d.begin_allocated_space
interpreting plan statistics. Once becoming"Begin_allocated_space(MB)",
familiar with them and having a decent viewer, one should be able to see absolute
d.begin_Used_space "Begin_Used_space(MB)",
in numbers. 10-15 seconds of execution should be enough for the query to get to the steps where it will be running fo
to_char(c.End_time,'DD-MON-YYYY') End_Time, e.End_allocated_space
"End_allocated_space(MB)", e.End_Used_space
This recipe looks rather tedious, "End_Used_space(MB)",
and it really is, unless the tool is used that does all that things. The point is, once I was free
(e.End_Used_space - d.begin_Used_space)"Total
only runaway queries (which are rare anyway) Growth(MB)", (c.End_time
but simply expensive -
queries with a lot of gets/execution. I should add tha
c.begin_time)"No.of complicated
days", cases or when in doubts. Most often, problems are simple and a quick look at the execution p
round(((e.End_Used_space - d.begin_Used_space)/(c.End_time -
c.begin_time))*30,2) "Growth(MB)_in_next30_days",
round(((e.End_Used_space - d.begin_Used_space)/(c.End_time -
c.begin_time))*60,2) "Growth(MB)_in_next60_days",
http://db.geeksinsight.com/2012/10/15/scripts-databasetabletablespace-growth-report-using-awr/
round(((e.End_Used_space - d.begin_Used_space)/(c.End_time -
Weekly
c.begin_time))*90,2) "Growth(MB)_in_next90_days"
from e,d,c
where e.name = d.name
and e.name = c.name
and (e.End_Used_space - d.begin_Used_space) > 0
order by 1;
from dba_hist_snapshot /sn,
sum(space_used_delta) 1024 / 1024 "Space used (MB)", avg(c.bytes) / 1024 /
dba_hist_seg_stat
1024 "Total Object a, Size (MB)",
dba_objects b,
round(sum(space_used_delta) / sum(c.bytes) * 100, 2) "Percent of Total Disk
dba_segments
Usage" c
where
from begin_interval_time > trunc(sysdate) – &days_back
and sn.snap_id = a.snap_id
dba_hist_snapshot sn,
and b.object_id = a.obj#
dba_hist_seg_stat a,
and b.owner = b,
dba_objects c.owner
and dba_segments c = c.segment_name
b.object_name
and
where c.owner ='&OWNER' > trunc(sysdate) - &days_back
begin_interval_time
group
and by c.TABLESPACE_NAME,c.segment_name,b.object_type)
sn.snap_id = a.snap_id
order by 3 asc; = a.obj#
and b.object_id
and b.owner = c.owner
and b.object_name = c.segment_name
andserveroutput
set c.segment_name on = '&segment_name'
group by to_char(end_interval_time, 'MM/DD/YY'))
prompt
order
-- Thisby to_date(mydate,
makes it possible to'MM/DD/YY');
locate this session in
-- order to kill it later.
BEGIN
45%dbms_output.put_line('
of ram size ');
dbms_output.put_line('SID is ' || sys_context('USERENV','SID'));
END;
EXAMPLE:
/---------

prompt
RAM SIZE Load is now
= 484 MBbeing generated.
-- This drops the copy table if it exists, and supresses
--
Sothe45error if it does
% should be =not
216exist.
MB
DECLARE
table_nonexistent
split the 216 MM forEXCEPTION;
SGA,PGA,BACKGROUNG PROCESSES
PRAGMA EXCEPTION_INIT(table_nonexistent, -942);
BEGIN
Fixed background process requires = 40 MB
BEGIN
execute immediate
SGA = 'drop 160 MBtable sh.sales_copy';
EXCEPTION
WHEN
PGA table_nonexistent
= 16 MB 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" | \


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

PRALLEL_THREADS_PER_CPU * CPU_COUNT (number of CPU cores) * ACTIVE_INSTANCE_COUNT (number of active in


SELECT A.SNAP_ID,A.INSTANCE_NUMBER
"ID",B.BEGIN_INTERVAL_TIME,B.END_INTERVAL_TIME,A.RESOURCE_NA
ME,
CURRENT_UTILIZATION "CURRENT",MAX_UTILIZATION "MAX"
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/

WITH hist_snaps
AS (SELECT instance_number,
snap_id,
round(begin_interval_time,'MI') datetime,
( begin_interval_time + 0 - LAG (begin_interval_time + 0)
OVER (PARTITION BY dbid, instance_number ORDER BY snap_id)) * 86400
diff_time
FROM dba_hist_snapshot), hist_stats
AS (SELECT dbid,
instance_number,
snap_id,
stat_name,
VALUE - LAG (VALUE) OVER (PARTITION BY
dbid,instance_number,stat_name ORDER BY snap_id)
delta_value
FROM dba_hist_sysstat
WHERE stat_name IN ('user commits', 'user rollbacks'))
SELECT datetime,
ROUND (SUM (delta_value) / 3600, 2) "Transactions/s"
FROM hist_snaps sn, hist_stats st
WHERE st.instance_number = sn.instance_number
AND st.snap_id = sn.snap_id
AND diff_time IS NOT NULL
GROUP BY datetime
ORDER BY 1 desc;

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);
Table renamed.

SQL> exec dbms_stats.gather_table_stats('SCOTT','BIG1');


COLUMN
PL/SQL procedureQUERY_PLAN FORMAT
successfully A60
completed.
SELECT LPAD (' ', 2 * LEVEL)
|| operation
SQL> select table_name,round((blocks*8),2)||'kb' "size"
2 from ||user_tables
''
3 where || table_name
options
SET LINESIZE
|| ' ' 100 = 'BIG1';
COLUMN trace_file FORMAT
|| object_name A60
TABLE_NAME size query_plan
FROM plan_table
------------------------------ ------------------------------------------
SELECT
CONNECT s.sid,
BY PRIOR id = parent_id
BIG1s.serial#,
85536kb
START WITH id = 1
pa.value
ORDER ||
id;'/' || LOWER(SYS_CONTEXT('userenv','instance_name'))
BYtable_name,round((num_rows*avg_row_len/1024),2)||'kb' ||
SQL> select
'_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 to_char(begin_time,'hh24:mi') time, round( value * 10, 2) "Response Time
(ms)"
from v$sysmetric
where metric_name='SQL Service Response Time';

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 (ORDER BY
sql_exec_id,
(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 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;

col data_type for a20


col column_name for a20
select table_name,column_name,data_type,num_distinct,num_nulls,
sample_size, histogram,num_buckets
from dba_tab_columns where table_name = '&TABLE_NAME' AND
OWNER='&OWNER';

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, esti
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_s
EXEC DBMS_STATS.GATHER_DATABASE_STATS(ESTIMATE_PERCENT => DBMS_STATS.AUTO_SAMPLE_SIZE, METH
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;
Table

set lines 1000 set pages 9999


col table_name for a40
col owner for a30
col partition_name for a40
col subpartition_name for a40
select distinct owner, table_name,partition_name,subpartition_name,
num_rows,blocks,stale_stats, TO_CHAR(last_analyzed,'dd-mon-yyyy
hh24:mi:ss') AS last_analyzed, stattype_locked
from dba_tab_statistics
where owner='&owner' and table_name in ('&tab1','&tab2','&tab3') order by
2,3,4;
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 n.object_name as
T,o.ROWCNT,o.BLKCNT,to_char(o.SAVTIME,'dd/mm/yyyy HH:MI:SS') as time
from dba_objects n,sys.WRI$_OPTSTAT_TAB_HISTORY o where
SET ECHO OFF and n.object_name='&Object_name' and n.owner='&owner'
o.obj#=n.object_id
SET
orderTERMOUT
by time; ON
SET SERVEROUTPUT ON
select 'execute DBMS_STATS.GATHER_SCHEMA_STATS('''||username||''') ;'
SET TIMING OFF
from dba_users where username <> 'SYS';
DECLARE
v1 varchar2(100);
v2 varchar2(100);
col TABLE_NAME for a30
v3 varchar2(100);
col PARTITION_NAME for a20
v4 varchar2(100);
col SUBPARTITION_NAME for a20
v5 varchar2(100);
select
v6 varchar2(100);
OWNER,TABLE_NAME,PARTITION_NAME,SUBPARTITION_NAME,NUM_RO
v7 varchar2(100);
WS,LAST_ANALYZED from dba_TAB_STATISTICS where
v8 varchar2(100);
STALE_STATS='YES';
v9 varchar2(100);
SELECT CLIENT_NAME, STATUS FROM DBA_AUTOTASK_CLIENT WHERE
v10 varchar2(100);
CLIENT_NAME='auto
BEGIN optimizer stats collection';
dbms_output.put_line('Automatic Stats Gathering Job - Parameters');

dbms_output.put_line('==========================================');
v1 := dbms_stats.get_prefs('AUTOSTATS_TARGET');
dbms_output.put_line(' AUTOSTATS_TARGET: ' || v1);
SELECT TABLES.OWNER, TABLES.TABLE_NAME,
v2 := dbms_stats.get_prefs('CASCADE');
ROUND((DELETES + UPDATES
dbms_output.put_line(' CASCADE:+ INSERTS)/NUM_ROWS*100)
' || v2);
PERCENTAGE
v3 := dbms_stats.get_prefs('DEGREE');
FROM DBA_TABLES TABLES,
dbms_output.put_line(' DEGREE:DBA_TAB_MODIFICATIONS
' || v3); MODIFICATIONS
WHERE TABLES.OWNER = MODIFICATIONS.TABLE_OWNER
v4 := dbms_stats.get_prefs('ESTIMATE_PERCENT');
AND TABLES.TABLE_NAME
dbms_output.put_line(' = MODIFICATIONS.TABLE_NAME
ESTIMATE_PERCENT: ' || v4); AND
NUM_ROWS > 0
v5 := dbms_stats.get_prefs('METHOD_OPT');
AND ROUND ( (DELETES
dbms_output.put_line(' + UPDATES + INSERTS)
METHOD_OPT: ' || v5); / NUM_ROWS * 100) >=
10v6 := dbms_stats.get_prefs('NO_INVALIDATE');
ORDER BY 3 desc
dbms_output.put_line(' NO_INVALIDATE: ' || v6);
/ v7 := dbms_stats.get_prefs('GRANULARITY');
dbms_output.put_line(' GRANULARITY: ' || v7);
v8 := dbms_stats.get_prefs('PUBLISH');
dbms_output.put_line(' PUBLISH: ' || v8);
v9 := dbms_stats.get_prefs('INCREMENTAL');
dbms_output.put_line(' INCREMENTAL: ' || v9);
v10:= dbms_stats.get_prefs('STALE_PERCENT');
dbms_output.put_line(' STALE_PERCENT: ' || v10);
END;
/
DBMS_STATS.RESTORE_DICTIONARY_STATS - Used to restore data
dictionary stats

DBMS_STATS.RESTORE_FIXED_OBJECTS_STATS - Used to restore fixed


object stats

DBMS_STATS.RESTORE_SCHEMA_STATS - Used to restore schema stats

DBMS_STATS.RESTORE_SYSTEM_STATS - Used to restore system stats

DBMS_STATS.RESTORE_TABLE_STATS - Used to restore table stats


exec dbms_stats.gather_table_stats('DBUSER01','TABLE01',
estimate_percent=>33, cascade => TRUE, method_opt => 'FOR ALL INDEXED
COLUMNS SIZE 10');

COL owner FOR A30


COL table_name FOR A30
COL column_name FOR A30
col LAST_ANALYZED for a30
SELECT OWNER,table_name,column_name, num_distinct,
num_buckets,NUM_NULLS,DENSITY,to_char(LAST_ANALYZED, 'dd-mon-yyyy
hh24:mi:ss') last_analyzed ,GLOBAL_STATS, histogram
FROM DBA_TAB_COL_STATISTICS
WHERE owner='&OWNER' and table_name = '&TABLE_NAME';

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;
/

select * from table(dbms_stats.diff_table_stats_in_history(


ownname => '&OWNER',
tabname => upper('&tabname'),
time1 => systimestamp,
time2 => to_timestamp('&time2','yyyy-mm-dd:hh24:mi:ss'),
pctthreshold => 0));

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 session_id,
COUNT(*)
FROM v$active_session_history
WHERE session_state = 'ON CPU'
AND sample_time > sysdate - ( 5 / ( 24 * 60 ) )
GROUP BY session_id
ORDER BY COUNT(*) DESC;
SELECT session_id,
COUNT(*)
FROM v$active_session_history
WHERE session_state = 'WAITING'
AND sample_time > sysdate - ( 5 / ( 24 * 60 ) )
GROUP BY session_id
ORDER BY COUNT(*) DESC;

SELECT event,
COUNT(*)
FROM v$active_session_history
WHERE session_state = 'WAITING'
AND sample_time > sysdate - ( 5 / ( 24 * 60 ) )
GROUP BY event
ORDER BY COUNT(*) DESC;

select
ash.session_id,
ash.session_serial#,
ash.user_id,
ash.program,
sum(decode(ash.session_state,'ON CPU',1,0)) "CPU",
sum(decode(ash.session_state,'WAITING',1,0)) -
sum(decode(ash.session_state,'WAITING',
decode(en.wait_class,'User I/O',1, 0 ), 0)) "WAITING" ,
sum(decode(ash.session_state,'WAITING',
decode(en.wait_class,'User I/O',1, 0 ), 0)) "IO" ,
sum(decode(session_state,'ON CPU',1,1)) "TOTAL"
from v$active_session_history ash,
v$event_name en
where en.event# = ash.event# AND SAMPLE_TIME > SYSDATE - (5/(24*60))
group by session_id,user_id,session_serial#,program
order by sum(decode(session_state,'ON CPU',1,0));

SELECT ash.sql_id,
SUM(DECODE(ash.session_state, 'ON CPU', 1, 0)) "CPU",
SUM(DECODE(ash.session_state, 'WAITING', 1, 0))
- SUM( DECODE(ash.session_state, 'WAITING',
DECODE(en.wait_class, 'User I/O', 1, 0), 0)) "WAIT",
SUM(DECODE(ash.session_state, 'WAITING', DECODE(en.wait_class,
'User I/O', 1, 0), 0)) "IO",
SUM(DECODE(ash.session_state, 'ON CPU', 1, 1)) "TOTAL"
FROM v$active_session_history ash,
v$event_name en
WHERE sql_id IS NOT NULL AND SAMPLE_TIME > SYSDATE - (5/(24*60))
AND en.event# = ash.event#
GROUP BY sql_id
ORDER BY SUM(DECODE(session_state, 'ON CPU', 1, 0)) DESC;
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',
sio,group_id=2
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)
/

https://jonathanlewis.wordpress.com/2014/12/09/parse-time-2/
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;

https://tinky2jed.wordpress.com/technical-stuff/oracle-stuff/changing-the-oracle-database-default-maintenance-window-time/
select window_name, repeat_interval, duration from dba_scheduler_windows;

EXECUTE
DBMS_SCHEDULER.SET_ATTRIBUTE('WEEKNIGHT_WINDOW','repeat_inter
val','freq=daily;byday=MON,TUE,WED,THU,FRI;byhour=05;byminute=0;
bysecond=0');
EXECUTE
DBMS_SCHEDULER.SET_ATTRIBUTE('WEEKEND_WINDOW','repeat_interva
l',' freq=daily;byday=SAT;byhour=07;byminute=0;bysecond=0');

select client_name, job_status, job_start_time, job_duration from dba_autotask_job_history order by job_start_time;

select client_name, status, window_group from dba_autotask_client;

select actual_start_date,run_duration,job_name,status,additional_info from


dba_scheduler_job_run_details where job_name like 'ORA$AT_OS%' order by
log_date;

select * from dba_scheduler_job_run_details where job_name like


'ORA$AT_OS%' order by log_date;

alter system set “_ash_disk_filter_ratio”=1.


AND bm.snap_id = ss.b_snap
AND bm.instance_number = ss.inst
AND em.dbid = ss.dbid
AND em.snap_id = ss.e_snap
AND em.instance_number = ss.inst
AND bm.stat_id = em.stat_id
GROUP BY
https://blog.dbi-services.com/sockets-cores-virtual-cpu-logical-cpu-hyper-threading-what-is-a-cpu-nowadays-1/
ss.dbid
,https://orastory.wordpress.com/page/2/
ss.inst
, ss.b_day
, ss.b_snap
, ss.e_snap
, ss.b_time
, ss.e_time
, ss.duration
--HAVING b_day NOT IN (6,7)
--AND inst = 2
--AND b_snap = 18673
--AND e_time = '17:00'
ORDER BY b_snap DESC;
, st.parsing_schema_name
, st.plan_hash_value
, SUM(st.fetches_delta) fch
, SUM(rows_processed_delta) rws
, SUM(executions_delta) execs
, ROUND(SUM(elapsed_time_delta)/1000/1000) elp
,
ROUND(SUM(elapsed_time_delta)/1000/1000/NVL(NULLIF(SUM(executions_d
elta),0),1),2) elpe
, ROUND(SUM(cpu_time_delta)/1000/1000) cpu
, SUM(buffer_gets_delta) gets
, ROUND(SUM(iowait_delta)/1000/1000) io
, ROUND(SUM(clwait_delta)/1000/1000) cl
, ROUND(SUM(ccwait_delta)/1000/1000) cc
, ROUND(SUM(apwait_delta)/1000/1000) ap
, ROUND(SUM(plsexec_time_delta)/1000/1000) pl
, ROUND(SUM(disk_reads_delta)) disk_reads
, ROUND(SUM(direct_writes_delta)) direct_writes
, ROW_NUMBER() over (PARTITION BY sn.dbid, sn.snap_id,
st.instance_number
ORDER BY SUM(elapsed_time_delta) desc) rn
FROM dba_hist_snapshot sn
, dba_hist_sqlstat st
WHERE st.dbid = sn.dbid
AND st.snap_id = sn.snap_id
AND sn.instance_number = st.instance_number
GROUP BY
sn.dbid
, sn.snap_id
, sn.end_interval_time
, st.sql_id
, st.instance_number
, st.parsing_schema_name
, st.plan_hash_value
)x
WHERE rn= 5
ORDER by snap_id DESC, instance_number, rn;
Parses' short_name, 1 coeff, 2 typ, 10 m_rank from dual union all
select 'Logons Per Txn' metric_name, 'Logons'
short_name, 1 coeff, 2 typ, 11 m_rank from dual union all
select 'Executions Per Txn' metric_name, 'Executes'
short_name, 1 coeff, 2 typ, 12 m_rank from dual union all
select 'User Rollbacks Per Txn' metric_name, 'Rollbacks'
short_name, 1 coeff, 2 typ, 13 m_rank from dual union all
select 'User Transaction Per Txn' metric_name,
'Transactions' short_name, 1 coeff, 2 typ, 14 m_rank from dual union all
select 'User Rollback Undo Records Applied Per Txn' metric_name,
'Applied urec' short_name, 1 coeff, 2 typ, 15 m_rank from dual) m
where m.metric_name = s.metric_name
and s.intsize_csec > 5000
and s.intsize_csec < 7000)
group by short_name)
order by m_rank;
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,onthe execution of the query is staged in a separate session where we can set
set serveroutput
d recreate run environment. Here is the full sequence of actions:
Declare
L_ID / Child_number of runway SQL
v_BaselineSize from v$session;
number(20);
sh_value from v$sql using SQL_ID
v_CurrentSize and CHILD_NUMBER;
number(20);
s from v$sql_bind_capture.
v_TotalGrowth Therenumber(20);
can be problems capturing bind variables, for brevity I will skip details. If no
bind variables,
v_Space skip this step;
number(20);
arate session “alter
cursor session
usageHistset statistics_level=all”;
is
nd variables, set same values
select and, even more importantly, same datatypes as in Capture step;
a.snap_id,
ncel execution (send SNAP_TIME,
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 over
sum(TOTAL_SPACE_ALLOCATED_DELTA) as in (step 1.by
order Very important: ProgSum
a.SNAP_ID) it should have
lan_hash_value, otherwise
from revise previous steps;
setislinesize
f plan statistics that(select750SNAP_ID,
it providespages
data9999
even on partial execution. It can be a separate article dedicated to the
aving a decentset numwidth
viewer, one 20
should be able to see absolutely TOTAL_SPACE_ALLOCATED_DELTA
sum(SPACE_ALLOCATED_DELTA) clear where the problem is. No guess work, it’s all
COL
or the query to getNAME the FOR
tofrom steps A30
where it will be running for lo-o-ong time, they can be easily identified.
DBA_HIST_SEG_STAT
col SNAP_ID group for 9999999
by SNAP_ID
sed that does all thathaving things.sum(SPACE_ALLOCATED_TOTAL)
The point is, once I was free from all<> that
0 routine, I was able to troubleshoot not
nsive queriesSELECT
with a lot of gets/execution.
order by 1 ) a, I should add that it makes sense to use this technique in really
n, problems are distinct
simple DHSS.SNAP_ID,VTS.NAME,
and a quick look
(select distinct SNAP_ID, at the execution plan is enough to spot the cause.
TO_CHAR(DHSS.END_INTERVAL_TIME,
to_char(END_INTERVAL_TIME,'DD-Mon-YYYY 'DD-MM HH:MI')HH24:Mi')
AS SNAP_Time,
SNAP_TIME
ROUND((DHTS.TABLESPACE_USEDSIZE*8192)/1024/1024)
from DBA_HIST_SNAPSHOT) b AS USED_MB,
ROUND((DHTS.TABLESPACE_SIZE*8192)/1024/1024)
where a.snap_id=b.snap_id; AS SIZE_MB
FROM
Begin DBA_HIST_TBSPC_SPACE_USAGE DHTS,
http://db.geeksinsight.com/2012/10/15/scripts-databasetabletablespace-growth-report-using-awr/
V$TABLESPACE VTS,
select sum(SPACE_ALLOCATED_DELTA)
Hourly into v_TotalGrowth from DBA_HIST_SEG_STAT;
DBA_HIST_SNAPSHOT DHSS
select sum(bytes) into v_CurrentSize from dba_segments;
WHERE VTS.TS#=DHTS.TABLESPACE_ID
v_BaselineSize := v_CurrentSize - v_TotalGrowth ;
AND DHTS.SNAP_ID=DHSS.SNAP_ID
AND DHSS.INSTANCE_NUMBER=1
dbms_output.put_line('SNAP_TIME Database Size(MB)');
AND NAME='&TABLESPACE_NAME'
ORDER
for rowBY in 1;
usageHist loop
v_Space := (v_BaselineSize + row.ProgSum)/(1024*1024);
dbms_output.put_line(row.SNAP_TIME || ' ' || to_char(v_Space) );
end loop;
end;
/
OS occupies memory of
-----------------------

20 % of RAM SIZE --> for windows

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

For merging files

cat *.xml >> file.log

ores) * ACTIVE_INSTANCE_COUNT (number of active instances)


http://www.oracle.com/technetwork/articles/schumacher-analysis-099313.html

col STAT_NAME for a20


col VALUE_DIFF for 9999,999,999
col STAT_PER_MIN for 9999,999,999
set lines 200 pages 1500 long 99999999
col BEGIN_INTERVAL_TIME for a30
col END_INTERVAL_TIME for a30
set pagesize 40
set pause on

select hsys.SNAP_ID,
hsnap.BEGIN_INTERVAL_TIME,
hsnap.END_INTERVAL_TIME,
hsys.STAT_NAME,
hsys.VALUE,
hsys.VALUE - LAG(hsys.VALUE,1,0) OVER (ORDER BY hsys.SNAP_ID) AS
"VALUE_DIFF",
round((hsys.VALUE - LAG(hsys.VALUE,1,0) OVER (ORDER BY hsys.SNAP_ID)) /
round(abs(extract(hour from (hsnap.END_INTERVAL_TIME -
hsnap.BEGIN_INTERVAL_TIME))*60 +
extract(minute from (hsnap.END_INTERVAL_TIME - hsnap.BEGIN_INTERVAL_TIME)) +
extract(second from (hsnap.END_INTERVAL_TIME -
hsnap.BEGIN_INTERVAL_TIME))/60),1)) "STAT_PER_MIN"
from dba_hist_sysstat hsys, dba_hist_snapshot hsnap
where hsys.snap_id = hsnap.snap_id
and hsnap.instance_number in (select instance_number from v$instance)
and hsnap.instance_number = hsys.instance_number
and hsys.STAT_NAME='user commits'
order by 1;
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
with epsilon
as
(select avg(average - STANDARD_DEVIATION ) m1,
avg(average + STANDARD_DEVIATION ) m2
from dba_hist_sysmetric_summary
where metric_name='User Calls Per Sec')
select avg(a.average - a.STANDARD_DEVIATION) "A - Good",
avg(a.average) "Average",
avg(a.average + a.STANDARD_DEVIATION) "B - Bad"
from dba_hist_sysmetric_summary a,
dba_hist_sysmetric_summary b,
epsilon e
where a.metric_name='SQL Service Response Time'
and b.metric_name='User Calls Per Sec'
and a.snap_id = b.snap_id
and b.average between e.m1 and e.m2
/

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 COLUM
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);
RCENT => DBMS_STATS.AUTO_SAMPLE_SIZE, METHOD_OPT => 'FOR ALL COLUMNS SIZE AUTO', DEGREE => 8, CASCADE => T

Partition

set lines 1000 pages 9999


col table_owner for a30
col table_name for a50
col partition_name for a50
select table_owner,table_name, partition_name, global_stats, TO_CHAR(last_analyzed,'dd-
mon-yyyy hh24:mi:ss') AS last_analyzed, num_rows
from dba_tab_partitions
where table_name='&partition_name'
and table_owner='&table_owner'
order by 1, 2, 4 desc nulls last;
set serveroutput on

DECLARE
ObjList dbms_stats.ObjectTab;
BEGIN
dbms_stats.gather_database_stats(objlist=>ObjList, options=>'LIST STALE');
FOR i in ObjList.FIRST..ObjList.LAST
LOOP
dbms_output.put_line(ObjList(i).ownname || '.' || ObjList(i).ObjName || ' ' || ObjList(i).ObjType || ' '
|| ObjList(i).partname);
END LOOP;
END;
/
COL owner FOR A30
COL table_name FOR A30
COL column_name FOR A30

SELECT
owner
table_name,
column_name, count(*)
FROM
dba_tab_histograms
WHERE owner = '&OWNER'
and table_name='&TABLE_NAME'
GROUP BY owner,table_name, column_name
ORDER BY count(*) ASC
/
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_015fdc7edace
0003'));

http://rohitsinhago.blogspot.com/2009/05/tracing-other-sessions.html

https://alexzeng.wordpress.com/2012/09/25/valuate-oracle-awr-automatic-workload-repository/
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','SUMMAR
Y') FROM dual;
the-oracle-database-default-maintenance-window-time/

a_autotask_job_history order by job_start_time;


yper-threading-what-is-a-cpu-nowadays-1/
https://timurakhmadeev.wordpress.com/2012/02/21/load-profile/
http://www.jamesmorle.com/the-oracle-wait-interface-is-useless-sometimes-pt/

https://anandmandilwar.com/2016/11/09/collection-of-useful-script-for-oracle-apps-dba/https://www.programering.com/a/MTM3
http://db.geeksinsight.com/2012/10/15/scripts-databasetabletablespace-growth-report-using-awr/
https://grepora.com/2016/05/25/oracle-tps-evaluating-transaction-per-second/ http://dbaclass.com/article/find-user-commits-pe
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
col owner for a30
col object_name for a50
SELECT Rownum AS Rank,
Seg_Lio.*
FROM (SELECT St.Owner,
St.Obj#,
St.Object_Type,
St.Object_Name,
St.VALUE,
'LIO' AS Unit
FROM V$segment_Statistics St
WHERE St.Statistic_Name = 'logical reads'
ORDER BY St.VALUE DESC) Seg_Lio
WHERE Rownum <= 10
UNION ALL
SELECT Rownum AS Rank,
Seq_Pio_r.*
FROM (SELECT St.Owner,
St.Obj#,
St.Object_Type,
St.Object_Name,
St.VALUE,
'PIO Reads' AS Unit
FROM V$segment_Statistics St
WHERE St.Statistic_Name = 'physical reads'
ORDER BY St.VALUE DESC) Seq_Pio_r
WHERE Rownum <= 10
UNION ALL
SELECT Rownum AS Rank,
Seq_Pio_w.*
FROM (SELECT St.Owner,
St.Obj#,
St.Object_Type,
St.Object_Name,
St.VALUE,
'PIO Writes' AS Unit
FROM V$segment_Statistics St
WHERE St.Statistic_Name = 'physical writes'
ORDER BY St.VALUE DESC) Seq_Pio_w
WHERE Rownum <= 10;
https://blog.pythian.com/do-you-know-if-your-database-slow/https://workwiththebest.intraway.com/blog-post/how-to-quickly-tell
https://www.oracle.com/technetwork/articles/schumacher-analy
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
le_size,method_opt=>'FOR ALL COLUMNS SIZE AUTO', granularity => 'ALL', degree => 8);

SIZE AUTO', degree => 8);


AUTO', DEGREE => 8, CASCADE => TRUE);

Subpartition

set lines 1000 pages 9999


col table_owner for a30
col table_name for a50
col subpartition_name for a50
select table_owner,table_name, subpartition_name,
global_stats, TO_CHAR(last_analyzed,'dd-mon-yyyy
hh24:mi:ss') AS last_analyzed, num_rows
from dba_tab_subpartitions
where table_name='&subpartition_name'
and table_owner='&table_owner'
order by 1, 2, 4 desc nulls last;
(Doc ID 457666.1)
https://community.toadworld.com/platforms/oracle/w/wiki/5477.recovering-previous-statistics
<-- 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;
work/articles/schumacher-analysis-099313.html
Database

Database Size
Table

Table size in MB

Each Table Size under a Schema

LOB Segment size in a TABLE Column wise

Table Partition size

Table subpartition size


Schema

Schema size in GB

Each Schema Size in MB


Tablespace

Tablespace Free

datafiles under tablespace


Max datafile limit formula

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


Index size,status,analyzed for a single table

Extent That going to get failed in Next Extent

Table fragmentation

LOB Space Allocations- Partition


SET LINESIZE 200
CDB
COLUMN owner FORMAT A30
COLUMN table_name FORMAT A30
select
COLUMN a.data_size+b.temp_size+c.redo_size+d.controlfile_size
column_name FORMAT A30
"total_size in MB" from ( select
COLUMN segment_name FORMATsum(bytes)/1024/1024
A30 data_size
from dba_data_files) a,( select
COLUMN tablespace_name FORMAT A30 nvl(sum(bytes),0)/1024/1024
temp_size
COLUMN size_mb from dba_temp_files ) b,( select sum(bytes)/1024/1024
FORMAT 99999999.00
redo_size from sys.v_$log ) c,
(SELECT
select sum(BLOCK_SIZE*FILE_SIZE_BLKS)/1024/1024
*
controlfile_size
FROM (SELECT from v$controlfile) d;
l.owner,
select
Without LOBl.table_name,
segment_name
l.column_name,table_name,
select segment_name,sum(bytes)/(1024*1024)
sum(bytes)/(1024*1024) table_size_meg "TABLE_SIZE(MB)"
from l.segment_name,
dba_extents where segment_type='TABLE' and
from l.tablespace_name,
owner=upper('&OWNER')
dba_extents and segment_name
=upper( ROUND(s.bytes/1024/1024,2)
'&SEGMENT_NAME') group by size_mb
segment_name;
whereFROM dba_lobs l
segment_type='TABLE'
JOIN dba_segments s ON s.owner = l.owner AND
and
set pages 50000 lines
s.segment_name 32767
= l.segment_name
colowner='GLOGOWNER'
tablespace_name
AND l.owner='&OWNER' group
format a30 by segment_name order by 2 desc;
col TABLESPACE_NAME heading
AND l.TABLE_NAME='&TABLE_NAME' "Tablespace|Name"
col Allocated_size
ORDER BY 6 DESC) heading "Allocated|Size(GB)" form 99999999.99
SELECT
col Current_size heading "Current|Size(GB)" form 99999999.99
WHERE ROWNUM <= 20;
owner,segment_name,partition_name,segment_type,bytes/1024/1024
col Used_size heading "Used|Size(GB)" form 99999999.99
"MB"
col FROM dba_segments
Available_size WHERE segment_type
heading "Available|Size(GB)" form=99999999.99
'TABLE
PARTITION'
col Pct_used
SELECT and segment_name=
heading "%Used '&TABLE_NAME'
(vs)|(Allocated)" form and
99999999.99
partition_name='&SUBPARTITION_NAME'
select a.tablespace_name and OWNER='&OWNER';
owner,segment_name,partition_name,segment_type,bytes/1024/1024
"MB",a.alloc_size/1024/1024/1024
FROM dba_segments WHERE Allocated_size
segment_type = 'TABLE
,a.cur_size/1024/1024/1024
SUBPARTITION' and segment_name= Current_Size
'&TABLE_NAME' and
,(u.used+a.file_count*65536)/1024/1024/1024
partition_name='&SUBPARTITION_NAME' Used_size
and OWNER='&OWNER';
,(a.alloc_size-(u.used+a.file_count*65536))/1024/1024/1024
Available_size
,((u.used+a.file_count*65536)*100)/a.alloc_size Pct_used
from
SELECTdba_tablespaces t
owner,Sum(bytes)/1024/1024/1024 AS total_size_gb
FROM ,(select t1.tablespace_name
dba_segments
WHERE ,nvl(sum(s.bytes),0)
owner =upper('&1') used
group by owner;
from dba_segments s
select owner,sum(bytes/1024/1024) ||'M' from dba_segments group by
,dba_tablespaces t1
owner order by sum(bytes/1024/1024) desc;
where t1.tablespace_name=s.tablespace_name(+)
group by t1.tablespace_name) u
,(select d.tablespace_name
,sum(greatest(d.bytes,nvl(d.maxbytes,0))) alloc_size
,sum(d.bytes) cur_size
,count(*) file_count
from dba_data_files d
group by d.tablespace_name) a
where t.tablespace_name=u.tablespace_name
and t.tablespace_name=a.tablespace_name
order by Pct_used desc
/
col file_name for a60
select TABLESPACE_NAME,FILE_ID,FILE_NAME,BYTES/1024/1024
"size in
MB",AUTOEXTENSIBLE,MAXBYTES/1024/1024,ONLINE_STATUS
from dba_data_files where
TABLESPACE_NAME='&TABLESPACE_NAME';
-- join with datafiles, put 5M minimum for datafiles with no extents
select file_name,nvl(hwm_blocks*(bytes/blocks),5*1024*1024)
hwm_bytes,bytes,autoextensible,maxbytes
SELECT A.tablespace_name tablespace, D.mb_total,
fromSUM hwmts right join dba_data_files
(A.used_blocks * D.block_size) / 1024 / 1024 mb_used,
using(tablespace_name,relative_fno)
D.mb_total - SUM (A.used_blocks * D.block_size) / 1024 / 1024
)
mb_free
select
FROMselect 'ALTER gv$sort_segment
TABLESPACE A, ' || tablespace_name || ' AUTOEXTEND
ON case (when autoextensible='YES'
MAXSIZE ' || to_char(round((bytes and maxbytes>=bytes
* 1.25)/
then -- we generate
SELECT
(1024*1024*1024),0),9999) B.name,resize statements
C.block_size,
|| 'G;' only
SUMif(C.bytes)
autoextensible
/ 1024can grow
/ 1024
back fromtodba_data_files
mb_total current size
where'/* reclaim
bytes'||to_char(ceil((bytes-hwm_bytes)/1024/1024),999999)
FROM v$tablespace B, v$tempfile C
> maxbytes
order ||'M WHERE
from
by '||to_char(ceil(bytes/1024/1024),999999)||'M
B.ts#= C.ts#
tablespace_name; */ '
||'alter
GROUPdatabase datafile '''||file_name||'''
BY B.name, C.block_size resize '||
ceil(hwm_bytes/1024/1024)||'M;'
)D
else -- generate
WHERE only a comment
A.tablespace_name when autoextensible is off
= D.name
set
GROUP'/* verify
reclaim off'||to_char(ceil((bytes-hwm_bytes)/1024/1024),999999)
by A.tablespace_name, D.mb_total;
column||'M from file_name format a50 word_wrapped
'||to_char(ceil(bytes/1024/1024),999999)
column||'M aftersmallest
value format
new_val
setting 999,990 heading
blksize
autoextensible maxsize"Smallest|Size|Poss."
higher than current size for
column
select
file ' currsize
value from format 999,990
v$parameter heading
where "Current|Size"
name = 'db_block_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 value from v$parameter where name = 'db_block_size'
/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_name desc) 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;
and si.segment_name = i.index_name
and si.tablespace_name=i.tablespace_name
and si.segment_type = 'INDEX'
and i.table_owner = t.owner
and i.table_name = t.table_name
and t.table_name='&TABLE_NAME'
and t.owner = st.owner
and st.owner='&OWNER'
and t.table_name = st.segment_name
and st.segment_type = 'TABLE'
order by pct_larger desc;
SELECT
segment_name,OWNER,segment_type,extents,max_extents,TABLES
PACE_NAME
FROM dba_segments
col table_name
WHERE extentsfor a30
> max_extents - 10;
col total_size for a20
col actual_size for a20
select table_name,round(((blocks*8/1024)),2)||'MB' "TOTAL_SIZE",
round((num_rows*avg_row_len/1024/1024),2)||'Mb' "ACTUAL_SIZE",
round(((blocks*8/1024)-(num_rows*avg_row_len/1024/1024)),2) ||'MB'
"FRAGMENTED_SPACE",
(round(((blocks*8/1024)-
(num_rows*avg_row_len/1024/1024)),2)/round(((blocks*8/1024)),2))*1
00 "percentage"
from dba_tables WHERE owner='&OWNER' and
table_name='&TABLE_NAME';

select l.column_name, l.partition_name, l.lob_name,


l.lob_partition_name, s.bytes/1048576 "Size (MB)"
from dba_segments s, dba_lob_partitions l
where s.segment_name = l.lob_name
and s.owner='&OWNER'
and l.table_name ='&table_name'
and l.lob_partition_name = s.partition_name;
SUBPARTITION')
WHERE
UNION ALL s.segment_name = i.index_name
AND s.owner
SELECT i.table_name, = i.owneri.owner, s.bytes
AND s.segment_type
FROM dba_indexes i, dba_segments IN ('INDEX', 'INDEX s PARTITION', 'INDEX
SUBPARTITION')
WHERE s.segment_name = i.index_name
UNION ALL
AND s.owner = i.owner
SELECT
AND l.table_name, IN
s.segment_type l.owner, s.bytes
('INDEX', 'INDEX PARTITION', 'INDEX
SETFROM LINESIZE
dba_lobs 200 l, dba_segments s
SUBPARTITION')
PDB
COLUMN owner FORMAT A30
WHERE
UNION ALL s.segment_name = l.segment_name
COLUMN
AND table_name
s.owner = l.owner FORMAT A30
SELECT l.table_name,
COLUMN column_nameIN l.owner,
FORMAT s.bytes
A30
AND
FROM s.segment_type
dba_lobs l, ('LOBSEGMENT',
dba_segments s A30 'LOB PARTITION')
column
COLUMN dummy noprint
segment_name FORMAT
UNION
WHERE ALLs.segment_name =FORMAT
l.segment_name
select
column
COLUMN a.data_size+b.temp_size
pct_used formatl.owner,
tablespace_name 999.9 "total_size
A30 in"%|Used"
heading MB"
SELECT
AND l.table_name,
s.owner = l.owner s.bytes
from
column
COLUMN ( select
name sum(bytes)/1024/1024
format
size_mbl, FORMAT a19 data_size
heading
99999999.00 "Tablespace Name"
FROM dba_lobs
ANDdba_data_files)
s.segment_type dba_segments s
from
column Kbytes formata, IN ('LOBSEGMENT',
999,999,999 'LOB
heading PARTITION')
"KBytes"
WHERE
UNION ALLs.segment_name = l.index_name
(SELECT
select nvl(sum(bytes),0)/1024/1024
column used
* format 999,999,999 temp_size
heading "Used"
AND
SELECT s.owner = l.owner
l.table_name, l.owner, s.bytes
from
column
FROM dba_temp_files
free format
(SELECT l.owner, ) b;
999,999,999 heading "Free"
AND
FROMLOB s.segment_type
dba_lobs l, = 'LOBINDEX')
dba_segments s
column
WITH largest
Segments
l.table_name,format 999,999,999 heading "Largest"
WHERE owner
WHEREmax_size in UPPER('&owner')
s.segment_name = l.index_name
column l.column_name, format 999,999,999 heading "MaxPoss|Kbytes"
and
ANDTable_name='&TABLE_NAME'
s.owner = l.owner
column pct_max_used
l.segment_name, format 999.9 heading "%|Max|Used"
GROUP BY table_name,= owner
AND s.segment_type 'LOBINDEX')
break on report
l.tablespace_name,
HAVING
WHERE owner SUM(bytes)/1024/1024 > 10 /* Ignore really small tables */
compute sum ofinkbytes
UPPER('&owner')
on report
ROUND(s.bytes/1024/1024,2) size_mb
ORDER
--andFROM BY 2;
Table_name='&TABLE_NAME'
compute sumdba_lobs
of free onl report
GROUP
compute BY sum
JOIN table_name,
ofdba_segments
used on reportowners ON s.owner = l.owner AND s.segment_name =
HAVING
l.segment_nameSUM(bytes)/1024/1024 > 10 /* Ignore really small tables */
ORDER
select BY
(select 2;decode(extent_management,'LOCAL','*','
AND l.owner='&OWNER' ') ||
decode(segment_space_management,'AUTO','a
-- AND l.TABLE_NAME='&TABLE_NAME' ','m ')
from dba_tablespaces
ORDER BY 6 DESC) where tablespace_name = b.tablespace_name) ||
nvl(b.tablespace_name,
WHERE ROWNUM <= 20;
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
SELECT largest,
owner,tablespace_name,Sum(bytes)/1024/1024/1024 AS total_size_gb
FROM tablespace_name
dba_segments
from sys.dba_free_space
WHERE owner =upper('&1') group by owner,tablespace_name;
group by tablespace_name ) a,
( select sum(bytes)/1024 Kbytes_alloc,
sum(maxbytes)/1024 Kbytes_max,
tablespace_name
from sys.dba_data_files
group by tablespace_name
union all
select sum(bytes)/1024 Kbytes_alloc,
sum(maxbytes)/1024 Kbytes_max,
tablespace_name
from sys.dba_temp_files
group by tablespace_name )b
where a.tablespace_name (+) = b.tablespace_name
order by 4
/

alter tablespace USERTABLESPACE add datafile '+DATAGROUP' size 10G;


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

Script to Command to resize


------------------------------------------
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
select table_name,avg_row_len,round(((blocks*16/1024)),2)||'MB' "TOTAL_SIZE",
round((num_rows*avg_row_len/1024/1024),2)||'Mb' "ACTUAL_SIZE",
round(((blocks*16/1024)-(num_rows*avg_row_len/1024/1024)),2) ||'MB'
"FRAGMENTED_SPACE",
(round(((blocks*16/1024)-
(num_rows*avg_row_len/1024/1024)),2)/round(((blocks*16/1024)),2))*100
"percentage"
from all_tables WHERE table_name='&TABLE_NAME';
select con_id,name,SUM(SIZE_MB) from
(
select c.con_id,nvl(p.name, 'CDB') name,
sum(bytes)/1024/1024 SIZE_MB from cdb_data_files c,
CDB WITH
v$pdbs ALL PDB
p where c.con_id=p.con_id(+) GROUP BY
c.con_id,name
UNION
select c.con_id,nvl(p.name, 'CDB') name ,
sum(bytes)/1024/1024 SIZE_MB from cdb_temp_files
c, v$pdbs p where c.con_id=p.con_id(+) GROUP BY
c.con_id,name
)group by con_id,name
order by con_id;

SELECT tablespace_name,
SUM (bytes) / (1024 * 1024) "FREE(MB)"
FROM dba_free_space where
tablespace_name=UPPER('&TABLESPACE_NAME')
GROUP BY tablespace_name;
file_name,
segment_type,
owner||'.'||segment_name segment,
block_id,
blockIdMB
from
select( b.Total_MB,
select
b.Total_MB - round(a.used_blocks*8/1024)
ex.owner owner,
Current_Free_MB,
ex.segment_name segment_name,
round(used_blocks*8/1024)
ex.segment_type segment_type,
Current_Used_MB,
ex.block_id block_id,
round(max_used_blocks*8/1024)
Max_used_MBdf.file_name file_name,
from v$sort_segment a,
trunc((ex.block_id*(ts.block_size))/1024/1024,2)
(select round(sum(bytes)/1024/1024) Total_MB from
blockIdMB
dba_temp_files ) b;
from
dba_extents ex, dba_data_files df,
dba_tablespaces ts
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
)
where rownum <= 100
/

gmented.html
col Table_name for a40
select table_name,
round(size_kb/1024) SIZE_MB,
round(actual_data_kb/1024) ACTUAL_DATA_MB,
round(wasted_space_kb/1024) WASTED_SPACE_MB
from (
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);
Only Segment Based

select sum(bytes)/1024/1024/1024 "DATABASE SIZE GB" from dba_segments;

set lines 750 pages 9999


SELECT ts.tablespace_name, "File Count",
TRUNC("SIZE(MB)", 2) "Size(MB)",
TRUNC(fr."FREE(MB)", 2) "Free(MB)",
TRUNC("SIZE(MB)" - "FREE(MB)", 2) "Used(MB)",
df."MAX_EXT" "Max Ext(MB)",
(fr."FREE(MB)" / df."SIZE(MB)") * 100 "% Free"
FROM (SELECT tablespace_name,
SUM (bytes) / (1024 * 1024) "FREE(MB)"
select *dba_free_space
FROM from dba_tablespace_usage_metrics;
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
WHERE fr.tablespace_name = df.tablespace_name (+)
AND fr.tablespace_name = ts.tablespace_name (+)
ORDER BY ts.tablespace_name;
http://stelliosdba.blogspot.com/2012/03/ora-03297-file-contains-used-data.html http://blog.dbi-services.com/resiz
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;
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

MAX_PDB_STORAGE

PDB & CDB Name


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>

select PROPERTY_NAME,PROPERTY_VALUE,DESCRIPTION,CON_ID FROM cdb_properties


WHERE property_name = 'MAX_PDB_STORAGE';

select name CDB_NAME,(select name from v$pdbs) PDB_NAME,open_mode,database_role,(SELECT


to_char(sysdate,'DD-MON-YYYY HH24:MI:SS') FROM dual) "Current_time_db" ,(select
INSTANCE_NAME from v$instance) INSTANCE_NAME,(select HOST_NAME from v$instance )
HOST_NAME from v$database;
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
col
echoDB_UNIQUE_NAME
-e "\033[0;31mNodes: format a10
\033[0;0m"`srvctl config database -d $line | grep
set head on;nodes" | cut -f2 -d:`;
"Configured
set
echolines 5000;
-e "\033[0;31mPDB: \033[0;0m"`srvctl config service -d $line -s
set tab off;
$CHANGE_ME | grep -i "Pluggable database name" | cut -f2 -d:`;
set
donetrimspool on;
; unset CHANGE_ME
COL BYTES FORMAT 999,999,999,999,999
COL MAXBYTES FORMAT 999,999,999,999,999
COL ZBYTES FORMAT 999,999,999,999,999
col FILE_NAME format a115

col zmax_pdb_storage_GB format 999,999,999,999,999


col "dbfile_total_size_GB" format 999,999,999,999,999
col dbfile_max_size_GB format 999,999,999,999,999

col data_size_GB format 999,999,999,999,999


col temp_size_GB format 999,999,999,999,999

col pdb_name format a15

select * from
(
select
srvctl add service -db, --b.con_id,
c.db_unique_name RAC12C -service TAFSRV -preferred RAC12C1 -available
RAC12C2 \
b.name pdb_name,
-tafpolicy BASIC -policy AUTOMATIC -failovertype
to_number(a.property_value)/1024/1024/1024 SELECT -failovermethod
zmax_pdb_storage_GB , BASIC \
-failoverretry 5 -pdb DEMOPDB
c.database_role , c.open_mode -verbose
srvctl start service -d RAC12C -s TAFSRV
from
database_properties a, v$pdbs b , v$database c
WHERE
a.property_name ='MAX_PDB_STORAGE'
) pdb_info ,
(
select a.data_size_GB+b.temp_size_GB "dbfile_total_size_GB" ,
a.max_size_GB+b.max_size_GB as dbfile_max_size_GB , data_size_Gb,
temp_size_GB
from ( select sum(bytes)/1024/1024/1024 data_size_GB ,
sum(maxbytes)/1024/1024/1024 max_size_GB
from dba_data_files ) a,
( select nvl(sum(bytes)/1024/1024/1024,0) temp_size_GB ,
sum(maxbytes)/1024/1024/1024 max_size_GB
from dba_temp_files ) b
) sdf ;
col DB_UNIQUE_NAME format a10
set lines 5000;
set tab off;
set trimspool on;
COL BYTES FORMAT 999,999,999,999,999
COL MAXBYTES FORMAT 999,999,999,999,999
COL ZBYTES FORMAT 999,999,999,999,999
col FILE_NAME format a115

col total_size format 999,999,999,999,999


col
<----zmax_pdb_storage format
input the service name
999,999,999,999,999
col "dbfile_total_size" format
999,999,999,999,999
col dbfile_max_size format 999,999,999,999,999

col data_size format 999,999,999,999,999


col temp_size format 999,999,999,999,999

col pdb_name format a15

select * from
(
select
c.name dbname , c.db_unique_name ,
--b.con_id,
b.name pdb_name, b.total_size ,
to_number(a.property_value)
zmax_pdb_storage ,
(b.total_size/to_number(a.property_value))
zpdb_pctfull ,
c.database_role , c.open_mode
from
database_properties a, v$pdbs b , v$database c
WHERE
a.property_name ='MAX_PDB_STORAGE'
) pdb_info ,
(
select a.data_size+b.temp_size
"dbfile_total_size" , a.max_size+b.max_size as
dbfile_max_size , data_size, temp_size
from ( select sum(bytes) data_size ,
sum(maxbytes) max_size
from dba_data_files ) a,
( select nvl(sum(bytes),0) temp_size ,
sum(maxbytes) max_size
from dba_temp_files ) b
) sdf;
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/ sum (io_count) as "LONG_WAIT_PCT",
(long_waits)
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;
from
SELECT V$RMAN_BACKUP_JOB_DETAILS
where s.input_file_scan_only =j 'NO'
leftbs.recid
outer join (select
group by d.session_recid,
bs_key d.session_stamp) x
on
, bp.tag d.session_recid,
x.session_recid d.session_stamp,
= j.session_recid and x.session_stamp = j.session_stamp tag
,left outer joinsum(case
DECODE(backup_type when d.controlfile_included
(select o.session_recid, o.session_stamp,= 'YES' then d.pieces
min(inst_id) else 0 end) CF,
inst_id
sum(case when
from GV$RMAN_OUTPUT
, 'L', 'Archived d.controlfile_included
Redo Logs' o = 'NO'
group by
, 'D', 'Datafile and d.backup_type||d.incremental_level
o.session_recid,
Full 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
SQL> insert into tables using the DBA_TABLES view
MANA.TAXINQUIRY_LOG_REPAIR shows* that
( select fromSKIP_CORRUPT
is enabled for table scott.dept.
MANA.TAXINQUIRY_LOG );
68 rows created.
SELECT
SQL> OWNER, TABLE_NAME, SKIP_CORRUPT FROM DBA_TABLES
commit;
WHERE
Commit OWNER = 'SCOTT';
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

Master Note for Handling Oracle Database Corruption Issues (Doc ID 1088018.1)

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
AND
dbi.dbinc_key
ts.ts# = df.ts#
bdf.dbinc_key
= df.dbinc_key
= df.dbinc_key
v121.ts,
AND bdf.dbinc_key
AND
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
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:
ase Corruption Issues (Doc ID 1088018.1)

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;


EXP , How long will it take ?

copy one table from one db to another

Estimate Dumpfile Size

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


ORA-27054: NFS file system where the file is created or
resides is not mounted with correct options

Export the table from previous time

user privs for impdp


what expdp/impdp actualy executing

schema backup

Scan the table using exp without taking dumpfile

DBA _resumable

Querying V$SESSION_LONGOPS & V$SESSION views

Querying V$SESSION_LONGOPS & V$DATAPUMP_JOB


Querying all the related views with a single query:-
begin
col job_mode for a30
dbms_metadata.set_transform_param (dbms_metadata.session_transform, 'SQLTERMINATOR', true);
dbms_metadata.set_transform_param
SELECT x.job_name, (dbms_metadata.session_transform, 'PRETTY', true);
end;b.state,
/-- b.degree,
-- x.owner_name,
variable
-- v_username VARCHAR2(30);
z.sql_text,
p.MESSAGE,
exec:v_username
p.totalwork, := upper('&1');
p.sofar,
select dbms_metadata.get_ddl('USER',
ROUND u.username)
( (p.sofar / p.totalwork) * 100, 2) done, AS ddl
fromp.time_remaining
dba_users u
where
FROMu.username = :v_username
dba_datapump_jobs b
unionLEFTall JOIN dba_datapump_sessions x ON (x.job_name = b.job_name)
select dbms_metadata.get_granted_ddl('TABLESPACE_QUOTA',
LEFT JOIN v$session y ON (y.saddr = x.saddr) tq.username) AS ddl
fromLEFT dba_ts_quotas
JOIN v$sql tq z ON (y.sql_id = z.sql_id)
where LEFTtq.username = :v_username p ON (p.sql_id = y.sql_id)
JOIN v$session_longops
and rownum = 1
WHERE y.module = 'Data Pump Worker' AND p.time_remaining > 0;
union all
select dbms_metadata.get_granted_ddl('ROLE_GRANT', rp.grantee) AS ddl
set
fromarraysize 1000
dba_role_privs rp
copy from
where username/passwd@source_connect_string
rp.grantee = :v_username to username/passwd@target_connect_string insert
table_target
and rownum using
= 1 select * from table_source;
union all
select dbms_metadata.get_granted_ddl('SYSTEM_GRANT', sp.grantee) AS ddl
from
Suppose dba_sys_privs sp then
if the table exists
where sp.grantee = :v_username
COPY FROM username1/passwd1@PROD to username2/passwd2@SANDBOX
and rownum
INSERT =1
TABLE_C (*) USING (SELECT * FROM TABLE_C WHERE COL_A = 4884);
union all
select dbms_metadata.get_granted_ddl('OBJECT_GRANT', tp.grantee) AS ddl
from
expdpdba_tab_privs
system/*******tp SCHEMAS=CMX_ORS NOLOGFILE=y ESTIMATE_ONLY=y DIRECTORY=tmp_pump_dir
where tp.grantee = :v_username
and rownum = 1
union all
alter session set current_schema=CMFP;
select
select dbms_metadata.get_granted_ddl('DEFAULT_ROLE', rp.grantee)
'alter table '||a.owner||'.'||a.table_name||' disable constraint AS ddl
'||a.constraint_name||';'
from fromdba_role_privs
all_constraintsrpa, all_constraints b
wherewhere rp.grantee = :v_username
a.constraint_type = 'R'
and rp.default_role
and a.r_constraint_name = 'YES'= b.constraint_name
and andrownum
a.r_owner = 1 = b.owner
union all
and b.table_name = 'CMFP_HRCHY';
select to_clob('/* Start profile creation script in case they are missing') AS ddl
from dba_users u
ALTER SYSTEM SET EVENTS '10298 trace name context forever, level 32';
where u.username = :v_username
and u.profile <> 'DEFAULT'
and rownum = 1
exp
union system/*****
all tables=schema.table_name file=exp_ix_str_store.dmp log=exp_ix_str_store.log query=\"where DBTIME\<to_
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 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;

expdp
userid='/ as sysdba'
nohup expdp parfile=/dbexports/EXP/dbname/schemaexpdp.par &
dumpfile=WRNAME_exp_dbname_SCOTT.dmp
logfile=WRNAME_exp_w665pr_SCOTT.log
schemas=SCOTT
compression=all
directory=DATA_PUMP_DIR

exp tables=<XXX> file=/dev/null log=/tmp/export.log statistics=none volsize=0

select * from dba_resumable;

SELECT b.username, a.sid, b.opname, b.target,


round(b.SOFAR*100/b.TOTALWORK,0) || '%' as "%DONE", b.TIME_REMAINING,
to_char(b.start_time,'YYYY/MM/DD HH24:MI:SS') start_time
FROM v$session_longops b, v$session a
WHERE a.sid = b.sid ORDER BY 6;

SELECT sl.sid, sl.serial#, sl.sofar, sl.totalwork, dp.owner_name, dp.state, dp.job_mode


FROM v$session_longops sl, v$datapump_job dp
WHERE sl.opname = dp.job_name
AND sl.sofar != sl.totalwork;
select x.job_name,b.state,b.job_mode,b.degree
, x.owner_name,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'
AND p.time_remaining > 0;
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);

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

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

Schema imp dp important


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;
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

DDL of all users ( Except schema )


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

Source code of all invalid objects

create scripts of all tables of a particular schema

GET_DEPENDENT_DDL
http://www.orafaq.com/node/807

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

set long 2000


select
select to_char(last_ddl_time,'DD-MON-YYYY
(case HH24:MI:SS') from dba_objects where owner='&user' and object_name='&ta
set long 20000 longchunksize
when ((select count(*) 20000 pagesize 0 linesize 1000
SELECT DBMS_METADATA.GET_DDL('&OBJECT_TYPE','&OBJECT_NAME','&OWNER')
from dba_users AAA FROM DUAL;
where username = 'ODB') > 0)
set pagesize 0 echo off timing off linesize 1000 trimspool on trim on long 2000000 longchunksize 2000000
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')
else to_clob (' -- Note: No TS Quotas found!')
selectLONG
SET 'CREATE 1000SEQUENCE '||SEQUENCE_NAME||chr(10)||
end ) from dual
'SELECT
INCREMENT BY '||INCREMENT_BY||chr(10)||
DBMS_METADATA.GET_DDL('DB_LINK',db.db_link,db.owner) from dba_db_links db;
UNION
' STARTALLWITH '||LAST_NUMBER||chr(10)||
select (case '||MIN_VALUE||chr(10)||
' MINVALUE
when ((select count(*)
' MAXVALUE '||MAX_VALUE||chr(10)||
from dba_role_privs
decode(CYCLE_FLAG,'N',' NOCYCLE','CICLE')||chr(10)||
where grantee = 'ODB') > 0)
decode(ORDER_FLAG,'N',' NOORDER','ORDER')||chr(10)||
then dbms_metadata.get_granted_ddl ('ROLE_GRANT', 'ODB')
' CACHE '||CACHE_SIZE|| ';'
else to_clob (' -- Note: No granted Roles found!')
from DBA_SEQUENCES where SEQUENCE_OWNER='&OWNER_NAME';
end ) from dual
UNION ALL
select (case
when ((select count(*)
select 'select
fromdbms_metadata.get_ddl(''TABLESPACE'','''||
dba_sys_privs tablespace_name || ''') from dual;' from dba_tablespaces;
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
/

set long 20000 longchunksize 20000 pagesize 0 linesize 1000


select dbms_metadata.get_ddl('USER',username) FROM dba_users where username not in ( select owner from dba_o
username like 'A%';
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||'''');
set long 20000
execute longchunksize
immediate 20000 pagesize
('ALTER PROFILE 0 linesize 1000 feedback
"FUNCTIONAL_USER" LIMIT off verify off trimspool on
column ddl format a1000
PASSWORD_VERIFY_FUNCTION PASSWDCOMPLEXVERIFICATION');

begin
end;
/ dbms_metadata.set_transform_param (dbms_metadata.session_transform, 'SQLTERMINATOR', true);
dbms_metadata.set_transform_param (dbms_metadata.session_transform, 'PRETTY', true);
end;
SQL> ALTER PROFILE FUNCTIONAL_USER LIMIT PASSWORD_VERIFY_FUNCTION NULL;
/Profile altered.
SQL> alter user trial identified by test;
variable v_role VARCHAR2(30);
User altered.
SQL> conn trial/test;
exec
ALTER :v_role := upper('&1');
PROFILE "FUNCTIONAL_USER" LIMIT PASSWORD_VERIFY_FUNCTION PASSWDCOMPLEXVERIFICATION

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


from dba_roles r
where r.role = :v_role
union all
select dbms_metadata.get_granted_ddl('ROLE_GRANT', rp.grantee) AS ddl
from dba_role_privs rp
where rp.grantee = :v_role
and rownum = 1
union
select all
' alter user '||username||' profile '||PROFILE||';' from dba_users;
select dbms_metadata.get_granted_ddl('SYSTEM_GRANT', sp.grantee) AS ddl
from dba_sys_privs sp
where sp.grantee = :v_role
and rownum = 1
union all
select dbms_metadata.get_granted_ddl('OBJECT_GRANT', tp.grantee) AS ddl
from dba_tab_privs tp
where tp.grantee = :v_role
and rownum = 1
/

set linesize 80 pagesize 14 feedback on verify on


select 'grant select,insert,update,delete on ' || a.owner || '."' ||
a.table_name || '"' || CHR(10) ||
' to L2_SUPPORT;' || CHR(10) ||
'grant select on ' || a.owner || '."' ||
a.table_name || '"' || CHR(10) ||
SELECT grantee || ' Through
' to L1_SUPPORT;' || CHR(10) role '|||| granted_role ge, 'SELECT' priv
FROM dba_role_privs
'grant select on ' || a.owner || '."' ||
START WITH granted_role
a.table_name IN (SELECT
|| '"' || CHR(10) || grantee
' to L3_SUPPORT;' FROM dba_tab_privs
from dba_tables aWHERE PRIVILEGE = 'SELECT')
CONNECT
where owner BY inPRIOR grantee = granted_role
('SCHEMA_NAME')
UNION
order by owner, table_name;
SELECT grantee || ' Through role ' || granted_role ge, 'UPDATE' priv
FROM dba_role_privs
START
spool offWITH granted_role IN (SELECT grantee
FROM dba_tab_privs
set feedback on WHERE PRIVILEGE = 'UPDATE')
CONNECT BY PRIOR grantee = granted_role
UNION
DB link : devgrantee
SELECT to prod|| ' Through role ' || granted_role ge, 'INSERT' priv
FROM dba_role_privs
CREATE
START DATABASE
WITH granted_roleLINK IN "COMPARE"
(SELECT granteeCONNECT TO DBSNMP IDENTIFIED BY mypwd USING 'destonation-db-name';
select * from DBA_TAB_PRIVS@compare
FROM dba_tab_privs T1 where not exists (select 1 from dba_tab_privs T2 where t1.TABLE_NAME=
t1.PRIVILEGE=t2.PRIVILEGEWHERE PRIVILEGE and t1.GRANTEE=t2.GRANTEE
= 'INSERT') ) and t1.grantee='&ROLE_NAME';
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 GRANTEE
CONNECT 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 '||granted_role||'IN (SELECT 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 * FROM USER_ROLE_PRIVS;
'WKPROXY',
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' ,
'SPATIAL_CSW_ADMIN_USR' ,
SELECT NAME, TO_CHAR (ptime, 'DD-MON-YYYY HH24:MI:SS') AS "LAST TIME CHANGED", ctime "CREATION TIME"
'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;

SELECT DBMS_METADATA.GET_DDL(db.OBJECT_TYPE,db.OBJECT_NAME,db.OWNER)|| '/' from dba_objects db whe


SELECT DBMS_METADATA.GET_DDL('PACKAGE_BODY',db.OBJECT_NAME,'db.owner')|| '/' from dba_objects db wher
object_type='PACKAGE BODY';
SELECT DBMS_METADATA.GET_DDL(db.OBJECT_TYPE,db.OBJECT_NAME,db.OWNER)|| '/' from dba_objects db whe
object_type not like '%PACKAGE%';

select 'select dbms_metadata.get_ddl(''TABLE'', '''||TABLE_NAME||''',''<schema>'') from dual;' FROM DBA_TABLES;

SELECT DBMS_METADATA.GET_DEPENDENT_DDL('REF_CONSTRAINT','<table_name>','<schema>') from dual;


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',
'EXPIRED', ' password expire',
'EXPIRED and LOCKED', ' account lock password
expire',
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 || '.' ||TABLE_NAME
when
|| ' to '((select count(*)
|| 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);
http://tech.padipa.net/generating-create-scripts-through-dbms_metadata-package
select dbms_metadata.get_ddl('USER', u.username) AS ddl select
from dba_users u dbms_me
where u.username = :v_username tadata.get
union all _ddl('USE
select dbms_metadata.get_granted_ddl('TABLESPACE_QUOTA', R',
tq.username) AS ddl 'KPHU00
from dba_ts_quotas tq 0') || '/'
where tq.username = :v_username
1_QUESTION_ID:494205100346718343 usercreat
and rownum = 1 e from
union all dual;
select dbms_metadata.get_granted_ddl('ROLE_GRANT', SELECT
rp.grantee) AS ddl DBMS_M
from dba_role_privs rp ETADATA
where rp.grantee = :v_username .GET_GR
and rownum = 1 ANTED_
union all DDL('RO
select dbms_metadata.get_granted_ddl('SYSTEM_GRANT', LE_GRA
sp.grantee) AS ddl NT','KPH
from dba_sys_privs sp U000') ||
where sp.grantee = :v_username '/' FROM
and rownum = 1 DUAL;
union all SELECT
select dbms_metadata.get_granted_ddl('OBJECT_GRANT', DBMS_M
tp.grantee) AS ddl ETADATA
from dba_tab_privs tp .GET_GR
where tp.grantee = :v_username ANTED_
and rownum = 1 DDL('SY
union all STEM_G
select dbms_metadata.get_granted_ddl('DEFAULT_ROLE', RANT','K
rp.grantee) AS ddl PHU000')
from dba_role_privs rp || '/'
where rp.grantee = :v_username FROM
and rp.default_role = 'YES' DUAL;
and rownum = 1 SELECT
union all DBMS_M
select to_clob('/* Start profile creation script in case they are ETADATA
missing') AS ddl .GET_GR
from dba_users u ANTED_
where u.username = :v_username DDL('OBJ
and u.profile <> 'DEFAULT' ECT_GR
and rownum = 1 ANT','KP
union all HU000') ||
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 ETADATA
select to_clob('End profile creation script */') AS ddl .GET_GR
from dba_users u ANTED_
where u.username = :v_username DDL('TAB
and u.profile <> 'DEFAULT' LESPAC
and rownum = 1 E_QUOT
/ A',
'KPHU00
set linesize 80 pagesize 14 feedback on trimspool on verify on 0') '/' from
dual;
-dbms_metadata-package
try this

Find locked Object

To find who is accessing the particular Table

Who is accessing the object

What a sid executed (sql_text of blocker )

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'
, 1, 'Null'
, 2, 'Row-S (SS)'
, 3, 'Row-X (SX)'
, 4, 'Share'
,https://github.com/gwenshap/Oracle-DBA-Scripts/blob/master/locks.sql
5, 'S/Row-X (SSX)'
, 6, 'Exclusive', TO_CHAR(lmode)) mode_held
SELECT
from t1.sid SID, s.username,
v$locked_object v s.osuser, s.program,
s.machine,
, dba_objects d o.object_name, t1.ctime
FROM
, v$lock l
v$ACCESS
, v$session s A,
v$LOCK
where T1,
v.object_id = d.object_id
v$SESSION
and S,
v.object_id = l.id1
select
and sn.USERNAME,
DBA_OBJECTS v.session_idO = s.sid
m.SID,
WHERE
order by oracle_username
,sn.SERIAL#,
t1.TYPE='TM'
session_id;
m.TYPE,
AND A.SID = S.SID
decode(LMODE,
AND T1.sid = s.sid
AND 0, 'None',
T1.id1 = o.object_id
AND 1, 'Null',
A.OBJECT LIKE 'TABLE_NAME'||'%'
2, 'Row-S
select
ORDER BY(SS)',
b.status,a.INST_ID,a.SID,OWNER,OBJECT,a.TYPE
T1.sid, T1.ctime; from gv$access
a,3,gv$session
'Row-X (SX)', b
4, 'Share',
where a.object='&object_name'
SELECT
and 5, 'S/Row-X o.inst_id,o.sid,
a.sid=b.sid (SSX)',
and o.sql_text, lock_type,
6, 'Exclusive')
a.inst_id=b.inst_id
order o.address,
decode(REQUEST,
by 1,2;
set o.hash_value,
lines 750 pages 9999
0, 'None',
col
All 1,sql o.user_name,
blocking_status
executed by aforsid
'Null', a100
select s.schemaname,
2, 'Row-S s1.inst_id,s2.inst_id,s1.username
(SS)', || '@' || s1.machine
o.sql_id
||3,' ('Row-X
SID=' ||(SX)',
s1.sid || ' ) is blocking '
||FROM
4,s2.username
'Share',gv$open_cursor o, gv$session
|| '@' || s2.machine || ' ( sSID=' || s2.sid || ' ) ' AS
WHERE
blocking_status o.saddr
5, 'S/Row-X (SSX)', , = s.saddr AND o.sid = s.sid ANDmins'
round(s2.seconds_in_wait/60)||' (O.SID = &sid)
Blocking_mins
and
from o.inst_id=s.inst_id;
gv$lock l1, gv$session
6, 'Exclusive') lock_requested, s1, gv$lock l2, gv$session s2
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
gv$lock.type
t.SQL_TEXTl1.id1 = l2.id1
FROM
fromand l2.id2
v$session= l2.id2
gv$lock join
sn, gv$session on gv$lock.sid=gv$session.sid and
order byms1.inst_id;
gv$lock.inst_id=gv$session.inst_id
v$lock ,
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
sn.SQL_HASH_VALUE = do.OBJECT_ID
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 LMODE request>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;
b.session_id AS sid,
NVL(b.oracle_username, '(oracle)') AS username,
select OS_USER_NAME
a.owner AS object_owner, os_user,
PROCESS os_pid,
a.object_name,
ORACLE_USERNAME
Decode(b.locked_mode, oracle_user,
0, 'None',
l.SID oracle_id, 1, 'Null (NULL)', SELECT DECODE(request,0,'Holder: ','Waiter: ') ||
decode(TYPE, 2, 'Row-S (SS)', gv$lock.sid sess, machine, do.object_name as
'MR', 'Media Recovery', 3, 'Row-X (SX)', locked_object,id1, id2, lmode, request, gv$lock.type
'RT', 'Redo Thread', 4, 'Share (S)', FROM gv$lock join gv$session on
'UN', 'User Name', 5, 'S/Row-X (SSX)', gv$lock.sid=gv$session.sid and
'TX', 'Transaction', 6, 'Exclusive (X)', gv$lock.inst_id=gv$session.inst_id
'TM', 'DML', b.locked_mode) locked_mode, join gv$locked_object lo on gv$lock.SID =
'UL', 'PL/SQL User Lock',
b.os_user_name lo.SESSION_ID and gv$lock.inst_id=lo.inst_id
'DX', 'Distributed Xaction',
FROM dba_objects a, join dba_objects do on lo.OBJECT_ID =
'CF', 'Control File',
gv$locked_object b do.OBJECT_ID
'IS', 'Instance State',= b.object_id
WHERE a.object_id WHERE (id1, id2, gv$lock.type) IN (
'FS', 'File Set',
ORDER BY 1, 2, 3, 4 SELECT id1, id2, type FROM gv$lock WHERE
/ 'IR', 'Instance Recovery', request>0)
'ST', 'Disk Space Transaction', ORDER BY id1, request;
'TS', 'Temp Segment',
'IV', 'Library Cache Invalidation',
'LS', 'Log Start or Switch',
set'RW',lines 750Wait',
'Row pages 9999
col blocking_status
'SQ', 'Sequence Number', for a100
SELECT s1.inst_id,s2.inst_id,
'TE', 'Extend Table', 'Instance '||s1.INST_ID||'
'||'TT',
s1.username
'Temp Table', type) lock_type,|| ' ( SID=' || s1.sid
|| '@' || s1.machine
||decode(LMODE,
','|| s1.serial#||' '||s1.status|| ','||s1.sql_id||' ) select sid as waiting_sid, sql_text as waiting_sql
is0,blocking
'None', '|| s2.username || '@' || s2.machine || ' from (select s.sid, txt.sql_text
(select
SID='
1, sid
'Null', as blocker_sid,
|| s2.sid sql_text
|| ' ) '||s2.sql_id as blocker_sql
||' since '|| from gv$sqltext txt, gv$session s, gv$lock lb,
from (select s.sid,
round(s2.seconds_in_wait/60)||'
2, 'Row-S (SS)', txt.sql_text mins' as gv$lock lw
blocker_sql
from
blocking_sessions
3, 'Row-X gv$sqltext
(SX)', txt, gv$session s, gv$lock l where txt.address = s.sql_address
waiting_sql
FROM where
4, 'Share', gv$lock txt.address
l1, gv$session = s.sql_address
s1, gv$lock l2, and s.sid = lw.sid
gv$session and s.sid
5, 'S/Row-X = l.sid
s2(SSX)', and lw.id1 = lb.id1
WHERE
6, and l.block
'Exclusive', = 1 lock_held,
s1.sid=l1.sid
lmode) AND SELECT and lb.block = 1
order by
s1.inst_id=l1.inst_id
decode(REQUEST, s.sid, txt.piece);
AND l1.sidand lw.request
|| ' is blocking >' ||0l2.sid blocking_sessions
0,s2.sid=l2.sid
'None', AND FROMorder by s.sid, txt.piece);
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 = l2.id2
5, 'S/Row-X (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


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

SELECT

s.blocking
_session,
s.sid,

s.serial#,

s.second
s_in_wait
FROM

v$session
s
WHERE

blocking_
session
IS NOT
NULL
https://github.com/gwenshap/Oracle-DBA-Scripts/blob/master/locks.sqlhttp://www.oracle-ckpt.com/scripts-for-locks-and-blockin
;
Trace enable

Trace disable

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


Check active events in oracle database

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


10132 Trace

Check this

parallel session trace

How to dump ASH info to file when db is hang


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

ALTER SESSION SET EVENTS '10046 TRACE NAME CONTEXT FOREVER, LEVEL 12';
-or-
EXEC SYS.DBMS_SYSTEM.SET_EV(SID,SERIAL#,10046,12,'');
-or-
EXEC SYS.DBMS_SUPPORT.START_TRACE_IN_SESSION(SID,SERIAL#,WAITS=>TRUE,BINDS=>FALSE);
-or-
EXEC DBMS_MONITOR.SESSION_TRACE_ENABLE(SESSION_ID=>SID,SERIAL_NUM=>SERIAL#,WAITS=>TRUE,BIND
-or-
EXEC SYS.DBMS_SYSTEM.SET_SQL_TRACE_IN_SESSION(SID,SERIAL#,TRUE);

ALTER SESSION SET EVENTS '10046 TRACE NAME CONTEXT OFF';


-or-
EXEC SYS.DBMS_SYSTEM.SET_EV(SID,SERIAL#,10046,0,'');
-or-
EXEC SYS.DBMS_SUPPORT.STOP_TRACE_IN_SESSION(SID,SERIAL#);
-or-
EXEC SYS.DBMS_SYSTEM.SET_SQL_TRACE_IN_SESSION(SID,SERIAL#,FALSE);

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=>true,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'; (OR)
alter system set events 'sql_trace[sql: cjrha4bzuupzf] level=12';

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


declare
event_level number;
begin
for i in 10000..10999 loop
sys.dbms_system.read_ev(i,event_level);
if (event_level > 0) then
dbms_output.put_line('Event '||to_char(i)||' set at level '|| to_char(event_level));
end if;
end loop;
end;
/

create or replace trigger sqltrace


after logon on database
begin
if user='XXXXX'
then
execute immediate 'alter session set events ''10046 trace name context forever, level 4''';
end if;
end;
/

ALTER SYSTEM SET sql_trace = true SCOPE=MEMORY;


ALTER SYSTEM SET sql_trace = false SCOPE=MEMORY;

$ tkprof orcl102_ora_3064.trc output.prf EXPLAIN=scott/tiger SYS=NO


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

$ ps -ef| egrep '4711|4713'


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

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


SQL> col spid for a8
SQL> col username for a20
SQL> col osuser for a20
1 select s.sid,s.serial#,p.spid,p.pid,s.username,s.osuser
2 from v$session s,v$process p
3* where s.paddr=p.addr
SQL> /
strace -fF -v -p 16311 -o output.txt
strace
SID/oracle/product/10.2.0.1/bin/sqlplus
SERIAL# SPID PID USERNAME -V 2>&1 |lessOSUSER
------- ------- -------- ---------- -------------------- --------------------
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 c
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
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;

SQL> oradebug setmypid


SQL> oradebug dump ashdump 5 — This will dump last 5 minute content
SQL> oradebug tracefile_name
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://blog.dbi-services.com/enable-10046-tracing-for-a-specific-sql/
https://avdeo.com/tag/sql-tuning/
https://oracle-base.com/articles/misc/sql-trace-10046-trcsess-and-tkprof
http://www.juliandyke.com/Diagnostics/Trace/EnablingTrace.php
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
SQL> set define #
SQL> column spid new_value unix_pid
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
for linux

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
select distinct sid OwnSID from v$mystat;
BEGIN
for c in (select s.sid sid,
s.serial# serial
from v$session s
where s.USERNAME = 'ASAP' and
s.status = ’ACTIVE’)
loop
dbms_support.start_trace_in_session(c.sid, c.serial);
end loop;
END;

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
Invalid Objects

Details of a object

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

all Indexes for a table

Find Table_name from index_name


Disable Trigger

Disable constraint

Disable constraints

Dependency Objects

count of columns of a table in a schema


dependent objects

ORA-02292: integrity constraint (OWNER.CONSTRAINT_NAME)


violated - child record found

BLOB/CLOB Objects tables in db

Find duplicate records in a column

Source code of all invalid objects

Dblinks

Select * from dba_db_links;

Drop Private db link

Rebuild / Fragmentation
Indexes requires rebuild
Rebuild Indexes

Index fragmentation

Index fragmentation other way


Unused indexes

Tables requires rebuild

TABLE Fragmentation / All Tables

re-organizing table
select 'alter '||object_type||' '||owner||'."'||object_name||'" compile;'
from dba_objects
where status<>'VALID'
and object_type not in ('PACKAGE BODY','TYPE BODY','UNDEFINED','JAVA CLASS','SYNONYM')
union
select 'alter package '||owner||'.'||object_name||' compile body;'
from dba_objects
where status<>'VALID'
and object_type='PACKAGE BODY'
union
select 'alter type '||owner||'.'||object_name||' compile body;'
selectdba_objects
from owner, object_type, substr(object_name,1,30) object_name, status
from dba_objects
where where status='INVALID' order by object_type;
status<>'VALID'
and object_type='TYPE BODY'
union
set lines 1000 pages 9999
select 'alter materialized
col object_name for a50 view '||owner||'.'||object_name||' compile;'
from
col ownerdba_objects
for a30
where status<>'VALID'
col object_type for a30
and object_type='UNDEFINED'
col STATUS for a30
union
select owner,object_name,object_type,CREATED,STATUS,TO_CHAR(LAST_DDL_TIME,'dd-mon-yyyy
select 'alter java
hh24:mi:ss') class '||owner||'."'||object_name||'"
AS LAST_DDL_TIME from dba_objectsresolve;'
where object_name in
from dba_objects
('&OBJECT_NAME1','&OBJECT_NAME2','&OBJECT_NAME3');
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’)
) for a30
col owner
count
col index_name for a30
colfrom user_tables
table_name order by table_name;
for a30
col column_name for a30
select
owner,b.uniqueness, a.index_name, a.table_name, a.column_name
from dba_ind_columns a, dba_indexes b
where a.index_name=b.index_name
and b.owner='&OWNER'
and a.table_name = upper('&TABLE_NAME')
order by a.table_name, a.index_name, a.column_position;

col owner for a30


col index_name for a30
col table_name for a30
col column_name for a30
select owner,b.uniqueness, a.index_name, a.table_name, a.column_name
from dba_ind_columns a, dba_indexes b
where a.index_name=b.index_name
and b.owner='&OWNER'
and b.index_name = upper('&INDEX_NAME')
order by a.table_name, a.index_name, a.column_position;
select 'ALTER TRIGGER '||OWNER||'.'||TRIGGER_NAME||' DISABLE '||';' from dba_triggers where table_name in ('&TABLE_N

select 'ALTER TABLE '||OWNER||'.'||TABLE_NAME||' DISABLE CONSTRAINT '||CONSTRAINT_NAME ||';' from dba_constrain

SELECT
'ALTER TABLE '||OWNER||'.'||
TABLE_NAME||' '||var_action||' CONSTRAINT '||CONSTRAINT_NAME AS sql_string,
CONSTRAINT_NAME
FROM
ALL_CONSTRAINTS
WHERE
CONSTRAINT_TYPE='R' AND OWNER=Target_Schema_Name;

select name, type, owner


from all_dependencies
colwhere
ownerreferenced_owner
for a30 = 'USER_NAME'
and referenced_name
col table_name for a50 = 'OBJECT_NAME';
select t.owner, t.table_name, t.num_rows, count(*)
from dba_tables t left join dba_tab_columns c on t.table_name = c.table_name
where t.owner='&OWNER_NAME' and num_rows is not null
group by t.owner, t.table_name, t.num_rows
order by count(*) desc;
|| '.'
|| REFERENCED_NAME AS DEPENDENCIES
FROM dba_dependencies
WHERE referenced_name = UPPER(LTRIM(RTRIM( '&ls_REF_name' )))
OR name = UPPER(LTRIM(RTRIM( '&ls_REF_name' )))
AND (REFERENCED_OWNER <> 'SYS'
AND REFERENCED_OWNER <> 'SYSTEM'
AND REFERENCED_OWNER <> 'PUBLIC')
AND (OWNER <> 'SYS'
AND OWNER <> 'SYSTEM'
set
AND lines 750 pages 999
OWNER
set serveroutput
col owner for1a30 on <> 'PUBLIC' )
ORDER
DECLARE
SELECT BY
owner, ; constraint_name, constraint_type, table_name, r_owner, r_constraint_name
col table_name for a50
l_sql
col FROM CLOB := for a50
all_constraints
column_name
'CREATE
WHERE PROCEDURE
owner='&OWNER'
col data_type for a30 <OWNER>.drop_db_links_prc
ISAND constraint_name='&CONSTRAINT_NAME';
SELECT OWNER, TABLE_NAME, COLUMN_NAME, DATA_TYPE
FROMBEGIN dba_tab_columns
WHERE FOR DATA_TYPE
i IN (SELECTIN * FROM user_db_links)
('CLOB', 'BLOB' , 'LOB', 'BFILE','NCLOB') and owner not in
LOOP
('SYS','SYSTEM','CTXSYS','WMSYS','XDB','OUTLN') order by 1,2;
selectdbms_output.put_line(''to
column_name, count(column_name)
drop ''||i.db_link);
from EXECUTE
table IMMEDIATE ''DROP DATABASE LINK ''||i.db_link;
group END by LOOP;
column_name
having
END;'; count (column_name) > 1;
l_sql1 clob;
BEGIN
FOR i inDBMS_METADATA.GET_DDL(db.OBJECT_TYPE,db.OBJECT_NAME,db.OWNER)||
SELECT (SELECT DISTINCT owner '/' from dba_objects db where s
FROM dba_objects
WHERE owner IN ('TOMASZ')
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 object_id into oid from dba_objects where object_type='INDEX' and owner=o and object_name=i;
/* Note:10640.1: block header size = fixed header (113 bytes) + variable transaction header (23*initrans)
*/
select nvl(to_char(block_size - 113 - ini_trans*23),'null') header_size into hsz
from dba_indexes left outer join dba_tablespaces using (tablespace_name) where owner=o and
index_name=i;
for c in cols loop
if ( c.column_position > 1 ) then k_lst:=k_lst||',' ; k_min:=k_min||',';k_max:=k_max||','; k_nul:=k_nul||' and '
; k_vsz:=k_vsz||'+' ; end if;
k_lst:=k_lst||c.column_name;
k_nul:=k_nul||c.column_name|| ' is not null';
k_min:=k_min||'min('||c.column_name||')
select '||c.column_name;
a.*, round(index_leaf_estimate_if_rebuilt/current_leaf_blocks*100) percent, case when
k_max:=k_max||'max('||c.column_name||')
index_leaf_estimate_if_rebuilt/current_leaf_blocks '||c.column_name;
< 0.5 then 'candidate for rebuild' end status
k_vsz:=k_vsz||'nvl(vsize('||c.column_name||'),1)+'||c.length_bytes;
from
( end loop;
if p != 100 then p_sam:='sample
select table_name, block('||p||')'; end if; round (100 / 90 * (ind_num_rows * (rowid_length +
index_name, current_leaf_blocks,
add('with leaf_blocks as (',0);
uniq_ind + 4) + sum((avg_col_len) * (tab_num_rows) ) ) / (8192 - 192) ) as index_leaf_estimate_if_rebuilt
add('select
from ( /* cursor_sharing_exact dynamic_sampling(0) no_monitoring',1);
add(' no_expand
select tab.table_name, index_ffs('||t||','||i||')
tab.num_rowsnoparallel_index('||t||','||i||') */',10);
tab_num_rows , decode(tab.partitioned,'YES',10,6) rowid_length ,
add(k_min||','||1/(p/100)||'*count(rowid) num_rows',1);
ind.index_name, ind.index_type, ind.num_rows ind_num_rows, ind.leaf_blocks as current_leaf_blocks,
add(','||1/(p/100)||'*sum(1+vsize(rowid)+'||k_vsz||')
decode(uniqueness,'UNIQUE',0,1) vsize',1); as ind_column_name, tc.column_name ,
uniq_ind,ic.column_name
add('from
tc.avg_col_len '||o||'.'||t||' '||p_sam||' '||t,1);
add('where
from dba_tables '||k_nul,1);
tab
add('group
join dba_indexes by sys_op_lbid('||oid||',''L'',rowid)',1);
ind on ind.owner=tab.owner and ind.table_name=tab.table_name
add('),keys
join as (',0); ic on ic.table_owner=tab.owner and ic.table_name=tab.table_name and
dba_ind_columns
add('select ntile('||n||') overand
ic.index_owner=tab.owner (order by '||k_lst||') bucket,',1);
ic.index_name=ind.index_name
add(k_min||',',2);
join dba_tab_columns tc on tc.owner=tab.owner and tc.table_name=tab.table_name and
add('count(*) leaf_blocks, count(*)*'||hsz||' tsize,',2);
tc.column_name=ic.column_name
add('sum(num_rows)
where tab.owner='&OWNER' num_rows,sum(vsize)
and ind.leaf_blocks vsize',2);
is not null and ind.leaf_blocks > 1000
add('from leaf_blocks group by '||k_lst,1);
) group by table_name, index_name, current_leaf_blocks, ind_num_rows, uniq_ind, rowid_length
)add(')',0);
a where index_leaf_estimate_if_rebuilt/current_leaf_blocks < 0.5
add('select
order '||k_min||',''->'' "->",'||k_max||',round(sum(num_rows)/sum(leaf_blocks)) "rows/block"',0);
by index_leaf_estimate_if_rebuilt/current_leaf_blocks;
add(',round(sum(vsize)/sum(leaf_blocks)) "bytes/block",',1);
add('case when sum(vsize)<=sum(tsize) then 100*round(1- sum(vsize) / (sum(tsize)),2) else null end
SELECT ' alter index ' || owner || '.' || index_name || ' rebuild ; ' FROM dba_indexes where owner not in ('SYS','SYSTEM');
"%free space",',1);
add(' sum(leaf_blocks) "blocks",');
--add('case when sum(vsize)<=sum(tsize)/2 then substr(rpad(''o'',5*round(1- sum(vsize) /
(sum(tsize)),2),''o''),1,5) end "free"',1);
add('substr(rpad(''o'',5*round(1- sum(vsize) / (sum(tsize)),2),''o''),1,5) "free"',1);
add('from keys group by bucket order by bucket',0);
begin open :c for s ; exception when others then dbms_output.put_line(s); raise; end ;
dbms_output.put_line(s);
end;
/
set termout on
print c

ANALYZE INDEX emp_id_idx VALIDATE STRUCTURE;


SELECT
name
, del_lf_rows
, lf_rows - del_lf_rows lf_rows_used
, TO_CHAR( del_lf_rows /(DECODE(lf_rows,0,0.01,lf_rows))*100,'999.99999') ibadness
FROM index_stats;
SELECT table_name, index_name
from user_indexes i
WhERE uniqueness <> 'UNIQUE'
AND
selectindex_name NOT IN
(sELECT DISTINCT object_name
‘exec analyzedb.reorg_a_table4(’||””||rtrim(t.table_owner)||””||’,'||””||
from v$sql_plan
rtrim(t.table_name)||””||’);’,
where operation LIKE '%INDEX%'
t.table_owner||’.'||t.table_name name,
AND object_owner='&OWNER');
a.num_rows,
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
whereanalyzedb.table_modifications
from owner='&OWNER' and table_name='&TABLE_NAME'
t, and
(round((blocks*8),2)
all_tables a > round((num_rows*avg_row_len/1024),2))
order
whereby 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 lines 750 pages 9999
col owner for a30
col object_name for a50
col object_type for a30
select 'select owner,object_name,object_type from dba_objects where object_name='''||
object_name ||''' and owner='''|| owner ||''';' from dba_objects where status='INVALID';

Set this below parameter if u want to run the compilation script in PDB

alter session set "_ORACLE_SCRIPT"=true;

Session altered.
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');
set serveroutput on size 1000000
DECLARE
CURSOR get_ts IS SELECT * FROM dba_tablespaces
WHERE tablespace_name != 'SYSTEM';
CURSOR get_df (p_ts VARCHAR2) IS
SELECT * from dba_data_files
WHERE tablespace_name = p_ts;
l_str VARCHAR2(10);
BEGIN
FOR ts_rec IN get_ts LOOP
dbms_output.put_line ('CREATE TABLESPACE '||ts_rec.tablespace_name);
-- For each tablespace loop through the datafiles
FOR df_rec IN get_df (ts_rec.tablespace_name) LOOP
IF get_df%ROWCOUNT = 1 THEN
l_str := 'DATAFILE';
ELSE
l_str := ',';
END IF;
dbms_output.put_line (l_str||' '
||chr(39)||df_rec.file_name||chr(39)
||' SIZE '||df_rec.bytes||' REUSE ');
if df_rec.autoextensible = 'YES' then
dbms_output.put_line (' AUTOEXTEND ON'
||' NEXT '||df_rec.increment_by );
if df_rec.maxbytes = 68719443968 then
dbms_output.put_line (' MAXSIZE UNLIMITED');
else
dbms_output.put_line (' MAXSIZE '||df_rec.maxbytes);
end if;
end if;
END LOOP;
/* Extent Management Clause */
dbms_output.put_line ('EXTENT MANAGEMENT ' ||ts_rec.extent_management );
if ts_rec.extent_management = 'LOCAL' then
if ts_rec.allocation_type = 'SYSTEM' then
dbms_output.put_line (' AUTOALLOCATE ');
here table_name in else('&TABLE_NAME1') and owner='&OWNER';
dbms_output.put_line (' UNIFORM SIZE '||ts_rec.initial_extent);
end if;
T_NAME ||';' from dba_constraints where table_name in ('&TABLE1') and owner='&OWNER';
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/

https://bommaritollc.com/2012/01/22/debugging-ora-02292-integrity-constraint-owner-constraint-violated-child-record-found/

| '/' from dba_objects db where status='INVALID';


er not in ('SYS','SYSTEM');

https://blog.dbi-services.com/how-i-measure-oracle-index-fragmentation/
Table size (with fragmentation)

SQL> select table_name,round((blocks*8),2)||'kb' "size"


from user_tables
where table_name = 'BIG1';

TABLE_NAME size
------------------------------ ------------------------------------------
BIG1 72952kb

Actual data in table:

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';
from user_tables
where table_name = 'BIG1';

TABLE_NAME size
------------------------------ ------------------------------------------
BIG1 30604.2kb

Note = 72952 - 30604 = 42348 Kb is wasted space in table


exec dbms_pdb.exec_as_oracle_script('alter package SYS.DBMS_METADATA compile body;');
SET ECHO ON SERVEROUTPUT ON SIZE 1000000
BEGIN
FOR cur_rec IN (SELECT object_type, owner,
object_name FROM dba_objects WHERE
owner='&OWNER' and object_type IN ('TABLE',
'VIEW', 'PACKAGE', 'PROCEDURE', 'FUNCTION',
'SEQUENCE','SYNONYM','TYPE')) LOOP
BEGIN
IF cur_rec.object_type = 'TABLE' THEN
EXECUTE IMMEDIATE 'DROP '||
cur_rec.object_type||' '||cur_rec.owner||'.'||
cur_rec.object_name||' CASCADE CONSTRAINTS';
ELSE
EXECUTE IMMEDIATE 'DROP '||
cur_rec.object_type||' '||cur_rec.owner||'.'||
cur_rec.object_name||' ';
END IF;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.put_line('FAILED: DROP '||
cur_rec.object_type||' '||cur_rec.owner||'.'||
cur_rec.object_name ||';');
END;
END LOOP;
END;
/
nt-owner-constraint-violated-child-record-found/
select
owner,table_name,blocks,num_rows,avg_row_len,rou
nd(((blocks*8/1024)),2) "TOTAL_SIZE( MB)",
round((num_rows*avg_row_len
/1024/1024),2) "ACTUAL_SIZE(MB)",
round(((blocks*8/1024)-
(num_rows*avg_row_len/1024/1024)),2)
"FRAGMENTED_SPACE(MB)" from
dba_tables where owner='&owner' and
table_name='&table_name' and
round(((blocks*8/1024)-
(num_rows*avg_row_len/1024/1024)),2) > 1 order by 8
desc;
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

Running Sql's

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

Undo Tablespace Advice

undo advisor
Monitoring undo segements

how long will that session take to finish rolling back?

Undo Not releasing the unexpired segments

TEMP
sort space usage by sesison

History of Temp tablespace usage

shrink tempfile
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
select sq.sql_text sql_text, t.USED_UREC Records,
TO_CHAR(s.sid)||','||TO_CHAR(s.serial#) t.USED_UBLK Blocks,
sid_serial,
(t.USED_UBLK*8192/1024) KBytes
NVL(s.username, 'None') orauser, from v$transaction t,
v$session
s.program, s,
v$sql sq undoseg,
r.name
where t.addr =* s.taddr
t.used_ublk TO_NUMBER(x.value)/1024/1024||'M' "Undo"
and
froms.sql_id = sq.sql_id
and s.username = '<user>'
sys.v_$rollname r,
/ sys.v_$session s,
sys.v_$transaction t,
colsys.v_$parameter
o format a10 x
where
col u format a10
s.taddr
select = t.addr
osuser o, username u, sid,
AND
segment_name s, substr(sa.sql_text,1,200) txt
r.usn
from = t.xidusn(+)
v$session s,
AND
v$transaction t,
x.name = 'db_block_size';
dba_rollback_segs r,
v$sqlarea sa
where s.taddr=t.addr
and t.xidusn=r.segment_id(+)
and s.sql_address=sa.address(+)
And substr(sa.sql_text,1,200) is not null
order by
select 3;
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;
select status,
round(sum_bytes / (1024*1024), 0) as MB,
round((sum_bytes / undo_size) * 100, 0) as PERC
from
(
select status, sum(bytes) sum_bytes
from dba_undo_extents
ALTER SYSTEM SET UNDO_SUPPRESS_ERRORS=TRUE scope=both;
group by status
),
(
prompt << Estimate the required UNDO_Size for the above retention
select sum(a.bytes)
>> undo_size
prompt << by this query:cselect
from dba_tablespaces
join v$tablespace b on b.name = c.tablespace_name
dbms_undo_adv.required_undo_size(<new_undo_retention>) new_undo_MB from dual
>>join v$datafile a on a.ts# = b.ts#
where c.contents = 'UNDO'
prompt
and c.status = 'ONLINE'
==================================================================
);
======================================
prompt
select status,TABLESPACE_NAME,sum(bytes) / 1024 / 1024 || 'MB' from
select max(maxquerylen)group
DBA_UNDO_EXTENTS as "maxquerylen",
by status,TABLESPACE_NAME;
dbms_undo_adv.required_undo_size(max(maxquerylen)) as "its required
UNDOTBS_n MB"
from gv$undostat
/

select dbms_undo_adv.required_retention as "required_retention",


dbms_undo_adv.required_undo_size(dbms_undo_adv.required_retention) as "its
required UNDOTBS_n MB"
from dual
/

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'
/
order by sid;

pause >>> wait a few seconds then press Enter...

col undo_records new_value undo_records_end


col time_now new_value time_end

select se.sid as session_id


, se.username
SQL> select max(maxquerylen),max(tuned_undoretention)
-- ,se.status as session_status from v$undostat;
SQL> select
-- , tr.status max(maxquerylen),max(tuned_undoretention)
as transaction_status from dba_hist_undostat;
, tr.start_time as transaction_start
--, tr.name as transaction_name
--, tr.used_ublk as undo_blocks
, tr.used_urec as undo_records
, round((dbms_utility.get_time - to_number('&time_start'))/100,1) sample_interval
, to_number('&undo_records_start') - tr.used_urec as undo_rec_change
, round(100 * abs(to_number('&undo_records_start') - tr.used_urec) /
(dbms_utility.get_time - to_number('&time_start')),1) undo_rec_change_per_sec
, round(tr.used_urec / (100 * abs(to_number('&undo_records_start') - tr.used_urec) /
(dbms_utility.get_time - to_number('&time_start'))) / 60,1) minutes_to_undo
, round(tr.used_urec / (100 * abs(to_number('&undo_records_start') - tr.used_urec) /
(dbms_utility.get_time - to_number('&time_start'))) / 3600,1) hours_to_undo
from v$session se
, v$transaction tr
, v$rollname rn
, v$rollstat rs
where se.sid = to_number('&session_id')
and se.serial# = to_number('&session_serial')
and tr.addr = se.taddr
and rn.usn = tr.xidusn
and rs.usn = rn.usn
order by sid;

SELECT a.ksppinm "Parameter",


b.ksppstvl "Session Value",
c.ksppstvl "Instance Value"
FROM sys.x$ksppi a, sys.x$ksppcv b, sys.x$ksppsv c
WHERE a.indx = b.indx
AND a.indx = c.indx
AND a.ksppinm in ( '_undo_autotune' , '_smu_debug_mode' ,
'_highthreshold_undoretention' ,
'undo_tablespace' , 'undo_retention' , 'undo_management' )
order by 2
/
column username format a15
column SQL_EXEC_START for a21
column sql_text format a50
column module format a35
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*1024) 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 v$session.SID,
v$session.SERIAL#,r.NAME "Undo Segment
Name", dba_seg.size_mb,
DECODE(TRUNC(SYSDATE - LOGON_TIME), 0,
NULL, TRUNC(SYSDATE - LOGON_TIME) || '
Days' || ' + ') ||
TO_CHAR(TO_DATE(TRUNC(MOD(SYSDATE-
LOGON_TIME,1) * 86400), 'SSSSS'),
'HH24:MI:SS') LOGON,
p.SPID, v$session.process,
v$session.USERNAME, v$session.STATUS,
v$session.OSUSER, v$session.MACHINE,
v$session.PROGRAM, v$session.module, action
FROM v$lock l, v$process p, v$rollname r,
v$session,
(SELECT segment_name, ROUND(bytes/
(1024*1024),2) size_mb FROM dba_segments
WHERE segment_type = 'TYPE2 UNDO' ORDER
BY bytes DESC) dba_seg
WHERE l.SID = p.pid(+) AND
v$session.SID = l.SID AND
TRUNC (l.id1(+)/65536)=r.usn AND
l.TYPE(+) = 'TX' AND
l.lmode(+) = 6
AND r.NAME = dba_seg.segment_name
--AND v$session.username = 'SYSTEM'
--AND status = 'INACTIVE'
ORDER BY size_mb DESC;

https://community.oracle.com/thread/1098943?tstart=0http://www.oracleflash.com/32/Change-or-switch-undo-tablespace-in-Or
If TRUE means it will not show any undo errors , So some times job may complete sucessfully.
select count(status) from dba_undo_extents where
status = 'EXPIRED';

select count(status) from dba_undo_extents where


status = 'UNEXPIRED';

select count(status) from dba_undo_extents where


status = 'ACTIVE';

select status, sum(bytes) / 1024 / 1024 || 'MB' from DBA_UNDO_EXTENTS group by status;

SELECT
dbms_undo_adv.required_undo_size(1800,
SYSDATE-30, SYSDATE)
FROM dual;
select maxquerysqlid, maxquerylen from
dba_hist_undostat order by maxquerylen desc;
select maxqueryid, maxquerylen from
v$undostat order by maxquerylen desc;

http://www.williamrobertson.net/documents/undo_tracker.shtml
col sid_serial for a20
SELECT S.sid || ',' || S.serial# sid_serial,
S.username, S.osuser, P.spid, S.module,
S.program, SUM (T.blocks) *
TBS.block_size / 1024 / 1024 mb_used,
T.tablespace,
COUNT(*) sort_ops
FROM v$sort_usage T, v$session S,
dba_tablespaces TBS, v$process P
WHERE T.session_addr = S.saddr
AND S.paddr = P.addr
AND T.tablespace = TBS.tablespace_name
GROUP BY S.sid, S.serial#, S.username,
S.osuser, P.spid, S.module,
S.program, TBS.block_size, T.tablespace
ORDER BY sid_serial;
SELECT distinct rpad(s.sid,3) "SID",S.USERNAME,
E.SEGMENT_NAME,
T.START_TIME "Start",
rpad(T.STATUS,9) "Status",
round((t.used_ublk*8)/1024) "Size(MB)"
--T.USED_UBLK||' Blocks and '||T.USED_UREC||' Records' "Rollback
Usage"
FROM DBA_DATA_FILES DF,
DBA_EXTENTS E,
V$SESSION S,
V$TRANSACTION T
WHERE DF.TABLESPACE_NAME = E.TABLESPACE_NAME AND
DF.FILE_ID = UBAFIL AND
S.SADDR = T.SES_ADDR AND
T.UBABLK BETWEEN E.BLOCK_ID AND E.BLOCK_ID+E.BLOCKS AND
E.SEGMENT_TYPE in( 'ROLLBACK','TYPE2 UNDO');

refer once for CFS1


o errors , So some times job may complete sucessfully.

|| 'MB' from DBA_UNDO_EXTENTS group by status;


https://community.oracle.com/community/support/support-blogs/database-support-blog/blog/2015/12/10/ora-1555-do-you-know

nts/undo_tracker.shtml
column SQL_EXEC_START for a21
column sql_text format a50
column module format a35
column sql_text format a50
break on report
compute SUM of MB_USED on report
SELECT 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 select
hh24:mi:ss') sql_exec_start,c.rows_processed,a.status, ROUND(
-- c.sql_text SUM(tem
substr(c.sql_text,1,50) sql_text pseg_siz
FROM v$session a, v$tempseg_usage b, v$sqlarea c, e)/10485
(select block_size from dba_tablespaces where 76)
tablespace_name='TEMP') d temp_mb
WHERE b.tablespace = 'TEMP' from
and a.saddr = b.session_addr gv$sql_w
AND c.address= a.sql_address orkarea_
AND c.hash_value = a.sql_hash_value active
ORDER BY b.tablespace, 5 desc; WHERE
sid=&sid;
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

OEM All metric repository tables


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;

https://blog.dbi-services.com/querying-the-oracle-management-repository/
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 b
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

agement-repository/
ly. May be one or 2 difference will be there

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


Troubleshootin GG ABENDED process
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

Identify the Lag from PDB ( execute on target side )

View errorlog from ggsci


shell commands in ggsci

View report ( Rutime statistics)

history command

execute the previous command


http://www.oracle-scn.com/approach-to-troubleshoot-an-abended-ogg-process/
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

select incoming_extract incoming_extract, round(


(extract (second from a)
+ extract (minute from a) * 60
+ extract (hour from a) * 60 * 60
+ extract (day from a) * 60 * 60 * 24)/60,0) as heartbeat_lag_secs
from (
select remote_database||'_'||incoming_extract incoming_extract
, (systimestamp - EXTRACT(TIMEZONE_HOUR FROM SYSTIMESTAMP)/24 + EXTRACT(TIMEZONE_MINUTE
FROM SYSTIMESTAMP)/60/24
- heartbeat_timestamp) +
(systimestamp - EXTRACT(TIMEZONE_HOUR FROM SYSTIMESTAMP)/24 + EXTRACT(TIMEZONE_MINUTE
FROM SYSTIMESTAMP)/60/24
- incoming_replicat_ts) as a
from C##GGADMIN.GG_HEARTBEAT);

VIEW GGSEVT
ggsci > sh date

Send <Process_name>, Report


View <process_name>, report

h
h 10

GGSCI (oelr5u7) 30> !


h 29

GGSCI Command History

2: start mgr
3: start er *
4: status all
...

29: h 29
30: h 29

GGSCI (oelr5u7) 31> !4


status all

Program Status Group Lag at Chkpt Time Since Chkpt

MANAGER RUNNING
EXTRACT RUNNING EBATCH 00:00:00 00:00:02
EXTRACT RUNNING ETEST 00:00:00 00:00:03
REPLICAT RUNNING RBATCH 00:00:00 00:00:04
REPLICAT RUNNING RTEST 00:00:00 00:00:05
REPLICAT RUNNING RTESTA 00:00:00 00:00:01
REPLICAT RUNNING RTESTB 00:00:00 00:00:00

GGSCI (oelr5u7) 32>


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 )

History of pga memeory used


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 min(a.begin_time),max(a.end_time),b.USED_TOTAL,b.ALLOCATED_TOTAL from
dba_hist_sysmetric_summary a,DBA_HIST_PROCESS_MEM_SUMMARY b where
begin_time between SYSDATE-3 and SYSDATE and a.snap_id=b.snap_id group by
b.USED_TOTAL,b.ALLOCATED_TOTAL order by 1 asc;
SELECT to_char(ssn.sid, '9999') || ' - ' || nvl(ssn.username, nvl(bgp.name, 'background')) ||
nvl(lower(ssn.machine), ins.host_name) "SESSION",
col percent head '%'
to_char(prc.spid, for 99990.99
'999999999') "PID/THREAD",
col star for A10 head ''
to_char((se1.value/1024)/1024, '999G999G990D00') || ' MB' " CURRENT SIZE",
to_char((se2.value/1024)/1024, '999G999G990D00') || ' MB' " MAXIMUM SIZE"
accept seconds prompt
FROM v$sesstat "Last Seconds
se1, v$sesstat [60] : " default
se2, v$session 60;
ssn, v$bgprocess bgp, v$process prc,
accept top prompt
v$instance "Top Rows
ins, v$statname stat1,[10] : " defaultstat2
v$statname 10;
WHERE se1.statistic# = stat1.statistic# and stat1.name = 'session pga memory'
select SQL_ID,round(PGA_MB,1)
AND se2.statistic# = stat2.statistic#PGA_MB,percent,rpad('*',percent*10/100,'*')
and stat2.name = 'session pga memory max' star
from
AND se1.sid = ssn.sid
(AND se2.sid = ssn.sid
select SQL_ID,sum(DELTA_PGA_MB) PGA_MB ,(ratio_to_report(sum(DELTA_PGA_MB))
AND se1.sid=114
over
AND ())*100 percent,rank()
ssn.paddr = bgp.paddrover(order
(+) by sum(DELTA_PGA_MB) desc) rank
from
AND ssn.paddr = prc.addr (+);
(
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


Auto Patching Code
/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';
for i in `crsstat.sh |grep .db| grep -v svc |grep -v .vip|grep -v .lsnr |grep -v .mgmt | grep -v OFFLINE | grep
"Open,STABLE"|cut -d"." -f2`

do
GRID_ENV=`ps -ef|grep pmon|awk '{print $NF}'|grep asm|cut -d_ -f3`
export GRID_ENV
. oraenv $GRID_ENV
NEW_HOME=`srvctl config database -v|grep $i|awk '{print $2}'`
export NEW_HOME
. /opt/oracle/local/bin/oraenv $i
for j in `srvctl status database -d $i | grep "running" | grep -v "not running" |awk '{print $2}' | awk 'NR==1'`
do
node=`srvctl status database -d $i |grep $j| awk '{print $NF}'`
connection="nohup `ssh -q $node "$(typeset -f Datapatch_apply); Datapatch_apply $j "` &"
done
done
<-- 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,ACTUA
L_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_DURATION
,
NEXT_RUN_DATE, MAX_RUN_DURATION,COMMENTS FROM
DBA_SCHEDULER_JOBS;
X$ Views

List the hidden parameters in the oracle database


undocumented init parameters:
find all internal tables like user$
how to find all x$views list

Hidden parameter default value

unset hidden parameter


Reading Alert log

Row Limiting Clause


v$ views

Info.sql

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

Case Insensitive search in sql where condition

Active Services running

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

Service Statics/Service previously running or not


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 object_name from dba_objects where object_name like '%$' and object_name not like 'SYS%'
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';

ALTER SYSTEM RESET "_some_hidden_parameter" scope = spfile;


select message_text from X$DBGALERTEXT where rownum <= 20;
SELECT val
FROM rownum_order_test
ORDER BY val DESC
FETCH FIRST 5 ROWS ONLY;

set long 20000 longchunksize 20000 pagesize 9999 linesize 1000


col PDB_NAME for a15
col HOST_NAME for a35
select db_unique_name CDB_NAME,(select name from v$pdbs where name not like '%SEED')
PDB_NAME,open_mode,database_role,(SELECT to_char(sysdate,'DD-MON-YYYY HH24:MI:SS') FROM dual)
"Current_time_db" ,(select INSTANCE_NAME from v$instance) INSTANCE_NAME,(select HOST_NAME from
v$instance ) HOST_NAME from v$database;
select INST_ID,INSTANCE_NAME,HOST_NAME,status,logins,VERSION from gv$instance order by 1;
select con_id,NAME,OPEN_MODE,RESTRICTED,OPEN_TIME from gv$pdbs order by 1;
col WRL_PARAMETER for a30
select INST_ID,STATUS,WALLET_TYPE,WRL_TYPE,WRL_PARAMETER,WALLET_ORDER from gv$encryption_wallet;

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 inst_id,to_char(startup_time,'DD-MON-YYYY HH24:MI:SS') "DB Startup Time" ,host_name FROM
sys.gv_$instance order by 1;
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 ) )

alter session set nls_comp=linguistic;


alter session set nls_sort=BINARY_CI;
select distinct metric_name from DBA_HIST_SYSMETRIC_SUMMARY where metric_name like '%memory%';

else following format required for searching


select distinct metric_name from DBA_HIST_SYSMETRIC_SUMMARY where metric_name like '%Memory%';

col NAME for a20


col SERVICENAME_AVAIL for a20
select
--b.inst_id ,
b.name , a.inst_id Inst_id_avail , a.name servicename_avail
from
gv$active_services a , dba_services b --, gv$instance c
where
--b.inst_id = a.inst_id(+) and
b.name = a.name(+) and
--(a.inst_id=c.inst_id and a.instance_name=c.instance_name) and
(a.name not like '%XDB%' AND a.NAME NOT LIKE '%SYS$%' and a.name not like '%DGB%') and
(b.name not like '%XDB%' AND b.NAME NOT LIKE '%SYS$%' and b.name not like '%DGB%')
order by 1,2
/

this gives proper output during spool


----------------------------------------------------------------
column dbname new_value dbname print
select name dbname from v$pdbs;
column timendate new_value spooltime print
select SYS_CONTEXT('USERENV', 'DB_UNIQUE_NAME')||'_'||SYS_CONTEXT('USERENV', 'SESSION_USER')||'_'||
to_char(sysdate,'dd-mon-yyyy-hh24-mi-ss') timeNdate from dual;
spool &dbname-&spooltime..log
create table
alert_log ( msg varchar2(80) )
organization external (
type oracle_loader
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


BREAK ON SNAP_ID
select snap_id,instance_number,SERVICE_NAME,value/100000 as DBTIME from DBA_HIST_SERVICE_STAT where
STAT_NAME='DB time' order by snap_id desc,instance_number FETCH FIRST 50 ROWS ONLY;
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------ 1 oracle
System
Run this bigtab dba 64 Mar 26 14:02 /proc/2661/fd/66 -> /var/tmp/test_rm.dbf (deleted)
altered.
from
where rownum <= l_rows-l_cnt;
l_cnt := l_cnt + sql%rowcount;
$ cd $ORACLE_HOME/install
commit;
$ ./changePerm.sh
end loop;
In
SQL>some other
alter unix, lsof
database dropmay be needed
logfile group 1;to map the file descriptor with the deleted file name
end;
alter
/ database drop logfile group 1
*
ERROR
alter table atbigtab
line 1:add constraint
first we setprimary
ORA-00350: a log
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
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, 'FALSE',to stop oslevel 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 , create or replace view all_parameters
x$ksppcv b , as
x$ksppsv c select x.ksppinm name, y.ksppstvl value
WHERE from x$ksppi
select name, value from sys.V$PARAMETER where name like '\_%' escape '\' andxISDEFAULT='FALSE';
, x$ksppcv y
a.indx = b.indx AND where x.indx = y.indx
a.indx = c.indx AND order by x.ksppinm
a.ksppinm LIKE '/_adg%' escape '/' /
ORDER BY grant select on all_parameters to public;
1 create public synonym all_parameters
/ for all_parameters;

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
column dbname new_value dbname
this gives lot of space output during spool -WASTE noprint
---------------------------------------------------------------- select name dbname from v$pdbs;
column dbname new_value dbname noprint SET MARKUP HTML ON
select name dbname from v$pdbs; spool C:\Oracle\login-
column timendate new_value spooltime noprint db\folder\&dbname..xls
select SYS_CONTEXT('USERENV', 'DB_UNIQUE_NAME')||'_'|| select * from all_db_links;
SYS_CONTEXT('USERENV', 'SESSION_USER')||'_'|| spool off
to_char(sysdate,'dd-mon-yyyy-hh24-mi-ss') timeNdate from dual; SET MARKUP HTML OFF
spool &dbname-&spooltime..log
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
set Pagesusing:
verification
linesize Processed (Data) : 3
500 SELECT
SELECT originating_timestamp,
Total
SQL> Pages Failing switch
alter system
originating_timestamp, (Data)logfile;
:0 message_text
message_text FROM
Total
FROM Pages 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;
select current_timestamp from dual;
select dbtimezone from dual;

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;

rg/reference/sys_context.html
OFF

dm_of

dmse_of

dv_of

lbac_of

part_of

rac_of
sdo_of
rat_of
olap_of
asm_of
ctx_of
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

SP parameter modification in last 7 days

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
Wallet status
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
set linesize 155
ADMINISTER
col time for a15KEY MANAGEMENT SET KEYSTORE close IDENTIFIED BY abc123
container=all;
col parameter_name format a50
ADMINISTER
col KEY MANAGEMENT
old_value format a30 SET KEYSTORE open IDENTIFIED BY abc123
container=all;
col new_value format a30
break on instance skip 3
Now
selectcheck the wallet status
instance_number at Container
instance, and
snap_id, PBD
time, level:
parameter_name, old_value, new_value from (
select status from v$encryption_wallet;
a.snap_id,to_char(end_interval_time,'DD-MON-YY HH24:MI') TIME, a.instance_number,
parameter_name, value new_value,
lag(parameter_name,1) over (partition by parameter_name, a.instance_number order by
a.snap_id) old_pname,
lag(value,1) over (partition by parameter_name, a.instance_number order by a.snap_id)
old_value ,
decode(substr(parameter_name,1,2),'__',2,1) calc_flag
from dba_hist_parameter a, dba_Hist_snapshot b , v$instance v
where a.snap_id=b.snap_id
and a.instance_number=b.instance_number
and parameter_name like nvl('&parameter_name',parameter_name)
and a.instance_number like nvl('&instance_number',v.instance_number)
)
where
new_value != old_value
and calc_flag not in (decode('&show_calculated','Y',3,2))
order by 1,2
/

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;
set lines 750 pages 9999
col WRL_PARAMETER for a50
select INST_ID,WRL_TYPE,WRL_PARAMETER,STATUS,WALLET_TYPE from
gv$encryption_wallet;
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++

How to find NON-ASCII characters 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


Diag collection

TFA collection for database


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]+
[^\x00-\x7F]+
Tick off 'Search Mode = Regular expression', and click --> Find Next
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;
/
Oracle

Root

run as root
./tfactl diagcollect -database mydb -from "Nov/16/2017 21:00:00" -to "Nov/17/2017 02:00:00"
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/
$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"

(Or) $TFA_HOME/bin/tfactl diagcollect -srdc dbperf TFA Collector - TFA with Database Support Tools Bundle (Doc ID
se Support Tools Bundle (Doc ID 1513912.1)
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

A tour of AWR Tables

Tanel pader's explain plan scripts

Best Url for sql_id performance scripts

Sql id Perf.sql one script

10046 trace analysis


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/

http://www.nocoug.org/download/2008-08/a-tour-of-the-awr-tables.nocoug-Aug-21-2008.abercrombie.html#script-aas-exact

https://blog.tanelpoder.com/2009/05/26/scripts-for-showing-execution-plans-via-plain-sql-and-also-in-oracle-9i/

http://www.williamrobertson.net/documents/index-code.shtml

https://mjsoracleblog.wordpress.com/2012/12/31/sql_sql_id-sql-1-7/

10046_events.pl
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