100% found this document useful (1 vote)
432 views545 pages

DBA Sheet v7.0

The document provides information about various hardware, operating system, memory, disk, CPU, network and other troubleshooting commands in Linux/Unix systems. It includes commands to check OS details, memory usage, disk usage and errors, CPU usage and processes, network configuration and ports, compression and archiving utilities, and other troubleshooting tasks.

Uploaded by

Atul Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as XLSX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
432 views545 pages

DBA Sheet v7.0

The document provides information about various hardware, operating system, memory, disk, CPU, network and other troubleshooting commands in Linux/Unix systems. It includes commands to check OS details, memory usage, disk usage and errors, CPU usage and processes, network configuration and ports, compression and archiving utilities, and other troubleshooting tasks.

Uploaded by

Atul Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as XLSX, PDF, TXT or read online on Scribd
You are on page 1/ 545

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?


Create all parent & subfolders structure
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


Vi command in unix prompt

Pause & Resume a PID in unix

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

ignore history in linux


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 . -name "*.trc" -exec grep -l "system state" {} \;

find . -type f | xargs grep dc7h92zrnpbnq


find . -type f -exec grep -l "dc7h92zrnpbnq" {} \;
find . -type d -exec echo "mkdir -p" {} \;

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


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

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


ifconfig nxge2:2 unplumb

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

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

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


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

# SOURCE:
follow same as below - dont add location directly to dumpfile

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

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

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

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


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

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

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

Ex : $ time dd if=test.img of=test.img.bkp bs=1M


dd: bad numeric argument: "1M"
real 0m0.01s
user 0m0.00s
sys 0m0.00s
pkginfo | grep xvnc
rpm -Uvh /opt/oracle/admin/redhat-release-6Server-1.noarch.rpm --nodeps

db/server: /dev/rdsk> zonename


Server1
Servernode2> zonename
global
bash-3.2# luxadm -e port
/devices/pci@0/pci@0/pci@8/pci@0/pci@8/SUNW,emlxs@0/fp@0,0:devctl NOT CONNECTED
/devices/pci@0/pci@0/pci@8/pci@0/pci@8/SUNW,emlxs@0,1/fp@0,0:devctl NOT CONNECTED
/devices/pci@0/pci@0/pci@9/SUNW,emlxs@0/fp@0,0:devctl NOT CONNECTED
/devices/pci@0/pci@0/pci@9/SUNW,emlxs@0,1/fp@0,0:devctl NOT CONNECTED
stty columns 120
vi file.log
vi listener.ora -c ':1,$s?(SID_DESC?\r(SID_DESC?g' -c ':wq'
pause it using: kill -STOP <PID>
resume the stopped process using command: kill -CONT <PID>.

$ 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

[root@v1ex1dbadm01 ~]# export HISTIGNORE='*'


[root@v1ex1dbadm01 ~]# ipmitool -I lanplus -H v1ex1dbadm02-ilom -U root -P XXXXXXXX chassis power on
Chassis Power Control: Up/On
[root@v1ex1dbadm01 ~]# export HISTIGNORE=''
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
1 -exec rm -f {} ;
play-two-files-side-by-side
prstat -Z
Host CPU utilization report from DATABASE

Get the CPU/Memory Free Usage details 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

Releasing oracle semaphores ( ipcs )


Tracing
Tracing Oracle process OS level
Tracing SQLPLUS at OS level

Scripts
Remove a line from oratab that matches dbname

Removing entry in tnsnames.ora

Remove Entry in tnsnames.ora file shell script ( Full Script )

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
Extract DB Alias from tnsnames.ora file
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

Batch script for single db login

Batch script for multiple db login


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

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


Server login automation- execute a command in remote server

Server login automation- execute a command in remote server- unix level

Arrange listener.ora & tnsnames.ora using AWK script

Arrange listener.ora file in single line format

Delete db entries in listener.ora file after db decommission.

Python Scripting

Python script for db connectivity

Python script for *.sql execution


For loop for executing in multiple databases

Running databases in a server

Shell scripting

Copy a file with dat & Time

Stop server idle timeout


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

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

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

check
------
$ipcs | grep oracle
$sysresv

releasing
--------
$ipcrm -m id (id is the id displayed for memory in ipcs under memory section)
$ipcrm -s id (id is the id displayed for semaphore in ipcs under semaphore section)
(or)
sysresv -i

strace -fF -v -p 16311


strace /oracle/product/10.2.0.1/bin/sqlplus -V 2>&1 |less
sed '/tns_alias2/,/^ *$/d' file
(OR)
awk '$1!="tns_alias2"' RS= ORS='\n\n' file
(OR)
sed -I '/dbname/d' /etc/oratab
awk '
for i in `olsnodes`
/^tns_alias2/ {getline
do L+=gsub (/\(/, "") - gsub (/\)/,"")
echo $i }
/usr/bin/ssh -q $i " echo "===============" ; sh /script/location/1.sh"
done
!L
L {L+=gsub (/\(/, "") - gsub (/\)/,"")
cat 1.sh }
========
#!/bin/ksh
' file
rm -rf /tmp/mm.txt
cat /etc/oratab | cut -d ":" -f2 | sort -u | grep -i 12.2.0.1 |
while read line ; do echo ""Checking DB Entry in ""$line/network/admin/tnsnames.ora ;
cp $line/network/admin/tnsnames.ora $line/network/admin/tnsnames.ora.cleanup
for i in `cat dblist.txt`
do
awk '/^'$i'/{getline;L+=gsub (/\(/, "") - gsub (/\)/,"")}!L ;L{L+=gsub (/\(/, "") - gsub (/\)/,"")}' $line/network/admin/tnsnames.ora >
/tmp/mm.txt && mv /tmp/mm.txt $line/network/admin/tnsnames.ora
done
done
grep "^[^#]" /var/opt/oracle/oratab | awk -F: '{printf("\t%-6s\t%-30s\n",$1,$2)}'
. Oraenv
ps -ef|grep pmon | awk '{print $8}'|grep -v "grep"| grep -v "ASM"| cut -d"_" -f3

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

sed -n '/DESCR/{x;p;d;}; x' $ORACLE_HOME/network/admin/tnsnames.ora | sed "s/=/${s}/"


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
#!/bin/kshcomp_name, version, status FROM dba_registry where status='INVALID';
SELECT
rm
exit-rf log.txt
for
EOF i in `cat a.txt`
do
done
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
echo off (select name from v\$database) dbname, (select NAME from v\$pdbs where con_id=(select con_id from v\$pdbs where
rownum
cls < 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
for /f "tokens=1-2 order by "p.inst_id;
delims= %%b in (1.txt) do (
exit;
echo.***********************************************
EOF
echo.Connect to %%b
done
rem echo. Password: %%c
echo.***********************************************
rem echo.sqlplus -L sys/pwd@%%b @C:\dbname.sql
sqlplus -L "sys/pwd@%%b as sysdba" @C:\dbname.sql

)
echo.
echo.DONE
echo.Press any key to exit.
pause >nul
for i in `ps -ef |grep pmon|grep -v MGMTDB|grep -v ASM|grep -v grep|cut -d"_" -f3`
do
export ORACLE_SID=$i
export ORACLE_HOME=`ps -ef |grep pmon|grep $i|awk {'print "pwdx " $2 '}|sh|awk {'print $2 '}|sed 's/....$//'`
#!/bin/ksh
export PATH=$ORACLE_HOME/bin:$ORACLE_HOME/OPatch:$PATH
# ------------------------------------------------------------------------
sqlpluskornshell
# A simple -s "/ as sysdba"
script to <<EOF
force all running instances to re-register
set lines 300
# with the remote_listener (workaround for bug 13066936)
col VALUE for a65
# ------------------------------------------------------------------------
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_//'`
do show parameter log_archive_config
echoEOF . Reregistering $INST with remote_listener
done
export ORAENV_ASK=NO
. oraenv $INST
sqlplus -SL "/ as sysdba" <<-EOF >/dev/null
col remote_val new_value remote_val
select value remote_val from v\$parameter where name='remote_listener';
alter system set remote_listener='';
alter system register;
alter system set remote_listener='&remote_val';
alter system register;
EOF
done

"
@echo off
cd C:\location
set /p id="Enter dbname :"
"C:\location\sql.exe" -L sys/pwd@"jdbc:oracle:thin:@tnsentry%id%" as sysdba @sqlinput.sql

"

"
@echo on
set result_file=result.log
cd C:\location\DBLOGIN
del result.log
(for /f %%i in (dblist.txt) do (
"C:\location\sqlplus.exe" -L -S sys/pwd@"tnsentry%%i" as sysdba @sqlinput.sql >>result.log
))
start C:\location\DBLOGIN\result.log
pause

"
export ORACLE_BASE=/opt/oracle
$ECHO ' \033[1;33m ***************************************************************************************** \033[0;0m '
export ORACLE_ASK=YES
echo ' '
export ORACLE_OWNER=oracle
echo
export'lsNLS_LANG=AMERICAN_AMERICA.UTF8
-ltr $DISK_LOC | sort '
ls -ltr $DISK_LOC | sort
export NLS_DATE_FORMAT='YYYY/MM/DD HH24:MI'
echo
nins ' '
echo
. .kshrc ''
$ECHO ' \033[1;33m ******************************* \033[0;0m '
$ECHO
# Set up' machine
\033[1;33m *
independentNETWORK
variables * \033[0;0m '
$ECHO ' \033[1;33m *******************************
stty erase '^H' kill "^U" intr "^C" eof "^D" \033[0;0m '
echo
umask 002' '
echo
export' 'JAVA_COMPILER=NONE
export HOST=$(uname -n)
echo
export'/sbin/ifconfig
PWD=`pwd`-a'
/sbin/ifconfig -a
export PS1='$ORACLE_SID@$HOST: $PWD> '
if [ -s "$MAIL" ] # This is at Shell startup. In normal
echo
then echo'' "$MAILMSG" # operation, the Shell checks
echo
fi '' # periodically.
$ECHO ' \033[1;33m ***************************** \033[0;0m '
$ECHO ' \033[1;33m * FINAL Summary * \033[0;0m '
$ECHO ' \033[1;33m ***************************** \033[0;0m '
export
echo ' 'ORATAB="/var/opt/oracle/oratab"
export ORA_CRS_HOME=`cat /etc/oratab|grep -i asm|awk -F: '{print $2}'`
if [[ $(ps -ef | grep mrp | grep -v grep| wc -l) -ne 0 ]];
then gpo_core_u |
tnsping
awk $ECHO ' \033[1;33m Dataguard =
'{FS="[()]+";for(i=1;i<=NF;i++) Running
if($i \033[0;0m '
~ /(HOST|PORT|SERVICE_NAME)/) print $i}'
else
echo "Dataguard = Not Running"
script.sql which executes SQLT XTRACT with a delay of 4.5 hours
fi
host sleep 4.5h
start run/sqltxtract.sql
if [[ $(ps 51x6yr9ym5hdc
-ef | grep ./mgr sqltxplain | wc -l) -ne 0 ]];
| $GREP -vE 'grep|async'
then
$ECHO ' \033[1;33m Goldengate = Running \033[0;0m '
Presnap
else
echo "Goldengate = Not Running"
fi
echo ' '
echo ' '
EOF

chmod
col 755 osprecheck.sh
c1 heading 'end|time' format a10
col c2 heading 'wait|class' format a20
./osprecheck.sh
col | tee presnap.txt
c3 heading 'time|waited' 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 -STOP rman
join
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;
##..add extra line
Pattern (and eventually
to match the SID_NAME track itoffor
theother usage)
deleted block.
if(level==1
reSidName &&= i==1 && tokens[i]~"[A-Za-z]")
"[(][^(]*SID_NAME *= *" DbName{ "[^A-Za-z0-9_.]";
} TOP=tokens[i];
if (first==1)
function { fnData, Local, j, k, Body, Head, nOpen) {
Fix (tx,
first=0;
}#..
else { each block, using the Sid Desc as the delimiter.
Split
printf(tx,
split "\n\n";
Body, reSidDesc, Head);
plink [email protected] -pw SecretRootPwd (date;hostname;ls -l)
}#.. Search for the block containing the required Sid Name.
} for (j = 1; j in Body; ++j) {
#!/usr/bin/expect
if (match (Body[j], reSidName)) {
for f in `cat
printf servers.txt`
(tokens[i]);
Head[j-1] = ""; #.. Discard the start of the block.
do i++; #.. Count the level of opening brackets inside the block.
spawn
} ssh
nOpen username@$f
= 1 + gsub "hostname"
("[(]", "(", Body[j]);
}expect ""password""
#.. Discard the matching closing brackets.
send {""XXXX\r""
END for (k = 1; k <= nOpen; ++k)
interact
# new linesub at the end of"",
("[^)]*[)]", fileBody[j]);
done
printf("\n");sub (/^\n/, "", Body[j]);
}' }
} }
#.. Write out what is left.
usage:printf ("%s", Body[1]) > fnData;
======
vi listener.ora
for (j = 2; j in& Body;
then execute
++j) { below code
cat tnsnames.ora
# convert printflistener.ora
("%s%s", | tidy_dotora
definition Body[j])
Head[j-1], in single>line format
fnData;
:1,$s?(SID_DESC?\r(SID_DESC?g
}
# convert listener.ora definition back to original format
close (fnData);
}:1,$s?\n(SID_DESC?(SID_DESC?g
{ Fix( $0, FILENAME); }
(or)
vi listener.ora -c ':1,$s?(SID_DESC?\r(SID_DESC?g' -c ':wq'
command to give input
======================
awk -v DbName="db12c|db12c_dgmgrl" -f logic.awk "listener.ora"

#!/usr/bin/env python
# -*- coding: utf8 -*-

import os
from subprocess import Popen, PIPE

connectString = 'username/password@service_name'
sqlCommand = 'select * from dual;'
import os
#sqlCommand = b’select * from blue.t;’ --for python 3
from subprocess
CommandFile import Popen, PIPE
= "@/home/script/info.sql"

sqlplus = Popen(["sqlplus", "-S", "/", "as", "sysdba"], stdout=PIPE, stdin=PIPE)


sqlplus.stdin.write("select
def runSqlQuery(sqlCommand,sysdate from dual;"+os.linesep)
connectString):
sqlplus.stdin.write("select count(*)
session = Popen(['sqlplus', from all_objects;"+os.linesep)
'-S', connectString], stdin=PIPE, stdout=PIPE, stderr=PIPE)
out, err = sqlplus.communicate()
session.stdin.write(sqlCommand)
print out session.communicate()
return

def runSqlFile(CommandFile, connectString):


session = Popen(['sqlplus','-S',connectString],stdin=PIPE,stdout=PIPE,stderr=PIPE)
session.stdin.write(CommandFile)
return session.communicate()

commandResult,errorMessage = runSqlFile(CommandFile,connectString)
queryResult, errorMessage = runSqlQuery(sqlCommand, connectString)
print queryResult
print commandResult
#!/usr/bin/env python
# -*- coding: utf8 -*-

import os
from subprocess import Popen, PIPE

sqlCommand = 'select * from dual;'


fh = open('/home/oracle/script/py/db.txt','r')

def runSqlQuery(sqlCommand, connectString):


session = Popen(['sqlplus', '-S', connectString ], stdin=PIPE, stdout=PIPE, stderr=PIPE)
session.stdin.write(sqlCommand)
return session.communicate()

for line in fh:


connectString = line
print connectString
queryResult, errorMessage = runSqlQuery(sqlCommand, connectString)
print queryResult

print(subprocess.call("ps -ef |grep pmon|grep -v MGMTDB|grep -v ASM|grep -v grep|cut -d'_' -f3", shell=True))

cp a.txt a.txt.$(date +%F-%H:%M)

export TMOUT=0
Comments

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

Solaris

https://www.unix.com/shell-programming-and-scripting/261826-removing-section-tnsnames-ora.html

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


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
for i in 'alter
select `ps -ef|grep pmon view
materialized | awk'||owner||'.'||object_name||'
'{print $8}'|grep -v "grep"| compile;'
grep -v "ASM"| cut -d"_" -f3` e $i in $x
do
from dba_objects stage"
export ORACLE_SID=$i
where status<>'VALID'; fi
sqlplus
spool off; -s /nolog <<EOF done
set
#!/bin/kshoff echo off feedback off
head
@$i.sql; rm
conn
rm -rf /dbhealthoutput.txt
exit as sysdba /tmp/temp
set
EOFlines
echo 160the syspassword"
"Enter .sql
select
done-echo
stty instance_name,logins,(select database_role from v\$database) database from v\$instance; done
select PROCESS,status from gv\$managed_standby where process like '%MRP%';
read sys_pw
col STBY_BEHIND_BY
stty echo for a20
select (select sysdate
for i in `cat dblist.txt` from dual)"TIMESTAMP",s.thread#,s.MAX_SEQ#, a.MAX_APP_SEQ#,
(s.MAX_SEQ#-a.MAX_APP_SEQ#) "Difference" from
do
( select thread#,max(sequence#) "MAX_SEQ#" from v\$archived_log group by thread# ) s,
echo '***********************************************'
(select thread#,max(sequence#)
echo connecting to $i "MAX_APP_SEQ#" from v\$archived_log where applied='YES'
group by thread#) a where a.thread#=s.thread#;
echo '***********************************************'
set serveroutput on
exec
echodbms_output.put_line('------------------------------');
'*********************' >>dbhealthoutput.txt
exit
echo connecting to $i >>dbhealthoutput.txt
EOFecho '*********************' >>dbhealthoutput.txt
donesqlplus -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
echo 'ls -ltr $DISK_LOC | sort '
ls -ltr $DISK_LOC | sort

echo ' '


echo ' '
$ECHO ' \033[1;33m ******************************* \033[0;0m '
$ECHO ' \033[1;33m * NETWORK * \033[0;0m '
$ECHO ' \033[1;33m ******************************* \033[0;0m '
echo ' '
echo ' '

echo '/sbin/ifconfig -a'


/sbin/ifconfig -a

echo ' '


echo ' '
$ECHO ' \033[1;33m ***************************** \033[0;0m '
$ECHO ' \033[1;33m * FINAL Summary * \033[0;0m '
$ECHO ' \033[1;33m ***************************** \033[0;0m '
echo ' '

if [[ $(ps -ef | grep mrp | grep -v grep| wc -l) -ne 0 ]];


then
$ECHO ' \033[1;33m Dataguard = Running \033[0;0m '
else
echo "Dataguard = Not Running"
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"
postsnap
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
for (j = 1; j in Body; ++j) {
if (match (Body[j], reSidName)) {
Head[j-1] = ""; #.. Discard the start of the block.
#.. Count the level of opening brackets inside the block.
nOpen = 1 + gsub ("[(]", "(", Body[j]);
#.. Discard the matching closing brackets.
for (k = 1; k <= nOpen; ++k)
https://www.thegeekstuff.com/2017/05/putty-plink-examples/
sub ("[^)]*[)]", "", Body[j]);
sub (/^\n/, "", Body[j]);
}
}
#.. Write out what is left.
printf ("%s", Body[1]) > fnData;
for (j = 2; j in Body; ++j) {
printf ("%s%s", Head[j-1], Body[j]) > fnData;
}
close (fnData);
}
{ Fix( $0, FILENAME); }
'
awk -v DbName="${1}" -f <( printf '%s' "${Awk}" ) "${fnOra}"
}
https://www.ludovicocaldara.net/dba/tidy_dotora/
DelSid "db12c" "listener.ora"
# DelSid "db12c_dgmgrl" "listener.ora"
# DelSid "db12c|db12c_dgmgrl" "listener.ora"

=============================
To execute this script try as below
./script.sh
(or)
bash ./script.sh

https://github.com/dsaran/scripts/blob/master/sqlrunner.py

https://leonotes.wordpress.com/2016/09/02/run-sql-or-sql-file-from-python-via-sqlplus/
export
PATH=$O
RACLE_
HOME/bi
n:
$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 exam
e same name. The best example is the "oracle" process, which is typically run by the user "oracle". So, when you want to stop the process
you want to stop the process called "oracle" and you issue:
exadata layout script
Complete ILOM Cheat sheet

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
Disk Failure/Poor performance deduction

Check Built in Functions

Cell Check
Cell details - Complete Detail
Cell details - Individual Components

Cell Processes - Run Check


- Check All 3 processes

- Restart Server (RS) - Parent Process

- Management Server (MS)

- CELLSRV

Cell Processes - Restart

- Restarting All processes

- Restart Server (RS)

- Management Server (MS)

- CELLSRV

Disk/Flash Creation

Lun Creation

Cell disk Creation

Grid disk Creation


ASM DG Creation
Flashlog Creation

Flashcache Creation

Others
To check Complet mapping of disks

Execute a Command in multiple Nodes


Validate email in cell

Cell Disk

Grid Disk

LUNS

Flashdisk

IORM Plan

Metrics - Definition ( Means help Command )

Metrics
current space utilization
History

Alerts

threshold

WriteBack Or writethrough ?

Flush the dirty blocks from Flash Cache to Grid disks

Exadata Version

Ilom Login

Ilom Password-reset

Pdu login
pdu formware version

Power on /OFF

Power on First Compute Node


Power on remaining Compute Nodes

Power on All Storage Node

Power off Storage Cells


Identify Serail Nmber

Exadata Machine

Compute Node
Storage Cells

InfiniBands

pdu
login
dbnode
cellnode
ibswitches

cisco switch / Ethernet Swicth


pdu
Exadata default passwords

Exadata DB Servers:

Exadata Storage Servers:

InfiniBand switches:
Ethernet switches

Power distribution units (PDUs):


Database server ILOMs:
Storage Server ILOMs

InfiniBand ILOMs:
Keyboard, video, mouse (KVM):

Changing default passwords


SELECT
cellname cv_cellname
, CAST(extract(xmltype(confval), '/cli-output/cell/releaseVersion/text()') AS VARCHAR2(20))
cv_cellVersion
, CAST(extract(xmltype(confval), '/cli-output/cell/flashCacheMode/text()') AS
VARCHAR2(20)) cv_flashcachemode
http://www.centroid.com/blog/monitoring-exadata-smart-scan
, CAST(extract(xmltype(confval), '/cli-output/cell/cpuCount/text()') AS VARCHAR2(10))
https://unknowndba.blogspot.com/2019/01/exadata-rack-layout.html
cpu_count
https://www.thegeekdiary.com/most-commonly-used-ilom-commands-cheat-sheet/
, 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"


dcli -l oracle -c host1,host2 uptime
[root@cellserver] cellcli -e list alerthistory
CellCLI> list lun
0_0 0_0 warning - poor performance
CellCLI> list physicaldisk
8:0 PKWA8V warning - poor performance
CellCLI> list celldisk
CD_00_CellServerce06 proactive failure
CellCLI> list griddisk attributes name,asmmodestatus,asmdeactivationoutcome,status
DATADISK_CD_00_Cellserverce06 DROPPED Yes proactive failure

V$SQLFN_METADATA

CellCLI> list cell detail


CellCLI> LIST CELL ATTRIBUTES name,status,fanstatus, -powerstatus,temperaturestatus

[root@cel01 ~]# service celld status

ps -eaf|grep cellrs

ps -eaf|grep ms.err

ps -eaf|grep "/cellsrv "

CellCLI> alter cell shutdown services all


CellCLI> alter cell startup services all
CellCLI> alter cell restart services all
CellCLI> alter cell restart services all force
CellCLI> alter cell shutdown services ms
CellCLI> alter cell startup services ms
CellCLI> alter cell restart services ms
CellCLI> alter cell shutdown services rs
CellCLI> alter cell startup services rs
CellCLI> alter cell restart services rs
CellCLI> alter cell shutdown services cellsrv
CellCLI> alter cell startup services cellsrv
CellCLI> alter cell restart services cellsrv

cd /opt/oracle/cell/disks/raw/
[root@qr01cel02 raw]# dd if=/dev/zero of=DISK22 bs=1M count=1024
CellCLI> create celldisk CD_DISK11_qr01cel01
lun="/opt/oracle/cell11.2.3.2.1_LINUX.X64_130109/disks/raw/DISK11"
create griddisk PRODHD_GD_DISK11_qr01cel01
celldisk=CD_DISK11_qr01cel01,size=400M
CellCLI> create griddisk ALL HARDDISK PREFIX=CD_DISK
create diskgroup prodhd normal redundancy disk 'o/*/PRODHD*' attribute 'compatible.asm'='11.2', 'compatible.rdbms'='11.2', 'a
CellCLI> create flashlog all size=100m
CellCLI> create flashlog celldisk='FD_00_qr01cel01,FD_01_qr01cel01'

CellCLI> create flashcache all


CellCLI> create flashcache celldisk='FD_00_qr01cel01,FD_01_qr01cel01',size=1G
CellCLI> create flashcache celldisk='FD_00_qr01cel01,FD_01_qr01cel01'

cellcli > list diskmap


dcli -g mycells cellcli -e list cell
dcli -g mycells "cat /proc/meminfo | grep Mem"
CellCLI> alter cell validate mail

CellCLI> LIST CELLDISK


CellCLI> list celldisk CD_DISK04_qr01cel01 detail

CellCLI> LIST GRIDDISK


CellCLI> list griddisk attributes name,asmmodestatus
CellCLI> list griddisk attributes name,asmmodestatus,asmdeactivationoutcome
CellCLI> list griddisk where celldisk=CD_DISK04_qr01cel01 detail
cellcli –e alter griddisk all inactive
cellcli –e alter griddisk all active

CellCLI> LIST LUN


CellCLI> LIST LUN WHERE DISKTYPE=HARDDISK
CellCLI> list lun where disktype=flashdisk
CellCLI> list lun where name like '.*DISK04' detail
CellCLI> list physicaldisk where luns like '.*DISK04' detail

CellCLI> list celldisk where disktype=flashdisk


CellCLI> list flashcache detail
CellCLI> list flashcachecontent detail
CellCLI> list flashlog detail
CellCLI> drop flashcache
CellCLI> drop flashlog
cellcli -e "alter cell flashCacheMode=writeback"

CellCLI> ALTER IORMPLAN OBJECTIVE=BALANCED


CellCLI> ALTER IORMPLAN ACTIVE
CellCLI>alter iormplan dbplan=((name=db1,level=1,allocation=100), (name=other,level=2,
allocation=100))
CellCLI> alter iormplan active
CellCLI> list iormplan detail

CellCLI> list metricdefinition


CellCLI> list metricdefinition detail
CellCLI> list metricdefinition where name like 'CL_.*' detail
CellCLI> list alertdefinition

CellCLI> list metriccurrent


CellCLI> list metriccurrent where objecttype='CELL'
CellCLI> list metriccurrent cl_memut
CellCLI> list metriccurrent where alertState != normal
CellCLI> list metriccurrent cl_fsut
CellCLI> list metrichistory

CellCLI> list alerthistory


CellCLI> list alerthistory 5_1 detail
CellCLI> alter alerthistory 5_1 examinedby='student'
CellCLI> drop alerthistory 4_1
CellCLI> list threshold
CellCLI> create threshold cl_fsut."/tmp" comparison='>',warning=50

CELLCLI> list cell attributes flashCacheMode

# dcli -g cell_group -l root cellcli -e alter flashcache all flush

dmidecode -s system-product-name

[root@dbnode ~]# ipmitool sunoem cli


--> show faulty
[root@dbnode ~]# ipmitool sunoem cli 'set /SP/users/root password=newpwd' newpwd
[root@dbnode ~]# ipmitool sunoem cli 'set /SP/users/root locked=false'
[root@dbnode ~]# ipmitool bmc reset cold

https://pduhostname.domain.comor#ssh admin@pduhostname
pducli --> get pdu_firmware_version

ssh root@v1ex1dbadm01-ilom
-> show /SYSTEM
-> start /SYSTEM
-> show /SYSTEM
[root@v1ex1dbadm01 ~]# ipmitool -I lanplus -H v1ex1dbadm02-ilom -U root -P XXXXXXXX chassis power on

[root@v1ex1dbadm01 ~]# for host in `cat /opt/oracle.SupportTools/onecommand/cell_group`;


do
> echo ${host}: `ipmitool -I lanplus -H ${host}-ilom -U root -P XXXXXXXX chassis power on`
> done

[root@v1ex1dbadm01 ~]# dcli -g /opt/oracle.SupportTools/onecommand/cell_group -l root


'hostname; uptime'
[root@v1ex1dbadm01 ~]# dcli -g /opt/oracle.SupportTools/onecommand/cell_group -l root
"cellcli -e alter cell shutdown services all"
[root@v1ex1dbadm01 ~]# dcli -g /opt/oracle.SupportTools/onecommand/cell_group -l root
poweroff

[root@exanode1 ~]# dmidecode -s system-serial-number


[root@v1ex1dbadm01 ~]# ipmitool sunoem cli "show /SP system_identifier" | grep
"system_identifier ="
[root@v1ex1dbadm01 ~]# dcli -g /opt/oracle.SupportTools/onecommand/dbs_group -l root
dmidecode -s system-serial-number
[root@v1ex1dbadm01 ~]# dcli -g /opt/oracle.SupportTools/onecommand/cell_group -l root
dmidecode -s system-serial-number
[root@v1ex1dbadm01 ~]# dcli -g /opt/oracle.SupportTools/onecommand/ib_group -l root
showfruinfo | grep -a Sun_Serial_Number
[root@exanode1 ~]# ipmitool -H exa-iba0 -U root sunoem cli "show /SYS
product_serial_number"
[root@exanode1 ~]# ipmitool sunoem cli "show
/System/Power/Power_Supplies/Power_Supply_0"

root@dbnode-ilom
root@cellnode-ilom
ilom-admin@ibswitch
[root@v1ex1dbadm01 ~]# telnet ip_address_of_ciscoswitch
exa1sw-ip> enable
exa1sw-ip#
Direct website as admin user

root/welcome1
oracle/welcome1
grid/welcome1
grub/sos1Exadata
root/welcome1
celladmin/welcome1
cellmonitor/welcome1
root/welcome1
nm2user/changeme
admin/welcome1
admin/welcome1
root/welcome1
root/welcome1
root/welcome1
ilom-admin/ilom-admin
ilom-operator/ilom-operator
admin/welcome1

http://rob.lasonder.org/index.php?title=Configure_functional_accounts_with_non_default_passwords
HP => High Performance
HC => High Capcity

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

run as root
used to start up and shut down the Cell Server (CELLSRV)
and
It works in cooperation with the Exadata cell command-line
Management
interface ServerIn(MS).
(CellCLI). addition, MS is responsible for sending
alerts
CELLSRV communicatesstatistics
and collects some in addition
with Oracle to those
Database collected
to serve
by CELLSRV
simple block requests, such as database buffer cache reads,
and Smart Scan requests, such as table scans with projections
and filters.

ble.asm'='11.2', 'compatible.rdbms'='11.2', 'au_size'='4M', 'cell.smart_scan_capable'='TRUE';


https://blog.zeddba.com/tag/exadata/
XXXXXX chassis power on
m/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
frompagesize
set v$asm_disk 100
order byinst
column group_number;
format a10 heading 'Inst'
column file_type format a20 heading 'File type'
col
col PATH
column
PATH mgfor
for a55
format
a55 99,999,999
col DG_NAME
break
select on
path, for 1a15
instgroup_number
skip group_#, disk_number disk_#, mount_status,header_status, state,
col DG_STATE
compute
total_mb,sum free_mb offormg a10
on v$asm_disk
from inst where header_status='CANDIDATE' or
col FAILGROUP
whenever sqlerrorfor
header_status='FORMER' a20
exit 1 order by 1 ;
set pages
lines 750 0 feed
pages off 9999
linesize 100 heading on
set pagesize
select 100
inst, file_type,sum(mg) mg from (
column
select inst format
select dg.name a10 heading
dg_name, 'Inst'
dg.state 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
d.path,d.total_mb,d.free_mb,
file_type, format a20 heading 'File
d.mount_status, type'd.FAILGROUP, d.state
column
from mg format
v$asm_diskgroup 99,999,999
round((szbytes)/1048576) as MG from ( dg, v$asm_disk d
break
select on
where inst skip 1 sys_connect_by_path(aname, '/'))) full_alias_path,
dg.group_number=d.group_number
lower(concat('',
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)
for
c.type a15file_type, c.bytes mgszbytes
from (
select substr(full_alias_path,2,instr(full_alias_path,'/',2,1)-2)
GROUP_NUMBER DG#,
from v$asm_alias a, v$asm_diskgroup name, b, v$asm_file c as INST,
ALLOCATION_UNIT_SIZE AU_SZ, STATE,
file_type,
TYPE, TOTAL_MB,
where a.group_number FREE_MB, OFFLINE_DISKS from v$asm_diskgroup;
= b.group_number
round((szbytes)/1048576)
and a.group_number as MG from (
= c.group_number(+)
select lower(concat('', sys_connect_by_path(aname,
and a.file_number = c.file_number(+) '/'))) full_alias_path,
select GROUP_NUMBER,NAME,COMPATIBILITY,DATABASE_COMPATIBILITY
system_created, alias_directory, file_type, szbytes from
and a.file_incarnation = c.incarnation(+)
v$asm_diskgroup;
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 rindexfile_type,
99.0
in c.bytes szbytes
SELECTfrom v$asm_alias
name,
( selectfree_mb, a, v$asm_diskgroup b, v$asm_file c
total_mb, ((total_mb-free_mb)/total_mb)*100
a.reference_index as "USED %",
where a.group_number
free_mb/total_mb*100
from v$asm_alias "FREE%"= b.group_number
from v$asm_diskgroup
a, 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)
)
where szbytes is not null)
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 username format a10
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 DISKGROUP
col username TEST INCLUDING CONTENTS;
format a6
col sid format 9999
col osuser
ALTER format a14 DATA01 ADD DISK '/dev/oracleasm/disks/ASM_DISK01' SIZE 1000 M
DISKGROUP
col s# format
rebalance power 99999
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 [email protected]:/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, b.path, b.header_statusmg from (
select substr(full_alias_path,2,instr(full_alias_path,'/',2,1)-2)
from v$asm_disk b, v$asm_diskgroup a as INST,
file_type,
where a.group_number (+) =b.group_number
round((szbytes)/1048576)
order by b.group_number, as MG from ( b.name
b.disk_number,
select
/ lower(concat('', sys_connect_by_path(aname, '/'))) full_alias_path, Good query
system_created, alias_directory, file_type, szbytes
from ( select b.name gname, a.parent_index pindex, a.name aname,
a.reference_index rindex , a.system_created, a.alias_directory,
c.type file_type, c.bytes szbytes
from v\$asm_alias a, v\$asm_diskgroup b, v\$asm_file c
where a.group_number = b.group_number
and a.group_number = c.group_number(+)
and a.file_number = c.file_number(+)
and a.file_incarnation = c.incarnation(+)
and b.name = UPPER('${DG}')
)
start with (mod(pindex, power(2, 24))) = 0
and rindex in
( select a.reference_index
from v\$asm_alias a, v\$asm_diskgroup b
where a.group_number = b.group_number
and (mod(a.parent_index, power(2, 24))) = 0
-- and a.name = 'SINGLEDBNAME'
)
connect by prior rindex = pindex)
where szbytes is not null)
group by inst, file_type
/
exit;

END
exit 0

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

60050768018E027998000000000010F6d0s0' SIZE 102400M;


680181050F20000000000007D4d0s0' SIZE 102400 M DISK '/dev/rdsk/c5t600507680181050F20000000000007D5d0s0' SIZE 102400 M D
http://edbinfo.blogspot.com/2009/02
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/
ASM_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.wordp

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

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
export%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

When was the last switchover happened

Change Mode - Max Performance/Availaility/Protection

Monitor Redo apply Process

increase apply speed


Run this at Primary
select distinct error from gv$archive_dest ;
-------------------
set
set lines
lines 750
160 pages 9999
column DEST_NAME format
col STBY_BEHIND_BY a20
for a20
column DESTINATION
select (select format
sysdate from a35
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 TARGET format a15
( select 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 inst_id,DEST_ID,DEST_NAME,DESTINATION,TARGET,STATUS,ERROR
activation# from gv$archive_dest
from v$database )and applied='YES' group by thread#) a where 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 system
ALTER set log_archive_dest_2='service="stbydbname",LGWR
DATABASE RECOVER MANAGED STANDBY DATABASE ASYNC PARALLELNOAFFIRM delay=0 optional
8 DISCONNECT FROM
compression=disable
SESSION; 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 a.event, a.wait_time, a.seconds_in_wait from gv$session_wait a, gv$session b where a.sid=b.sid and
SQL> show parameter log_archive_max_processes
b.sid=(select SID from v$session where PADDR=(select PADDR from v$bgprocess where NAME='MRP0'))
NAME TYPE VALUE
------------------------------------
set lines 1000 pages 9999 ----------- ------------------------------
log_archive_max_processes
select to_char(START_TIME,'DD-MON-YYYY integer 8HH24:MI:SS') "Recovery Start Time",to_char(item)||' = '||
to_char(sofar)||' '||to_char(units) "Progress"
DGMGRL> edit database STBY
from v$recovery_progress whereset property maxconnections=30;
start_time=(select max(start_time) from v$recovery_progress);
Property "maxconnections" updated

DGMGRL> show database STBY maxconnections;


MaxConnections = '30'

SQL> show parameter log_archive_max_processes


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

Now check the MRP Active apply speed


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

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


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

so total time taken


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

execute this on primary


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

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

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

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

show configuration ;
show database verbose india
show database verbose america

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

add this static entry in the listener.ora file

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

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

dgmgrl /

connect sys/pwd
switchover to america;

connect sys/pwd
switchover to india;

RMAN>
echo set on
run {
allocate channel c1 device type disk;
allocate auxiliary channel a1 device type disk;
allocate auxiliary channel a2 device type disk;
duplicate database for standby from active database using backupset nofilenamecheck;
}

$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

SELECT standby_became_primary_scn FROM v$database;


select scn_to_timestamp(scn_number) from dual;

DGMGRL > Edit Configuration Set protection mode as MaxPerformance;


Edit database 'prod_db' set property 'LogXptMode'='ASYNC';
Edit database 'stby_db' set property 'LogXptMode'='ASYNC';

select process,status,thread#,sequence#,block#,blocks from v$managed_standby;

SQL>alter system Set PARALLEL_EXECUTION_MESSAGE_SIZE = 4096 scope = spfile;


http://sanzdbaworld.blogspot.com/2012/09/how-query-dataguard-status-physical.html
onprimary
--------------
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;
}
When using parallel media recovery or parallel standby recovery, increasing the
PARALLEL_EXECUTION_MESSAGE_SIZE database parameter to 4K (4096)
can improve parallel recovery by as much as 20 percent. Set this parameter on
both the primary and standby databases in preparation for switchover operations.
Increasing this parameter requires more memory from the shared pool by each
parallel execution slave process.
4 – Kernel parameters that changed in order to reduce file system cache size.
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
http://emrebaransel.blogspot.com/2008/11/dataguard-performance.html
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 1000 pages
column 9999
computeusername
column SUM
sid format
format
of inactive
9999 a30
a30
on report
column
col program
username format
for 999999
a50
column
column serial for
os_user format a20
select
column DECODE(username,NULL,'INTERNAL',USERNAME)
status format
col LOGON_TIME
Username, fora15
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) AS
EXTRACTVALUE(XMLType(report_summary),'/report_repository_sum "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 ?
SELECT
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')
(SELECT io_secs_per_exec,
TO_CHAR(ROUND(h.ccwait_total
status, / h.executions_total / 1e6, 3),
COL pl_secs HEA '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') cl_secs_per_exec,
TO_CHAR(ROUND(h.plsexec_time_total
sql_id, / h.executions_total /
SELECT 'SQLAREA' source,h.inst_id,(1111/1111) snap_id,
sw.wait_class,
1e6,TO_CHAR(ROUND(h.apwait_total
3), '999,990.000')
sql_exec_id, pl_secs_per_exec, / h.executions_total / 1e6, 3),
TO_CHAR(LAST_LOAD_TIME, 'DD-MON-YYYY HH24:MI')
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_totalAS /
set lines
snap_time, 1500 pages 9999
1e6, sw.seconds_in_wait,
TO_CHAR(ROUND(h.ccwait_total
3), '999,990.000')
sql_exec_start, ja_secs_per_exec / h.executions_total / 1e6, 3),
column sid format 9999
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 = =sw.sid and s.inst_id=sw.inst_id
TO_CHAR(ROUND(h.javexec_time_total
h.sql_id
ROUND(physical_read_bytes /(1024*1024)) and
ASs.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.s
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
ql_id,a.sql_child_number HEA 'Plan|Hash
where sid=&sidValue';
and inst_id=&inst_id
child,b.plan_hash_value,to_char
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'; / 1e6, 3),
TO_CHAR(ROUND(h.JAVA_EXEC_TIME
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_total / h.executions //
type=>'TEXT')
1e6, 3), '999,990.000') cl_secs_per_exec,
et_secs_per_exec,
cc_secs_per_exec,
from dual;
TO_CHAR(ROUND(h.APPLICATION_WAIT_TIME
TO_CHAR(ROUND(h.cpu_time_total
TO_CHAR(ROUND(h.PLSQL_EXEC_TIME / h.executions_total / h.executions
/ h.executions 1e6,3),/
/ /1e6,
All
1e6,in 3),
one'999,990.000') ap_secs_per_exec,
'999,990.000')
3), '999,990.000') cpu_secs_per_exec,
pl_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
/ h.executions_total
/ 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
/ h.executions_total / 1e6,
/ 1e6, 3),3),
ja_secs_per_exec
'999,990.000') 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
UPPER(sql_text);object_name
in ( select
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
PGA/TEMP by sql_id,SQL_EXEC_ID,sql_exec_start
( current )
order by sql_id
)
SELECT
where sql_id sql_plan_hash_Value,
= 'b4tmgwbcjawp5'sql_full_plan_hash_Value,
sql_adaptive_plan_resolved
order by sql_id, run_time_sec desc
,FETCH
COUNT(DISTINCT
FIRST 10 ROWS sql_exec_id),
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
sql_id sess_io.consistent_gets,
inst_id,SESSION_ID,USER_ID,PROGRAM,sql_id,SQL_CHILD_NUMB
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) whereOVER (PARTITION BY sql_id) -
MINfrom gv$sess_io
sql_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
round(time_waited*100
NVL(a.event, / sum(time_waited)
'ON CPU') 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 by
s, gv$process p where paddr=addr and s.sid=&sid
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';


v$session.sid)
/ (SELECT DECODE (VALUE, 0, 1, VALUE)
FROM v$sesstat
WHERE STATISTIC# = 583 AND v$sesstat.SID =
v$session.sid),
2)
AS "Hard Parse, %",
select(SELECT
'alter system
ROUNDkill session
(VALUE ' ||/''''1024
|| sid/ 1024,
|| ',' || serial#
2) ||',@'|| inst_id ||
'''' || ' immediate;' from gv$session where sid='&sid';
FROM v$sesstat
WHERE STATISTIC# = 83 AND v$sesstat.SID = v$session.sid)
AS "Physical read bytes, in MB",
(SELECT ROUND (VALUE / 1024 / 1024, 2)
FROM v$sesstat
WHERE STATISTIC# = 96 AND v$sesstat.SID = v$session.sid)
AS "Physical write bytes, in MB",
(SELECT ROUND (VALUE / 1024 / 1024, 2)
FROM v$sesstat
WHERE STATISTIC# = 185 AND v$sesstat.SID =
v$session.sid)
AS "Redo size, in MB",
(SELECT ROUND (VALUE / 1024 / 1024, 2)
FROM v$sesstat
WHERE
select ' alter system STATISTIC# = 590
kill session AND v$sesstat.SID =
'''||sid||''','''||serial#||''',''@'||inst_id||'''
v$session.sid)
immediate; '
AS "Received
from gv$session where from client, ininMB",
username ('SCHEMA1','SCHEMA2') and
(SELECT ROUND (VALUE
logon_time < sysdate -1 and status='INACTIVE'; / 1024 / 1024, 2)
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;
"ID",B.BEGIN_INTERVAL_TIME,B.END_INTERVAL_TIME,A.RESOUR
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
WHEREENDA.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 signature format 999,999,999,999,999,999,999
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;
/
sql_id likeExplain
script.
PROMPT nvl('&sql_id',sql_id)
Plan from AWR
and other_xml
REM The PRVTPOOL.PLB
PROMPT is not null script is automatically executed after
================================
)
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 inst_id, child_number,
BEGIN ================================ plan_hash_value, executions,
SELECT
is_shareable regexp_replace(extractvalue(value(d),
FOR i IN (SELECT address, hash_value '/hint'),'''','''''') plan_hint
FROM
set
FROM from
linesgv$sql
1000 WHERE
pages
gv$sqlarea sql_idsql_id
9999
WHERE = '&&sql_id.' ORDER BY 1, 2;
= '&sql_id.')
BEGIN
col
LOOP xmltable('/*/outline_data/hint'
name for a30
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
END gv$sqlarea
category
LOOP;for a10 select WHERE sql_id = '&&sql_id.')
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 is not null
col signature for 9999999999999999999999999
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
) d;
SELECT inst_id, loaded_versions, invalidations, address, hash_value
s,prof.SIGNATURE
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 HINTS
FROM sql.sql_id
gv$sql WHERE fromsql_id
PROFILES
in ('&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 Sql Baselines sd, dba_sql_profiles p,
table(xmlsequence(extract(xmltype(sd.comp_data),
PROMPT ================
'/outline_data/hint'))) t
where sd.obj_type = 1
coland p.signature =for
SQL_HANDLE sd.signature
a30
and p.category
col 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
round(
-- filter for the statistic we are interested in
(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,
set and sum(decode(session_state,
lines 155 'WAITING', 1, 0)) as waiting,
round(
count(*) as active_sessions
col stat_start.instance_number
execs for 999,999,999 = snap.instance_number
(variance(sub1.active_sessions)/avg(sub1.active_sessions)),1) as
col) from
min_etime for 999,999.99
act_var_mean
col v$active_session_history
max_etime for 999,999.99
order
from by
where
colstat_start.snap_id
avg_etime for 999,999.999
( -- sub1: one row per second, the resolution of SAMPLE_TIME
col sample_time
avg_lio > sysdate - (&minutes/1440)
for 999,999,999.9
; select
col group by
norm_stddev for 999,999.9999
sample_id,
sample_id,
col begin_interval_time for a30
sample_time,
col node sample_time
for 99999
sum(decode(session_state, 'ON CPU', 1, 0)) as on_cpu,
) sub1
break on plan_hash_value on startup_time skip 1
sum(decode(session_state, 'WAITING', 1, 0)) as waiting,
group by
select * from (
count(*) as active_sessions
round(sub1.sample_time,
select 'MI')
sql_id, sum(execs), min(avg_etime) min_etime, max(avg_etime)
from
order by
max_etime, stddev_etime/min(avg_etime) norm_stddev
dba_hist_active_sess_history
fromround(sub1.sample_time,
( 'MI')
where
;select sql_id, plan_hash_value, execs, avg_etime,
sample_time > sysdate - (&hours/24)
stddev(avg_etime) over (partition by sql_id) stddev_etime
group by
from (
sample_id,
select sql_id, plan_hash_value,
sample_time
sum(nvl(executions_delta,0)) execs,
) sub1
(sum(elapsed_time_delta)/
group by
decode(sum(nvl(executions_delta,0)),0,1,sum(executions_delta))/
round(sub1.sample_time, 'HH24')
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
when trunc(elapsed_time/1000000)<60 then
to_char(trunc(elapsed_time/1000000))||' Sec(s)' set pages 500
set
set lines 1000
linesize 750pages 9999
when trunc(elapsed_time/1000000/60)<60 then column
to_char(trunc(elapsed_time/1000000/60))||' Min(s)' column box format9999
sid format a30
column
column serial for 999999
spid format a10
when trunc(elapsed_time/1000000/60/60)<24 then column
to_char(trunc(elapsed_time/1000000/60/60))||' column status
username format a15 a30
format
column
column username formata30
program format a10
Hour(s)' column
when trunc(elapsed_time/1000000/60/60/24)>=1 column sql_text
os_user format
format a80
a20
column module format a30
then col program for a30
to_char(trunc(elapsed_time/1000000/60/60/24))||' select b.sid,b.serial#,a.spid, substr(b.machine,1,30)
col SQL_EXEC_START
box,b.logon_time logon_date for a20
, to_char
Day(s)'
end) as time (b.logon_time, 'hh24:mi:ss') logon_time,
SELECT * FROM
substr(b.username,1,30) username,
from v$session a,v$sqlarea b (SELECT status,inst_id,sid,SESSION_SERIAL#
where a.sql_address=b.address substr(b.osuser,1,20) os_user,
as
substr(b.program,1,30) program,status,b.last_call_et
and a.sql_hash_value=b.hash_value Serial,username,sql_id,SQL_PLAN_HASH_VALUE,
and users_executing>0 AS last_call_et_secs,b.sql_id
MODULE,program,
from v$session b,v$process a
and elapsed_time/1000000>30;
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
col program (or)a33
for ERROR you can rewrite the sql using below hint
col USERNAME 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(XMLType
col START_TIME for a10 = 'sqlmonitor' and
WHERE
SELECT
col
component_name
* FROM
LAST_UPDATE_TIME for a10
(report_summary),'/
(EXTRACTVALUE(XMLType(report_summary),'/repor report_repository_summary/sql/stats/
col (SELECTfor
TARGET status,inst_id,sid,SESSION_SERIAL#
a25 COLUMN sid FORMAT 99999
t_repository_summary/sql/@sql_id'))='&sql_id' and
as
col MESSAGE
snap_id=&snap_id; for a25 stat[@name="elapsed_time"]'))
COLUMN serial# FORMAT 9999999
Serial,username,sql_id,SQL_PLAN_HASH_VALUE,pr
alter session set nls_date_format = 'DD-MM-YYYY COLUMN machine FORMAT A30
ogram,
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 MINS",
"REMAIN (s)", 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 ROUND(user_io_wait_time
BI for 990
'999,999,990.000'), 18) cpu_secs,/1000000,3) AS NVL(p.plan_parent_id,'0') || ')',8) || '|' ||
COL
"I/OBS se.total_waits,
executions_total
instance_number
wait FOR
FOR999,999
9999 HEA HEA 'Execs|
'Inst'; COL end_time HEA 'End Time';
col for(s)",
9999 RPAD(LPAD (' ', 2*p.plan_DEPTH) ||
Total';
COL
SELECT se.total_timeouts,
end_time
'DBA_HIST'HEA 'End
ROUND(application_wait_time/1000000,3) Time'; AS COL plan_hash_value
p.plan_operation || ' ' || HEA 'Plan|Hash Value';
p.plan_options,60,'.') ||
col PI for 99
LPAD(TO_CHAR(ROUND(user_io_wait_time/1e6, 3),
COL se.time_waited,
rows_per_exec
plan_hash_value
source,h.instance_number,h.SNAP_ID,
"Appli waitfor (s)", HEA
HEA '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'; AS 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, p.plan_object_owner||
COL
col se.max_wait,
cpu_secs_per_exec
SQL_PROFILE for a30 HEA
EXTRACTVALUE(XMLType(s.report_summary),'/repo
"Concurrency 'CPU Secs|Per Exec'; COL executions_total FOR 999,999 HEA 'Execs|
col
3), PSID for a5wait (s)", 18) cluster_wait_secs,
'999,999,990.000'), ') ', '') ||
COL se.time_waited_micro
io_secs_per_exec
executions_total FORHEA
rt_repository_summary/sql/@sql_exec_start')
ROUND(cluster_wait_time 'IO
999,999 Secs|Per
HEA Exec';
'Execs| Total';
select a.inst_id i, a.sid, a.serial#,/1000000,3) b.qcsid "PSID", AS NVL2(p.plan_COST,'Cost:' || p.plan_COST,'') || ' '
FROM
COL
Total';
start_time,
"Cluster v$session_event
cl_secs_per_exec
wait a.osuser,
(s)", se, 'Clus Secs|Per Exec';
HEA COL
|| rows_per_exec HEA 'Rows |Per Exec';
a.username, a.machine,a.status,
LPAD(TO_CHAR(ROUND(application_wait_time/1e6,
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 COL select 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
COL s.sid
cc_secs_per_exec
et_secs_per_exec= se.sid HEA
HEA
EXTRACTVALUE(XMLType(s.report_summary),'/repo
"Phys reads (MB)", 'Conc
'Elap Secs|Per
Secs|Per Exec';
Exec'; from
COL V$SESS_TIME_MODEL
cpu_secs_per_exec HEA 'CPU Secs|Per Exec';
p.plan_bytes || ' bytes, ' || p.plan_CARDINALITY || '
"RunT (M)",seconds_in_wait/60 "Seconds
AND
COL s.sid = &Session_ID
pl_secs_per_exec
cpu_secs_per_exec
rt_repository_summary/sql/@sql_exec_id')
ROUND(physical_write_bytes HEA
HEA 'PLSQL
'CPU Secs|PerExec';
Secs|Per
/(1024*1024)) Exec';
AS where
COL sid|| =' ' &sid
io_secs_per_exec
rows)','') || HEA 'IO Secs|Per Exec';
Wait(M)",a.blocking_session
LPAD(TO_CHAR(ROUND(concurrency_wait_time/1e BS,a.blocking_instance
ORDER
COL BY se.time_waited
ja_secs_per_exec DESC
'Java Secs|Per Exec'; order by value desc;
BI 3), io_secs_per_exec
sql_exec_id,
"Phys
6, writes (MB)",
'999,999,990.000'), HEA
18) 'IO Secs|Per
conc_wait_secs, Exec'; COL cl_secs_per_exec
NVL2(p.plan_partition_start HEA 'Clus || Secs|Per Exec';
/COL
SELECTh.sql_id,
buffer_getsh.instance_number,h.SNAP_ID,
cl_secs_per_exec HEA 'Clus AS Secs|Per
"Buffer Exec';
gets", COL ap_secs_per_exec
p.plan_partition_stop,' HEA
PStart:' 'App
|| Secs|Per Exec';
fromLPAD(TO_CHAR(ROUND(plsql_exec_time/1e6,
gv$session a, gv$px_session b column my_sid format 999
COL
Each
where TO_CHAR(CAST(s.begin_interval_time
ap_secs_per_exec
Layer time spend18)
h.plan_hash_value,sql_profile,
ROUND(plsql_exec_time/1000000,3) HEA 'App Secs|Per AS Exec';
AS COL
Explaincc_secs_per_exec
Plan waiting
p.plan_partition_start
column my_ser formatsteps HEA 'Conc
||99999
' PStop:' || Secs|Per Exec';
3), '999,999,990.000'), plsql_exec_secs,
DATE),
COL
"Plsql 'DD-MM-YYYY
cc_secs_per_exec
h.executions_total,
exec
a.last_call_et (s)",
>0 HH24:MI')
HEA 'Conc snap_time,
Secs|Per Exec'; COL pl_secs_per_exec
p.plan_partition_stop,'')
column my_state format||HEA a30 '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 HEA
TO_CHAR(ROUND(h.rows_processed_total 'PLSQL
/1000000,3) Secs|Per ASExec';
/ Exec';
column program
NVL2(p.plan_time, format a30
--and
3), a.status = 'ACTIVE'
'999,999,990.000'), 18) java_exec_secs, column
"Elapsed (s)", formatp.plan_time
my_blkr 999 || '(s)','') AS PLAN
--andh.plan_hash_value,
COL
"Java ja_secs_per_exec
h.executions_total),
exec (s)"
a.username HEA 'Java Secs|Per Exec';
in'999,999,999,999')
('DELPHI')
LPAD(TO_CHAR(io_cell_offload_eligible_bytes, COL
column
select ja_secs_per_exec
FROM username formatHEA
gv$sql_plan_monitor
to_char(a.sample_time,
ROUND(cpu_time a30'Java p Secs|PerAS
'HH24:MI:SS')
/1000000,3) Exec';
"CPU
COL h.executions_total,
FROMDISK_READS_TOTAL
rows_per_exec,
--and Machine gv$sql_monitor
in HEA 'Disk|reads'; COL
column DISK_READS_TOTAL
WHERE sql_id format
sid=&sid a13
MY_TIME,a.session_id MY_SID,a.session_serial# HEA 'Disk|reads';
'999,999,999,999,999,999,990'),
SELECT * 30) (s)",
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 query_runs.*, HEA
BY p.plan_line_id, p.plan_parent_id;
MY_SER,SQL_PLAN_HASH_VALUE,SQL_CHILD_ 'Buffer|gets';
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') col execs
ROUND
NUMBER,(s)", for
( 999,999,999
(end_time - start_time) * 24, 2) AS
LPAD(TO_CHAR(io_interconnect_bytes,
(SELECT status, "Queuing
rows_per_exec,
select * from not( in
SELECT col avg_etime for 999,999
et_secs_per_exec,
and event ('Streams AQ: waiting
'999,999,999,999,999,999,990'),
--username, 30) for messages select duration_hrs* from ( SELECT
DECODE(a.session_state,
ROUND(application_wait_time/1000000,3) 'WAITING' ,a.event, AS
in TO_CHAR(ROUND(h.elapsed_time_total
h.instance_number,h.SNAP_ID,
TO_CHAR(ROUND(h.cpu_time_total
the sql_id,
queue') / / col avg_lio for 999,999,999
h.instance_number,h.SNAP_ID,
FROM
a.session_state)
io_interconnect_bytes,
v$sqlarea ( ALL ) 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') col avg_pio for 999,999,999
h.sql_id,sql_profile,
(SELECT u.username,
a.blocking_session MY_BLKR
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 (+) col
from begin_interval_time
h.plan_hash_value,
ash.program,
gv$active_session_history for a30 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 node
ash.sql_id,for 99999
h.executions_total,
u.user_id = a.user_id
io_interconnect_bytes
hh24:mi:ss') AS sql_exec_start, THEN ROUND(cluster_wait_time /1000000,3) AS
h.executions_total
/ / 1e6,
TO_CHAR(ROUND(h.rows_processed_total3), '999,990.000') / break on plan_hash_value
TO_CHAR(ROUND(h.rows_processed_total
ASH.SQL_PLAN_HASH_VALUE
and a.sql_id on startup_time skip AS 1 /
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') select ss.snap_id,
h.executions_total),
plan_hash_value,
andROUND(user_io_wait_time ss.instance_number
'999,999,999,999')
a.sample_time > SYSTIMESTAMP-(2/1440); node,
AS "Elapsed(io_cell_offload_eligible_bytes
(s)", - /1000000,3) AS
TO_CHAR(ROUND(h.iowait_total
rows_per_exec, / begin_interval_time, sql_id, plan_hash_value,
v$sql
TO_CHAR(ROUND(h.clwait_total
io_interconnect_bytes)
ROUND(cpu_time
( sql_id ) * 100 /
/1000000) AS rows_per_exec,
"UserASH.SESSION_ID
io wait (s)", AS sess#,
h.executions_total / 1e6, 3), '999,990.000')
TO_CHAR(ROUND(h.elapsed_time_total / nvl(executions_delta,0)
TO_CHAR(ROUND(h.elapsed_time_total
ASH.SESSION_SERIAL# execs, / AS
AS sess_ser,
io_cell_offload_eligible_bytes
"CPU (s)", ROUND(physical_read_bytes /(1024*1024))
io_secs_per_exec,
h.executions_total
cl_secs_per_exec, / 1e6, 3), '999,990.000') (elapsed_time_delta/
h.executions_total
CAST (MIN / 1e6,
(ASH.SAMPLE_TIME) 3), '999,990.000') AS DATE) AS
, 2), '990.00')||' %', 8) END io_saved
buffer_gets, "Phys reads (MB)",
TO_CHAR(ROUND(h.clwait_total
et_secs_per_exec,
TO_CHAR(ROUND(h.apwait_total // decode(nvl(executions_delta,0),0,1,executions_delta
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, 3), '999,990.000')/
TO_CHAR(ROUND(h.cpu_time_total ))/1000000 avg_etime,
TO_CHAR(ROUND(h.cpu_time_total
CAST (MAX (ash.sample_time) AS DATE) / AS
WHERE
"Phys sql_id
reads = '&sql_id'
(MB)", "Phys writes (MB)",
cl_secs_per_exec,
h.executions_total
ap_secs_per_exec, / 1e6, 3), '999,990.000') (buffer_gets_delta/
h.executions_total
end_time / 1e6, 3), '999,990.000')
ORDER BY 1, 2;
ROUND(physical_write_bytes/(1024*1024)) AS buffer_gets AS "Buffer gets",
TO_CHAR(ROUND(h.apwait_total
cpu_secs_per_exec,
TO_CHAR(ROUND(h.ccwait_total // decode(nvl(buffer_gets_delta,0),0,1,executions_delt
cpu_secs_per_exec,
FROM dba_hist_active_sess_history ash, AS
"Phys writes (MB)"
Elapsed/CPU/Read/Write MB Each ROUND(plsql_exec_time/1000000,3)
Layer time spend
h.executions_total / 1e6, 3), '999,990.000')
TO_CHAR(ROUND(h.iowait_total / a))dba_users
avg_lio,
TO_CHAR(ROUND(h.iowait_total
u /
FROM gv$sql_monitor where sql_id='&sql_id' "Plsql exec (s)",
ap_secs_per_exec,
h.executions_total
cc_secs_per_exec / 1e6, 3), '999,990.000') ROUND(disk_reads_delta/
h.executions_total
WHERE u.user_id / 1e6,
= 3), '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, / DECODE(executions_delta,0,1,
io_secs_per_exec,
AND exec ash.sql_id executions_delta),1)
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') / avg_pio,
GROUPTO_CHAR(ROUND(h.clwait_total
BY u.username, /
) FROM gv$sql_monitor
cc_secs_per_exec,
h.executions_total
WHERE h.sql_id =/ 1e6,
'&sql_id'3), '999,990.000') ROUND(rows_processed_delta/
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 = / DECODE(executions_delta,0,
cl_secs_per_exec,
ash.sql_id, 1, executions_delta),
AWR data (More
h.executions_total detailed)
/ 1e6, 3), '999,990.000') SHORT Report
1) ASH.SQL_PLAN_HASH_VALUE,
avg_rows,
TO_CHAR(ROUND(h.apwait_total
(EXTRACTVALUE(XMLType(s.report_summary),'/rep / TO_CHAR(ROUND(h.apwait_total /
pl_secs_per_exec,
h.executions_total / 1e6, 3), '999,990.000')
ort_repository_summary/sql/@sql_id')) round(px_servers_execs_delta/
h.executions_total
ASH.SESSION_ID, / 1e6, 3), '999,990.000')
TO_CHAR(ROUND(h.javexec_time_total
ap_secs_per_exec,
AND s.snap_id = h.snap_id / decode(executions_delta,0,1,
ASH.SESSION_SERIAL# executions_delta), 1)
ap_secs_per_exec,
h.executions_total
AND s.dbid = h.dbid / 1e6, 3), '999,990.000')
TO_CHAR(ROUND(h.ccwait_total / 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 source,snap_id,start_time h, ; 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,
Top DISK_READS_TOTAL
I/O Used ,BUFFER_GETS_TOTAL Top DISK_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
set long 20000
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'|',
by1,sample_time
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 ( sql_text format a800 over greatest(PGA_ALLOCATED -
column
(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
max(sample_time) end_time, "DELTA_PGA_MB"
status='EXECUTING' and module not like '%emagent NAME,POSITION,DATATYPE_STRING,VALUE_ST
where
TABLE(dbms_xplan.display_awr('&sql_id', null, null, from
%' sql_exec_start starting_time, RING FROM gv$sql_bind_capture WHERE
'ALL')) sample_time >= to_date ('2013/04/16
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 < to_date
plan_table_outputPGA_ALLOCATED,
sum(DELTA_PGA) ('2013/04/16
like '%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
from sql_exec_start
BY owner, is not
table_name, nullindex_name order by 1,2,3,4
/ and
( IS_SQLID_CURRENT='Y' )
) select
PGA/TEMP ( History )sql_id, group
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
ordergreatest(PGA_ALLOCATED
by sql_id, run_time_sec desc; - /
select s.sid, s.serial#, p.spid, s.username, 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(+)
wherefrom 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_fulltextisfromnot 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_TIME wait_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 (Only999999999 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
ROUND (time_waited_micro / 1000) AS
from V$SYSTEM_WAIT_CLASS 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') from


select distinct sid OwnSID from v$mystat; 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 ELAPS

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;
output :=
SYS.DBMS_SQLTUNE_INTERNAL.I_CREATE_SQ
L_PROFILE(
SQL_TEXT => sql_txt,
PROFILE_XML =>
DBMS_SMB_INTERNAL.VARR_TO_HINTS_XML(h)
,
name => 'coe_5273fz2cqkk80_3455548535',
description => 'coe 5273fz2cqkk80
3455548535 '||:signature||' '||:signaturef||'',
CATEGORY => 'DEFAULT',
CREATOR => 'SYS',
VALIDATE
set lines => TRUE,
1000 pages 9999
TYPE for
col name => a30
'PATCH',
FORCE_MATCH for
col task_exec_name => a16
TRUE,
IS_PATCH
col category for=> TRUE);
a10
DBMS_LOB.FREETEMPORARY(sql_txt);
col created for a30
dbms_output.put_line(output);
col 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)||''''|| SELECT chr(9)||chr(9)||''''||
dbms_spm.drop_sql_plan_baseline('SQL_b3d69637a
regexp_replace(extractvalue(value(d), variable sqlid number;
regexp_replace(extractvalue(value(d),
a86a8ca');
'/hint'),'''','''''')||''',' execute :sqlid :=DBMS_SPM.LOAD_PLANS_FROM
'/hint'),'''','''''')||''','
dbms_output.put_line(i);
from _CURSOR_CACHE(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-n
http://expertoracle.com/2015/07/08/flush-bad-sql-plan-from-shared-pool/
GE,0)) "16",
max(decode(to_char(END_TIME,'HH24'),'17',AVERA
GE,0)) "17",
max(decode(to_char(END_TIME,'HH24'),'18',AVERA
GE,0)) "18",
max(decode(to_char(END_TIME,'HH24'),'19',AVERA
GE,0)) "19",
max(decode(to_char(END_TIME,'HH24'),'20',AVERA
GE,0)) "20",
set pages 100 max(decode(to_char(END_TIME,'HH24'),'21',AVERA
select INSTANCE_NUMBER, GE,0)) "21",
SUM(value), max(decode(to_char(END_TIME,'HH24'),'22',AVERA
to_char(trunc(end_time,’HH’),’dd-mm-yyyy hh24:mi’) GE,0)) "22",
as sample_time max(decode(to_char(END_TIME,'HH24'),'23',AVERA
from dba_hist_sysmetric_history GE,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 Machine .........................................:
'stats/stat[@name="duration"]' , application_wait_time path https://
'||s.machine,
, elapsed_time path 'stats/stat[@name="application_wait_tim mauro-
'LAST_CALL_ET .......................................
'stats/stat[@name="elapsed_time"]' e"]' pagano.c
....: '||s.last_call_et,
, cpu_time path , concurrency_wait_time path om/
'S.LAST_CALL_ET/
'stats/stat[@name="cpu_time"]' 'stats/stat[@name="concurrency_wait_ti 2015/05/0
3600 ....................................: '||
, user_io_wait_time path me"]' 4/
s.last_call_et/3600
'stats/stat[@name="user_io_wait_time"]' , cluster_wait_time path SELECT historical-
from v$session s, v$process p
, application_wait_time 'stats/stat[@name="cluster_wait_time"]' report_id, sql-
where p.addr=s.paddr and path
'stats/stat[@name="application_wait_time" , plsql_exec_time path key1 monitor-
s.sid=nvl('&sid',s.sid) and
]'p.spid=nvl('&spid',p.spid) and 'stats/stat[@name="plsql_exec_time"]' sql_id, reports-in-
, concurrency_wait_time path , other_wait_time path key2 12c/
nvl(s.process,-1) =
'stats/stat[@name="concurrency_wait_tim 'stats/stat[@name="other_wait_time"]' sql_exec_
nvl('&ClientPid',nvl(s.process,-1)); http://allappsdba.blogspot.com/2012/04/queries-to-get-session-information.html
e"]' , buffer_gets path id, key3 http://
, cluster_wait_time path 'stats/stat[@name="buffer_gets"]' sql_exec_ www.toad
'stats/stat[@name="cluster_wait_time"]' , read_reqs path start world.com
, plsql_exec_time path 'stats/stat[@name="read_reqs"]' FROM /
'stats/stat[@name="plsql_exec_time"]' , read_bytes path dba_hist_ platforms/
, other_wait_time path 'stats/stat[@name="read_bytes"]' reports oracle/
'stats/stat[@name="other_wait_time"]' ) x1 WHERE w/wiki/
, buffer_gets path where x1.elapsed_time/1000000 > 200 compone 11372.rea
ALTER SESSION SET
'stats/stat[@name="buffer_gets"]' and t.COMPONENT_NAME = nt_name l-time-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/ MINUTES, Sql_Text
MON/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)/DECOD when begin_interval_time >= sql_id,
,px_servers_executions/decode(nvl(execut
/* st.parsing_schema_name
E(ss.executions_delta,0,1,ss.executions_ to_date('14-nov-2017 1100','dd-mon-
ions,0),0,1,executions)
,select
delta) st.plan_hash_value avg_px,
to_char(sql_exec_start,'dd.mm.yyyy
ela_per_exec, yyyy hh24mi') then s.executions_total sql_plan_
,hh24:mi:ss') optimizer_cost
SUM(st.fetches_delta)
(ss.cpu_time_delta as cost,fch else 0 hash_valu
,LAST_LOAD_TIME
SQL_EXEC_START, SUM(rows_processed_delta)
/1000000)/DECODE(ss.executions_delta, timestamp, rws end) - e,
,parsing_schema_name
0,1,ss.executions_delta) max(sample_time) ---cpu_per_exec,
SUM(executions_delta) execs sum(case
,FIRST_LOAD_TIME,
SQL_EXEC_START ss.buffer_gets_delta LAST_LOAD_TIME, as when begin_interval_time < to_date('14- event,sql_
LAST_ACTIVE_TIME, select vsn.name, vst.value
ROUND(SUM(elapsed_time_delta)/1000/
duration, 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
elp
sql_exec_id,
cutions_delta) lio_per_exec, then s.executions_total
,where vsn.statistic#
sql_id =
sql_plan_hash_value, = vst.statistic#
nvl(trim('&sql_id'),sql_id)
ss.disk_reads_delta else 0 sql_exec_
and vst.value
UNION 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
order
INST_ID,
),0),1),2) by vst.value;
t1.sql_id
elpe a150 sql_id, s,
round(max(temp_space_allocated) /
FROM
col PLAN dba_hist_snapshot
FOR dba_hist_sqlstat s, current_o
,t1.plan_hash_value
1024
SELECT / 1024
dba_hist_sqlstat / 1024, ss plan_hash_value,
3) as max_temp_gb, dba_hist_snapshot sn bj#,
t2.avg_et_secs
ROUND(SUM(cpu_time_delta)/1000/1000 avg_et_secs,
round(max(pga_allocated) t2.avg_px,
WHERE RPAD('(' ss.dbid
|| p.plan_line_ID = s.dbid || ' ' || / 1024 where
)t1.cost
AND cpu
/NVL(p.plan_parent_id,'0')
1024 /cost,
1024, t1.timestamp
3) as max_pga_gb,
ss.instance_number timestamp,
||= ')',8) || '|' || sn.begin_interval_time between sql_plan_l
,NULL
s.instance_number parsing_schema_name
SUM(buffer_gets_delta)
max(px_used)
RPAD(LPAD (' ', 2*p.plan_DEPTH) gets || to_date('05-nov-2017 0001','dd-mon- ine_id,
FROM
,p.plan_operation
ANDas dba_hist_sql_plan
max_px_used
ss.snap_id t1,
|| ' ' ||= s.snap_id 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(S
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_
UM(executions_total),0,1,SUM(executions
just cl
asconsider
temp_space_allocated,
only rows
p.plan_object_name || ')proceesed
', '') || and sn.snap_id=s.snap_id options
,_total))/1e6,2)
calculate avg_et_secs
sum(pga_allocated)
total execution
NVL2(p.plan_COST,'Cost:' time =||sum group by )
ROUND(SUM(ccwait_delta)/1000/1000)
as
p.plan_COST,'') pga_allocated,
( executions_delta || ' 1' ||+ executions_delta s.sql_id order by
round(SUM(elapsed_time_total)/decode(S
0 )cc */ count(distinct session_serial#) - order by count_1
NVL2(p.plan_bytes||
,UM(executions_total),0,1,SUM(executions
1
ORDER as px_used,
p.plan_CARDINALITY,'(' BY s.snap_id; || p.plan_bytes || difference desc; desc;
_total))/1e6/
ROUND(SUM(apwait_delta)/1000/1000) select x.*, (SELECT sql_text from
' bytes, ' ||sample_time p.plan_CARDINALITY || '
rows)','') ap from || ' dba_hist_active_sess_history
' || dba_hist_sqltext t where t.sql_id =
,decode(SUM(px_servers_execs_total),0,1
where sql_id =
NVL2(p.plan_partition_start || '&&1' x.sql_id and rownum = 1) txt
,SUM(px_servers_execs_total))/
ROUND(SUM(plsexec_time_delta)/1000/1
and snap_id between &2 and from (
p.plan_partition_stop,' PStart:' ||
decode(SUM(executions_total),0,1,SUM(e
000)
nvl('&&3', pl &&2) SELECT snap_id
p.plan_partition_start || ' PStop:' ||
xecutions_total)),2)
,p.plan_partition_stop,'')
ROUND(SUM(disk_reads_delta))
and sql_exec_id avg_et_secs,
> 0 , sql_id
||
disk_reads
group by sql_exec_start,
NVL2(p.plan_time, p.plan_time || '(s)','') ,
sql_id, instance_number
Explain Plan waiting steps
,SUM(px_servers_execs_total)/decode(SU
sql_exec_id,
AS PLAN ROUND(SUM(direct_writes_delta))
sql_plan_hash_value, , parsing_schema_name
M(executions_total),0,1,SUM(executions_t
module, direct_writes
action, sample_id, sample_time , plan_hash_value,
FROM gv$sql_plan_monitor p
,otal)) avg_px
ROW_NUMBER()
having over
sum(temp_space_allocated)
WHERE sql_id='&sql_id' (PARTITION s.CPU_TIME_TOTAL,
BY
is not ORDERnull)FROM
sn.dbid, BY
dba_hist_sqlstat
sn.snap_id,
p.plan_line_id, RANK() OVER (ORDER BY
st.instance_number
group 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
sql_exec_id, sql_plan_hash_value,executions_total
ORDER BY >0 _total)) DESC) cpu_rank,
AWR -- FULL GROUP BYDetails --check sql_id,rn Current Memory
SUM(elapsed_time_delta)
module, action 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 <== Advanced
SELECT
elapsed_rank * 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 '16-AUG-18
where
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_in
fo;

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
() * 100)||'%',10,' ') percent
order by 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 username = 'A' and
i.sid=s.sid
STATUS = 'ACTIVE';
and p.addr=paddr(+) 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
ME) ='SYS' ORDER BY ELAPSED_TIME DESC
' || l_plans_altered);
END;
/ SQL_PLAN_d6ccg6ggusyy2ee7f0c12

SET SERVEROUTPUT ON YES


DECLARE
l_plans_altered PLS_INTEGER;
BEGIN variable sqlid number;
l_plans_altered := exec :sqlid :=DBMS_SPM.ALTER_SQL_
DBMS_SPM.alter_sql_plan_baseline( PLAN_BASELINE ( 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 :=DBMS_SPM.LOAD_PL
l_plans_altered PLS_INTEGER; ANS_FROM_CURSOR_CACHE(sql_id=
BEGIN >'5qbbnv0abm2vx',
l_plans_altered := PLAN_HASH_VALUE=> 4197102931,
DBMS_SPM.alter_sql_plan_baseline( 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_CURS
attribute_value
select => 'YES');
hint as outline_hints OR('5qbbnv0abm2vx',&childnumber,'AL
from (select p.name, p.signature, LSTATS
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'),'''','''''') plan_hint +BYTES'));
+COST
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/2017

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


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
Herea.name,
is a technique I use when troubleshooting runaway query. It is based on data from v$sql_plan_statistics already menti
round((dh.tablespace_size*
alternative to 10046 traces. A.BLOCK_SIZE)/1024/1024,2)
The biggest obstacle to a wide begin_allocated_space,
adoption is the horrible slowness caused by high CPU overhead in
round((dh.tablespace_usedsizethe * A.BLOCK_SIZE)/1024/1024,2)
execution of the query is staged begin_Used_space
in a separate session where we can set statistics_level=all
from dba_hist_tbspc_space_usage dh,c,a --,b
where dh.snap_id = c.Begin_snap_ID – Find SQL_ID / Child_number of runway SQ
and a.ts# = dh.tablespace_id – Find plan_hash_value from v$sql using SQL_ID
and a.name = c.namethe query is using bind variables, capture bind variables from v$sql_bind_capture. There can be problem
– Assuming
), – In a separate session “alter session set sta
e as ( – Start executing SQL in this session. If there were bind variables, set same values and
select a.name, – If the query is absolutely hopeless, cancel execution (send break) after so
round((tablespace_size*a.block_size)/1024/1024,2)
– Find SQL_ID of just executed query by lookingEnd_allocated_space,
in v$session.prev_sql_id. If sql text was not changed, the SQL_ID should
round((tablespace_usedsize*a.block_size)/1024/1024,2) End_Used_space previous steps;
from– dba_hist_tbspc_space_usage,c ,a
Examine plan statistics from v$sql_plan_statistics. The beauty of plan statistics is that it provides data even on partial exe
where snap_id
familiar = c.End_Snap_ID
with them and having a decent viewer, one should be able to see absolutely clear where the problem is. No guess w
and a.ts# = dba_hist_tbspc_space_usage.tablespace_id steps where it will be running for lo-o-ong time, they
and a.name = c.name
) This recipe looks rather tedious, and it really is, unless the tool is used that does all that things. The point is, once I was free
selectbut
e.name,to_char(c.begin_time,'DD-MON-YYYY') Begin_time,d.begin_allocated_space
simply expensive queries with a lot of gets/execution. I should add that it makes sense "Begin_allocated_space(MB)",
to use this technique in really c
d.begin_Used_space "Begin_Used_space(MB)", execution plan is enough to spot the
to_char(c.End_time,'DD-MON-YYYY') End_Time, e.End_allocated_space "End_allocated_space(MB)", e.End_Used_space
"End_Used_space(MB)",
(e.End_Used_space - d.begin_Used_space)"Total Growth(MB)", (c.End_time - c.begin_time)"No.of days",
round(((e.End_Used_space - d.begin_Used_space)/(c.End_time - c.begin_time))*30,2) "Growth(MB)_in_next30_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 - c.begin_time))*60,2) "Growth(MB)_in_next60_days",
Weekly
round(((e.End_Used_space - d.begin_Used_space)/(c.End_time - 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
set feedback off sn,
dba_hist_seg_stat
select * from (selecta,to_char(end_interval_time, 'MM/DD/YY') mydate, sum(space_used_delta) / 1024 / 1024 "Space used
dba_objects b,
(MB)", avg(c.bytes) / 1024 / 1024 "Total Object Size (MB)",
dba_segments c
round(sum(space_used_delta) / sum(c.bytes) * 100, 2) "Percent of Total Disk Usage"
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 by c.TABLESPACE_NAME,c.segment_name,b.object_type)
and sn.snap_id = a.snap_id
orderb.object_id
and by 3 asc; = a.obj#
and b.owner = c.owner
and b.object_name = c.segment_name
and c.segment_name = '&segment_name'
set
group serveroutput on
by to_char(end_interval_time, 'MM/DD/YY'))
prompt
order by to_date(mydate, 'MM/DD/YY');
-- This makes it possible to 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_NAME,
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));

Current
SET LINESIZE 200 PAGESIZE 50000
COL BEGIN_TIME FORMAT A17
COL END_TIME FORMAT A17
COL INST_ID FORMAT 999
COL "Min Response Time (msecs)" FORMAT 999,999,999,999.99
COL "Avg Response Time (msecs)" FORMAT 999,999,999,999.99
COL "Max Response Time (msecs)" FORMAT 999,999,999,999.99

SELECT TO_CHAR (BEGIN_TIME, 'DD-MON-YYYY HH24:MI') BEGIN_TIME,


TO_CHAR (END_TIME, 'DD-MON-YYYY HH24:MI') END_TIME,
INST_ID,
ROUND (MINVAL * 10, 2) "Min Response Time (msecs)",
ROUND (AVERAGE * 10, 2) "Avg Response Time (msecs)",
ROUND (MAXVAL * 10, 2) "Max Response Time (msecs)"
FROM GV$SYSMETRIC_SUMMARY
WHERE 1 = 1
AND METRIC_NAME = 'SQL Service Response Time'
ORDER BY INST_ID;

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 status,
--username,
sql_id,
sql_exec_id,
selectTO_CHAR(sql_exec_start,'dd-mon-yyyy
* from hh24:mi:ss') AS sql_exec_start,
(selectROUND(elapsed_time/1000000)
s.sql_id, RANK() OVER (ORDER BY (max(s.CPU_TIME_TOTAL/s.executions_total))
AS "Elapsed (s)", DESC) cpu_rank,
RANK() OVER (ORDER BY
ROUND(cpu_time /1000000) (max(s.ELAPSED_TIME_TOTAL/s.EXECUTIONS_TOTAL))
AS "CPU (s)", DESC) elapsed_rank
from buffer_gets,
dba_hist_sqlstat s,
ROUND(physical_read_bytes /(1024*1024)) AS "Phys reads (MB)",
dba_hist_snapshot sn
ROUND(physical_write_bytes/(1024*1024)) AS "Phys writes (MB)"
whereFROM v$sql_monitor
sn.begin_interval_time
ORDER BY elapsed_time between to_date('06-aug-2014 0001','dd-mon-yyyy hh24mi')
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, es
exec dbms_stats.gather_index_stats ( ownname => '&OWNER', indname => '&INDEX_NAME',estimate_percent => dbms_sta
exec DBMS_STATS.GATHER_SCHEMA_STATS (ownname => '&OWNER' , estimate_percent => dbms_stats.auto_sample_s
EXEC DBMS_STATS.GATHER_DATABASE_STATS(ESTIMATE_PERCENT => DBMS_STATS.AUTO_SAMPLE_SIZE, MET
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 o.obj#=n.object_id and n.object_name='&Object_name'
and n.owner='&owner' order by time;
SET ECHO OFF
SET TERMOUT ON
select 'execute DBMS_STATS.GATHER_SCHEMA_STATS('''||username||''') ;' from dba_users where username <> 'SYS';
SET SERVEROUTPUT ON
SET TIMING OFF
DECLARE
v1 varchar2(100);
v2 varchar2(100);
colv3TABLE_NAME
varchar2(100);for a30
colv4PARTITION_NAME
varchar2(100); for a20
colv5SUBPARTITION_NAME
varchar2(100); for a20
select OWNER,TABLE_NAME,PARTITION_NAME,SUBPARTITION_NAME,NUM_ROWS,LAST_ANALYZED from
v6 varchar2(100);
dba_TAB_STATISTICS
v7 varchar2(100); where STALE_STATS='YES';
v8 varchar2(100);
SELECT CLIENT_NAME, STATUS FROM DBA_AUTOTASK_CLIENT WHERE CLIENT_NAME='auto optimizer stats
v9 varchar2(100);
collection';
v10 varchar2(100);
BEGIN
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);
v2 := dbms_stats.get_prefs('CASCADE');
dbms_output.put_line(' CASCADE: ' || v2);
v3 := dbms_stats.get_prefs('DEGREE');
SELECT TABLES.OWNER,
dbms_output.put_line(' TABLES.TABLE_NAME,
DEGREE: ' || v3);
ROUND((DELETES + UPDATES + INSERTS)/NUM_ROWS*100) PERCENTAGE
v4 := dbms_stats.get_prefs('ESTIMATE_PERCENT');
FROM DBA_TABLES TABLES,
dbms_output.put_line(' DBA_TAB_MODIFICATIONS
ESTIMATE_PERCENT: ' || v4); MODIFICATIONS
WHERE TABLES.OWNER = MODIFICATIONS.TABLE_OWNER
v5 := dbms_stats.get_prefs('METHOD_OPT');
AND TABLES.TABLE_NAME
dbms_output.put_line(' = MODIFICATIONS.TABLE_NAME
METHOD_OPT: ' || v5); AND NUM_ROWS > 0
AND ROUND
v6 := ( (DELETES + UPDATES + INSERTS) / NUM_ROWS * 100) >= 10
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
SELECT where m.wait_class_id=n.wait_class_id
sysmetric_history.sample_time,
DECLARE
cpu/60 and n.wait_class != 'Idle'
AS cpu,
l_sql_tune_task_id
bcpu/60groupAS bybcpu, VARCHAR2(100);
decode(n.wait_class,'User I/O','User I/O', 'Commit','Commit', 'Wait')
BEGIN union
DECODE(SIGN((cpu+bcpu)/60-cpu_ora_consumed), -1, 0, ((cpu+bcpu)/60-cpu_ora_consumed)) AS cpu_ora_wait,
l_sql_tune_task_id := DBMS_SQLTUNE.create_tuning_task ( CLASS,
select 'CPU_ORA_CONSUMED'
scheduler/60 AS scheduler,
uio/60 AS uio, sql_id => '4pgqpkv31u4nn',
round(value/100,3) AAS
sio/60 ASfrom scope => DBMS_SQLTUNE.scope_comprehensive,
v$sysmetric
sio,
time_limit
where metric_name='CPU
concurrency/60 => 2100,Usage Per Sec'
AS concurrency,
application/60 task_name
and group_id=2
AS => '4pgqpkv31u4nn_tuning_task',
application,
union ASdescription
COMMIT/60 COMMIT, => 'Tuning task for statement d4pgqpkv31u4nn.');
DBMS_OUTPUT.put_line('l_sql_tune_task_id:
select 'CPU_OS'
configuration/60 AS configuration, ' || l_sql_tune_task_id);
CLASS ,
END; round((prcnt.busy*parameter.cpu_count)/100,3)
administrative/60 AS administrative, AAS
/ network/60
from AS network,
( select
queueing/60 ASvalue busy from v$sysmetric where metric_name='Host CPU Utilization (%)' and group_id=2 ) prcnt,
queueing,
EXEC DBMS_SQLTUNE.execute_tuning_task(task_name
clust/60 ( AS
select value cpu_count from v$parameter where =>
clust, '4pgqpkv31u4nn_tuning_task');
name='cpu_count' ) parameter
union
other/60 AS other
select
FROMtask_name,
select status from dba_advisor_log where task_name='4pgqpkv31u4nn_tuning_task';
(SELECT 'CPU_ORA_DEMAND' CLASS,
SET SERVEROUTPUT ON AS sample_time,
nvl(round( sum(decode(session_state,'ON
TRUNC(sample_time,'MI') CPU',1,0))/60,2),0) AAS
SET LONGfrom100000;
v$active_session_history
DECODE(session_state,'ON ash
CPU',DECODE(session_type,'BACKGROUND','BCPU','ON CPU'), wait_class) AS wait_class
setFROM
longchunksize
where 1000;
SAMPLE_TIME
v$active_session_history > sysdate - (60/(24*60*60))
SET
) WHEREPAGESIZE 1000
sample_time>sysdate-INTERVAL '1' HOUR
SET
select LINESIZE 200
AND sample_time<=TRUNC(SYSDATE,'MI')) ash
SELECT
PIVOT DBMS_SQLTUNE.report_tuning_task('4pgqpkv31u4nn_tuning_task')
( decode(sign(CPU_OS-CPU_ORA_CONSUMED),
(COUNT(*) FOR wait_class IN ('ON CPU' AS cpu,'BCPU' -1, 0, (CPU_OS AS recommendations
- CPU_ORA_CONSUMED
AS bcpu,'Scheduler' ))FROM
+
AS scheduler,'User dual;
I/O' AS
SETCPU_ORA_CONSUMED
PAGESIZE
uio,'System I/O' AS24 sio, +
decode(sign(CPU_ORA_DEMAND-CPU_ORA_CONSUMED),
'Concurrency' AS concurrency,'Application' AS application,'Commit'-1,AS 0,COMMIT,'Configuration'
(CPU_ORA_DEMAND -AS configuration,
CPU_ORA_CONSUMED ))) CPU_TOTAL, AS network,'Queueing' AS queueing,'Cluster' AS clust,'Other' AS other)) ash,
'Administrative' AS administrative,'Network'
decode(sign(CPU_OS-CPU_ORA_CONSUMED), -1, 0, (CPU_OS - CPU_ORA_CONSUMED )) CPU_OS,
(SELECT
CPU_ORA_CONSUMEDAS
TRUNC(begin_time,'MI') CPU_ORA,
sample_time,
decode(sign(CPU_ORA_DEMAND-CPU_ORA_CONSUMED),
VALUE/100 AS cpu_ora_consumed -1, 0, (CPU_ORA_DEMAND - CPU_ORA_CONSUMED ))
CPU_ORA_WAIT,
FROM v$sysmetric_history
COMMIT,
WHERE GROUP_ID=2
READIO,
AND metric_name='CPU Usage Per Sec') sysmetric_history
WHERE WAITash.sample_time (+)=sysmetric_history.sample_time
from
ORDER ( BY sample_time;
select
sum(decode(CLASS,'CPU_ORA_CONSUMED',AAS,0)) 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_interval','freq=daily;byday=MON,TUE,WED,THU,F
RI;byhour=05;byminute=0; bysecond=0');
EXECUTE DBMS_SCHEDULER.SET_ATTRIBUTE('WEEKEND_WINDOW','repeat_interval','
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.


WHERE bm.dbid = ss.dbid
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;
, TO_CHAR(sn.end_interval_time,'DD-MON-YYYY HH24:MI') dt
, st.sql_id
, st.instance_number
, 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_delta),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;
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;
ready mentioned in your article.
set serveroutput onIn my opinion, plan statistics have tremendous value and potentially a good
overhead in “statistics_level=all” mode. But it is OK to do that at session level, even in production system. So,
cs_level=all and recreate run environment. Here is the full sequence of actions:
Declare
v_BaselineSize number(20);
runway SQL from v$session; number(20);
v_CurrentSize
ng SQL_ID andv_TotalGrowth
CHILD_NUMBER; number(20);
be problems capturing
v_Spacebind variables,
number(20);for brevity I will skip details. If no bind variables, skip this step;
ssion set statistics_level=all”;
cursor usageHist is
values and, even more selectimportantly,
a.snap_id,same datatypes as in Capture step;
eak) after some time,SNAP_TIME,
even 10-15 secs should be sufficient;
L_ID should be samesum(TOTAL_SPACE_ALLOCATED_DELTA)
as in step 1. Very important: it should have same over (Plan_hash_value, otherwise
order by a.SNAP_ID) revise
ProgSum
steps; from
set linesize
n partial execution. can750
It(select pages
beSNAP_ID, 9999article dedicated to the interpreting plan statistics. Once becoming
a separate
No guess work,set numwidth 20
it’s all sum(SPACE_ALLOCATED_DELTA)
in numbers. 10-15 seconds of execution should be enough for the query to get to the
TOTAL_SPACE_ALLOCATED_DELTA
COLbe
g time, they can NAME
easily FOR A30
identified.
from DBA_HIST_SEG_STAT
col SNAP_IDgroup for 9999999
by SNAP_ID
e I was free from all thathavingroutine, I was able to troubleshoot not only
sum(SPACE_ALLOCATED_TOTAL) <>runaway
0 queries (which are rare anyway)
SELECT
ue in really complicated order cases
by 1or when in doubts. Most often, problems are simple and a quick look at the
) a,
h to spot the distinct DHSS.SNAP_ID,VTS.NAME,
cause. (select distinct SNAP_ID,
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

r 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

PAST
SET LINESIZE 200 PAGESIZE 50000
COL BEGIN_TIME FORMAT A17
COL END_TIME FORMAT A17
COL INST_ID FORMAT 999
COL "Min Response Time (msecs)" FORMAT 999,999,999,999.99
COL "Avg Response Time (msecs)" FORMAT 999,999,999,999.99
COL "Max Response Time (msecs)" FORMAT 999,999,999,999.99

SELECT TO_CHAR (BEGIN_TIME, 'DD-MON-YYYY HH24:MI') BEGIN_TIME,


TO_CHAR (END_TIME, 'DD-MON-YYYY HH24:MI') END_TIME,
INSTANCE_NUMBER INST_ID,
ROUND (MINVAL * 10, 2) "Min Response Time (msecs)",
ROUND (AVERAGE * 10, 2) "Avg Response Time (msecs)",
ROUND (MAXVAL * 10, 2) "Max Response Time (msecs)"
FROM DBA_HIST_SYSMETRIC_SUMMARY
WHERE 1 = 1 AND METRIC_NAME = 'SQL Service Response Time'
ORDER BY BEGIN_TIME DESC, INSTANCE_NUMBER;

= 'WAITING' AND wait_class!= 'Idle' ;

ROUP 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
=> true, estimate_percent => dbms_stats.auto_sample_size,method_opt=>'FOR ALL COLUMNS SIZE AUTO', granularity => 'ALL', degre
=> dbms_stats.auto_sample_size, degree => 8);
o_sample_size ,method_opt=>'FOR ALL COLUMNS SIZE AUTO', degree => 8);
_SIZE, METHOD_OPT => 'FOR ALL COLUMNS SIZE AUTO', DEGREE => 8, CASCADE => TRUE);

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;
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
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
SIZE AUTO', granularity => 'ALL', degree => 8);

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

thout-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 size

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
Whole
COLUMNdb cdb & pdb
owner FORMAT A30
COLUMN table_name FORMAT A30
COLUMN column_name FORMAT A30
COLUMN segment_name FORMAT A30
COLUMN tablespace_name FORMAT A30
COLUMN size_mb FORMAT 99999999.00
select
SELECT d.name,round(sum(c.bytes)/1024/1024/1024)
* SIZE_GB from
cdb_data_files
FROM (SELECT c, v$database
l.owner, d group by d.name;
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 "Tablespace|Name"
AND l.TABLE_NAME='&TABLE_NAME'
col Allocated_size
ORDER BY 6heading
DESC) "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" FROM dba_segments
col Available_size WHERE segment_type
heading "Available|Size(GB)" form=99999999.99
'TABLE
PARTITION'
col and segment_name= '&TABLE_NAME' and
Pct_used heading "%Used (vs)|(Allocated)" form 99999999.99
SELECT
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') usedgroup 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';
hwmts as (
-- join ts# with tablespace_name
select name tablespace_name,relative_fno,hwm_blocks
from hwm join v$tablespace using(ts#)
),
hwmdf as (
-- join 'ALTER
select with datafiles, put 5M minimum
TABLESPACE for datafiles with
' || tablespace_name no extents
|| ' AUTOEXTEND
select file_name,nvl(hwm_blocks*(bytes/blocks),5*1024*1024)
ON MAXSIZE ' || to_char(round((bytes *
hwm_bytes,bytes,autoextensible,maxbytes
SELECT A.tablespace_name tablespace,
1.25)/(1024*1024*1024),0),9999) || 'G;' D.mb_total,
COL from hwmts
SUM right
TABLESPACE_SIZE
from dba_data_files join
(A.used_blocks dba_data_files
*
FOR D.block_size)
999,999,999,999/ 1024 / 1024 mb_used,
using(tablespace_name,relative_fno)
COL D.mb_total
ALLOCATED_SPACE
where bytes > maxbytes - SUM (A.used_blocks
FOR * D.block_size)
999,999,999,999 / 1024 / 1024
)
mb_free
COL FREE_SPACE
order by tablespace_name; FOR 999,999,999,999
select
FROM gv$sort_segment A,
case (when
select autoextensible='YES' and maxbytes>=bytes
TABLESPACE_NAME,TABLESPACE_SIZE/1024/1024/1024
then -- we generate
SELECT
TABLESPACE_SIZE_GB, B.name,resize statements only
C.block_size, SUMif(C.bytes)
autoextensible
/ 1024can grow
/ 1024
back
mb_total to current size
ALLOCATED_SPACE/1024/1024/1024 ALLOCATED_SPACE_GB,
'/* reclaim
FROM'||to_char(ceil((bytes-hwm_bytes)/1024/1024),999999)
FREE_SPACE/1024/1024/1024 v$tablespace B, v$tempfile
FREE_SPACE C FROM
||'M from
WHERE
dba_temp_free_space;'||to_char(ceil(bytes/1024/1024),999999)||'M
B.ts#= C.ts# */ '
||'alter database
GROUP 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 fromfile_name format a50 word_wrapped
'||to_char(ceil(bytes/1024/1024),999999)
column smallest
value
||'M after format
new_val
setting 999,990 heading
blksize
autoextensible maxsize"Smallest|Size|Poss."
higher than current size for
column
select
file currsize format 999,990
' value from v$parameter where name heading "Current|Size"
= '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 from v$parameter where name = 'db_block_size'
value
/order by bytes-hwm_bytes desc
column num_instances heading "Num" format 999
/column type heading "Object Type" format a12
select file_name,
column source_size heading "Source" format 99,999,999
ceil( (nvl(hwm,1)*&&blksize)/1024/1024 ) smallest,
column parsed_size heading "Parsed" format 99,999,999
ceil( blocks*&&blksize/1024/1024) currsize,
column code_size heading "Code" format 99,999,999
ceil( blocks*&&blksize/1024/1024) -
column error_size heading "Errors" format 999,999
ceil( (nvl(hwm,1)*&&blksize)/1024/1024 ) savings
column size_required heading "Total" format 999,999,999
from dba_data_files a,
compute sum of size_required on report
( select file_id, max(block_id+blocks-1) hwm
from dba_extents
select count(name) num_instances
group by file_id ) b
,type
where a.file_id = b.file_id(+)
,sum(source_size) source_size
/
,sum(parsed_size) parsed_size
,sum(code_size) code_size
,sum(error_size) error_size
,sum(source_size)
+sum(parsed_size)
+sum(code_size)
+sum(error_size) size_required
from dba_object_size
group by type
order by 2
/

select * from (select owner,segment_name, bytes/1024/1024 meg


from dba_segments
where segment_type = 'TABLE' and owner not in
('SYS','SYSTEM','DBSNMP','APEX_040200','MDSYS')
order by bytes/1024/1024 desc) where rownum <= 10;
where si.owner = i.owner
round(si.bytes/1024/1024,1) index_mb, round(st.bytes/1024/1024,1)
and si.segment_name = i.index_name
table_mb,
and si.tablespace_name=i.tablespace_name
round(si.bytes/st.bytes*100,1)
and si.segment_type = 'INDEX'pct_larger
from dba_segments
and i.table_owner si, dba_indexes i, dba_tables t, dba_segments st
= t.owner
where si.owner = i.owner
and i.table_name = t.table_name
and si.segment_name
t.owner = st.owner= i.index_name
and si.tablespace_name=i.tablespace_name
t.table_name = st.segment_name
and si.segment_type
st.segment_type = 'INDEX'
'TABLE'
and i.table_owner = t.owner
si.bytes > st.bytes
and i.table_name = t.table_name
si.bytes> 100*1024*1024 /* Larger than 100 MB */
and
ordert.table_name='&TABLE_NAME'
by pct_larger desc;
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
WHERE extents > max_extents - 10;
col table_name for a30
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))*100 "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 = i.owner
AND con_id,name,SUM(SIZE_MB)
s.owner
select from
SELECT
ANDLINESIZE l.table_name, IN
s.segment_type l.owner, s.bytes
('INDEX', 'INDEX PARTITION', 'INDEX
(SET 200
FROM dba_lobs
SUBPARTITION') l, dba_segments s
CDB
select
COLUMN WITH list of
c.con_id,nvl(p.name,
owner FORMAT A30PDBs 'CDB') name, sum(bytes)/1024/1024 SIZE_MB from
WHERE
UNION s.segment_name
ALL = l.segment_name
cdb_data_files
COLUMN c,
table_name v$pdbs p where
FORMAT A30 c.con_id=p.con_id(+) GROUP BY
AND
SELECT s.owner = l.owner
l.table_name, l.owner, s.bytes
c.con_id,name
COLUMN column_nameIN FORMAT A30
AND
FROM s.segment_type
dba_lobs l, ('LOBSEGMENT',
dba_segments s A30 'LOB PARTITION')
UNION
column
COLUMN dummy noprint
segment_name FORMAT
UNION
WHERE ALL
s.segment_name ='CDB')
l.segment_name
select
column
COLUMN c.con_id,nvl(p.name,
pct_used
tablespace_nameformatl.owner,
999.9FORMAT name
heading
A30, sum(bytes)/1024/1024
"%|Used" SIZE_MB from
SELECT
AND l.table_name,
s.owner = l.owner s.bytes
cdb_temp_files
column
COLUMN name c,
format
size_mbl, FORMATv$pdbs a19 p where c.con_id=p.con_id(+)
heading
99999999.00 "Tablespace GROUP
Name" BY
FROM dba_lobs
AND s.segment_type dba_segments s
c.con_id,name
column
WHERE Kbytes format IN
s.segment_name
('LOBSEGMENT',
999,999,999
= l.index_name heading'LOB PARTITION')
"KBytes"
UNION
)group
column
SELECT byALLcon_id,name
used
* format 999,999,999 heading "Used"
AND
SELECT s.owner = l.ownerl.owner, s.bytes
l.table_name,
order
column
FROM by (SELECT
con_id;
free format 999,999,999
l.owner, heading "Free"
AND
FROMLOB s.segment_type
dba_lobs l,format = 'LOBINDEX')
dba_segments s heading "Largest"
column
WITH
WHERE largest
ownerSegments
l.table_name, 999,999,999
in UPPER('&owner')
WHEREmax_size
column s.segment_name
l.column_name, = l.index_name
format 999,999,999 heading "MaxPoss|Kbytes"
and Table_name='&TABLE_NAME'
AND s.owner = l.owner
column
GROUP pct_max_used
l.segment_name,
BY table_name,= owner format 999.9 heading "%|Max|Used"
AND s.segment_type
break on report
l.tablespace_name, 'LOBINDEX')
HAVING
WHERE SUM(bytes)/1024/1024
owner > 10 /* Ignore really small tables */
compute
ORDER sum
BY ofinkbytes
UPPER('&owner')
on report
ROUND(s.bytes/1024/1024,2)
2; size_mb
--and
compute Table_name='&TABLE_NAME'
FROM sumdba_lobs
of free onl report
GROUP BY
compute sum
JOIN table_name,
ofdba_segments
used on report owners ON s.owner = l.owner AND s.segment_name =
HAVING SUM(bytes)/1024/1024
l.segment_name > 10 /* Ignore really small tables */
ORDER
select
AND BY
(select 2;decode(extent_management,'LOCAL','*',' ') ||
l.owner='&OWNER'
-- ANDdecode(segment_space_management,'AUTO','a
l.TABLE_NAME='&TABLE_NAME' ','m ')
from
ORDER dba_tablespaces
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
FROMtablespace_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*1
6/1024)),2))*100 "percentage"
from all_tables WHERE table_name='&TABLE_NAME';
select
a.data_size+b.temp_size+c.redo_size+d.controlfile_size
only CDB in MB" from ( select sum(bytes)/1024/1024
"total_size
data_size
from dba_data_files) a,( select
nvl(sum(bytes),0)/1024/1024 temp_size from
dba_temp_files ) b,( select sum(bytes)/1024/1024
redo_size from sys.v_$log ) c,
( select
sum(BLOCK_SIZE*FILE_SIZE_BLKS)/1024/1024
controlfile_size from v$controlfile) d;

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

select a.data_size+b.temp_size "total_size in MB"


from ( select sum(bytes)/1024/1024 data_size
from dba_data_files) a,
( select nvl(sum(bytes),0)/1024/1024 temp_size
from dba_temp_files ) b;

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
FROM*dba_free_space
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
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;
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
echo -e "\033[0;31mNodes:
col DB_UNIQUE_NAME \033[0;0m"`srvctl
format a10 config database -d $line | grep
"Configured
set head on; nodes" | cut -f2 -d:`;
echo -e "\033[0;31mPDB:
set lines 5000; \033[0;0m"`srvctl config service -d $line -s
$CHANGE_ME
set tab off; | grep -i "Pluggable database name" | cut -f2 -d:`;
done ; unset CHANGE_ME
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 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
from start service -d RAC12C -s TAFSRV
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
<---- input the format
col total_size service999,999,999,999,999
name
col zmax_pdb_storage format
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$SESSION_LONGOPS
v$session s,
WHERE OPNAME LIKE 'RMAN%'
(select sid,
AND
serial,OPNAME NOT LIKE '%aggregate%'
AND sum
100* TOTALWORK != 0
(long_waits) / sum (io_count) as "LONG_WAIT_PCT",
AND (effective_bytes_per_second)/1024/1024
sum SOFAR != TOTALWORK; as "MB_PER_S"
from v$backup_async_io
group by sid, serial) aio
where aio.sid = s.sid
and aio.serial = s.serial#
and l.opname like 'RMAN%'
and l.opname not like '%aggregate%'
and l.totalwork != 0
and l.sofar <> l.totalwork
select to_char(START_TIME,'MM-DD-YYYY
and s.sid = l.sid HH24:MI:SS') as
START_TIME,to_char(END_TIME,'MM-DD-YYYY
and s.serial# = l.serial# HH24:MI:SS') as
END_TIME,ELAPSED_SECONDS/60/60,INPUT_BYTES/1024/1024/1024/1024
order by 1; as
INPUT_TB,OUTPUT_BYTES/1024/1024/1024/1024 as
OUTPUT_TB,INPUT_BYTES_PER_SEC/1024/1024 as
INPUT_SEC_MB,OUTPUT_BYTES_PER_SEC/1024/1024 as OUTPUT_SEC_MB,status
from
V$RMAN_BACKUP_job_details where INPUT_TYPE like 'DB%INCR%';

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


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

select * from v$rman_configuration;

COL STATUS FORMAT a25


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

SELECT INPUT_TYPE,
STATUS,
TO_CHAR(START_TIME,'mm/dd/yy hh24:mi') start_time,
TO_CHAR(END_TIME,'mm/dd/yy hh24:mi') end_time,
INPUT_BYTES_DISPLAY in_size,
round(ELAPSED_SECONDS/3600,3) HRS
FROM V$RMAN_BACKUP_JOB_DETAILS
where sysdate - start_time <= 7;
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 d.session_recid, d.session_stamp,
x.session_recid = j.session_recid
bp.tag and x.session_stamp = j.session_stamp tag
left outer joinsum(case
, DECODE(backup_type when d.controlfile_included
(select o.session_recid, = 'YES'
o.session_stamp, 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
order 0by
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
WHERE output
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 bySPID FORMAT 9999
trunc(bp.completion_time), backup_type)
order by 1, 2;
SELECT s.SID, p.SPID, s.CLIENT_INFO
FROM V$PROCESS p, V$SESSION s
WHERE p.ADDR = s.PADDR
AND CLIENT_INFO LIKE 'rman%'
/

SELECT * FROM V$RECOVER_FILE;

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


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

blockrecover datafile 8 block 13;

SELECT owner, segment_name, segment_type


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

RMAN> validate tablespace corrupt;


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

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

select * from schemaname.rcver;

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

select DBID, NAME ,STATUS from RC_DATABASE_INCARNATION where name like


'%IKB%'

COLUMN EVENT FORMAT a10


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

SELECT p.SPID, EVENT, SECONDS_IN_WAIT AS SEC_WAIT,


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

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

SELECT 'SQL "ALTER DATABASE RENAME FILE '''''|| MEMBER ||'''''' ||chr(10)||'to ''''' ||
member || '''''" ;' FROM
V$LOGFILE;
from v105.rc_database a,v105.bs b
where a.db_key=b.db_key
and b.bck_type is not null having max(start_time) < sysdate - 7
group by a.name,dbid,b.bck_type
) group by db,dbid
union
select 'V112 - ' ||DB NAME,dbid,min(backuptype_db) DBBKP,min(backuptype_arch)
ARCBKP
from (
select a.name DB,dbid,
decode(b.bck_type,'D',max(b.completion_time),'I',
max(b.completion_time)) BACKUPTYPE_db,
decode(b.bck_type,'L',
max(b.completion_time)) BACKUPTYPE_arch
from v112.rc_database a,v112.bs b
where a.db_key=b.db_key
and b.bck_type is not null having max(start_time) < sysdate - 7
group by a.name,dbid,b.bck_type
) group by db,dbid
union
select 'isp102 - ' ||DB NAME,dbid,min(backuptype_db) DBBKP,min(backuptype_arch)
ARCBKP
from (
select a.name DB,dbid,
decode(b.bck_type,'D',max(b.completion_time),'I',
max(b.completion_time)) BACKUPTYPE_db,
decode(b.bck_type,'L',
max(b.completion_time)) BACKUPTYPE_arch
from isp102.rc_database a,isp102.bs b
where a.db_key=b.db_key and a.name not in
('RTL0892','RTL0890','RTL0888','RTL0007','RTL0881')
and b.bck_type is not null having max(start_time) < sysdate - 7
group by a.name,dbid,b.bck_type
) group by db,dbid
;
mct := ct;
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 = site_dfatt.site_key
BACKUPTYPE_db,
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 fname, dbi.db_name,
tag
DISTINCT
v104.ts,
FROM bp.tag
v112.dbinc dbi,
bdf.completion_time,
v104.df,
FROM v92.dbinc
v112.bdf,
df.file#, dbi,
v104.bp,
v92.bdf
v112.ts, bdf,
SELECT fname,
DISTINCT
v104.node, dbi.db_name,
v92.dfatt
v112.df,
bp.tagdf,
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,
ts.ts# = df.ts#
AND
WHERE bdf.file#
v102.bp 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
AND dbi.dbinc_key
NULL)AND bdf.dbinc_key
ts.ts# = df.ts# = df.dbinc_key
v121.ts,
AND bdf.dbinc_key = df.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.dbinc_key = dbi.db_key
= df.dbinc_key
AND (bdf.incr_level
v121.bp,
bdf.file# = df.file# 0 OR bdf.incr_level IS
AND bdf.dbinc_key
NULL)v121.node, = df.dbinc_key
AND (bdf.incr_level
node.db_key ==dbi.db_key
0 OR bdf.incr_level IS
NULL)AND bdf.bs_key
v121.site_dfatt
AND bdf.file#
= bp.bs_key;
= df.file#= ts.dbinc_key
WHERE
AND dbi.dbinc_key
node.site_key = site_dfatt.site_key
AND (bdf.incr_level
AND 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:
se 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.incr_level = 0 OR bdf.incr_level IS NULL)
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:-
col message for a100
begin
col job_mode for a30
dbms_metadata.set_transform_param (dbms_metadata.session_transform, 'SQLTERMINATOR', true);
dbms_metadata.set_transform_param (dbms_metadata.session_transform, 'PRETTY', true);
SELECT x.job_name,
end;
/ b.state,
-- b.degree,
--
variable x.owner_name,
v_username VARCHAR2(30);
-- z.sql_text,
p.MESSAGE, := upper('&1');
exec:v_username
p.totalwork,
select p.sofar,
dbms_metadata.get_ddl('USER', u.username) AS ddl
fromROUND dba_users ( (p.sofar
u / p.totalwork) * 100, 2) done,
p.time_remaining
where u.username = :v_username
FROM
union all dba_datapump_jobs b
select LEFT JOIN dba_datapump_sessions x ON (x.job_name = b.job_name)
dbms_metadata.get_granted_ddl('TABLESPACE_QUOTA', tq.username) AS ddl
fromLEFT JOIN v$session
dba_ts_quotas tq y ON (y.saddr = x.saddr)
where LEFT JOIN v$sql= z:v_username
tq.username ON (y.sql_id = z.sql_id)
LEFT
and rownum = 1 JOIN v$session_longops p ON (p.sql_id = y.sql_id)
WHERE
union all y.module = 'Data Pump Worker' AND p.time_remaining > 0;
select dbms_metadata.get_granted_ddl('ROLE_GRANT', rp.grantee) AS ddl
from dba_role_privs
set arraysize 1000 rp
where rp.grantee = :v_username
copy from username/passwd@source_connect_string to username/passwd@target_connect_string insert table_target
and rownum
using select = 1 table_source;
* from
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
COPY FROM sp.grantee = :v_username
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
expdpdba_tab_privs
from 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 dba_role_privs rp
from all_constraints a, all_constraints b
wherewhere rp.grantee = :v_username
a.constraint_type = 'R'
and andrp.default_role
a.r_constraint_name = 'YES'= b.constraint_name
and andrownum
a.r_owner = 1 = b.owner
unionandallb.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 system/*****
union 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_EXP
ORT_SC
HEMA_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 the
to_char(b.start_time,'YYYY/MM/DD progress
HH24:MI:SS') start_time of
FROM v$session_longops b, Currently
v$session a running
WHERE a.sid = b.sid ORDER BY 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

Show my current session Roles


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

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

set long 2000


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

##For 11g
set lines 2000
select 'alter user ' || NAME ||' identified by values ''' || password || ''';' from user$;
##For 12c and later
set longsize 9999
set lines 2000
set longchunksize 9999
set long 9999
select 'alter user ' || NAME ||' identified by values ''' || SPARE4 || ''';' from sys.user$ where name='&name';

declare
userNm varchar2(100);
userpswd varchar2(100);
begin
userNm := upper('&TypeUserNameHere');
select password into userpswd from sys.user$ where name = userNm;
execute immediate ('ALTER PROFILE "FUNCTIONAL_USER" LIMIT
PASSWORD_VERIFY_FUNCTION null
PASSWORD_LIFE_TIME UNLIMITED
PASSWORD_REUSE_TIME UNLIMITED
PASSWORD_REUSE_MAX UNLIMITED');
execute immediate ('alter user '||userNm||' identified by oct152014oct');
execute immediate ('alter user '||userNm||' identified by values '''||userpswd||'''');
execute immediate ('ALTER PROFILE "FUNCTIONAL_USER" LIMIT
PASSWORD_VERIFY_FUNCTION PASSWDCOMPLEXVERIFICATION');

end;
/

SQL> ALTER PROFILE FUNCTIONAL_USER LIMIT PASSWORD_VERIFY_FUNCTION NULL;


Profile altered.
SQL> alter user trial identified by test;
User altered.
SQL> conn trial/test;
ALTER PROFILE "FUNCTIONAL_USER" LIMIT PASSWORD_VERIFY_FUNCTION PASSWDCOMPLEXVERIFICATION

select ' alter user '||username||' profile '||PROFILE||';' from dba_users;


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

spool off

set feedback on

DB link : dev to prod

CREATE DATABASE LINK "COMPARE" CONNECT TO DBSNMP IDENTIFIED BY mypwd USING 'destonation-db-name'
select * from DBA_TAB_PRIVS@compare T1 where not exists (select 1 from dba_tab_privs T2 where t1.TABLE_NAME=
t1.PRIVILEGE=t2.PRIVILEGE and t1.GRANTEE=t2.GRANTEE ) and t1.grantee='&ROLE_NAME';

select GRANTEE as users from dba_role_privs where GRANTED_ROLE=UPPER('&GRANTED_ROLE');

select 'GRANT '||granted_role||' to '||grantee||


DECODE(ADMIN_OPTION, 'Y', ' WITH ADMIN OPTION;', ';')
from dba_role_privs
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%');
FROM dba_role_privs
START WITH granted_role IN (SELECT grantee
FROM dba_tab_privs
WHERE PRIVILEGE = 'REFERENCES')
select
CONNECT username from dba_users
BY PRIOR where username not in (
grantee = granted_role
'ANONYMOUS',
UNION
'AURORA',
SELECT grantee || ' Through role ' || granted_role ge, 'EXECUTE' priv
'$JIS',
FROM dba_role_privs
'$UTILITY',
START WITH granted_role IN (SELECT grantee
'$AURORA', FROM dba_tab_privs
'$ORB', WHERE PRIVILEGE = 'EXECUTE')
'$UNAUTHENTICATED',
CONNECT BY PRIOR grantee = granted_role
'CTXSYS',
UNION
'DBSNMP',
SELECT grantee || ' Direct' ge, PRIVILEGE priv
'DMSYS',
FROM SYS.dba_tab_privs
select
'DSSYS',
WHERE table_name = UPPER ('&TABLE_NAME')
lpad(' ', BY
'EXFSYS',
ORDER 2*level)
1, 2; || c "Privilege, Roles and Users"
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 see which table privileges are granted to you by other users
where
'PERFSTAT',
SELECTname*like
'PUBLIC', FROM USER_TAB_PRIVS_RECD;
upper('%&enter_privliege%')
To see which column
/* THE ROLES TO ROLES
'REPADMIN', level privileges
RELATIONS are granted
*/ by you to other users.
SELECT
union
'SYS', * FROM USER_COL_PRIVS_MADE
Toselect
see which column level privileges are granted to you by other users
'SYSMAN',
SELECT * FROM p,
granted_role
'SYSTEM', USER_COL_PRIVS_RECD;
To see which
grantee
'TRACESVR', privileges
c are granted to roles
SELECT
from
'WKPROXY', * FROM USER_ROLE_PRIVS;
dba_role_privs
'WKSYS',
/* THE ROLES TO PRIVILEGE RELATIONS */
'WMSYS',
union
'XDB',
Granted
select Roles:
'APEX_PUBLIC_USER' ,
SELECT * FROM
privilege
'APEX_030200', p, DBA_ROLE_PRIVS
WHEREgrantee
'APPQOSSYS', GRANTEE c = 'USER';
Privileges
'BI'from
, Granted Directly To User:
SELECT , *
'DIP'dba_sys_privs
FROM
) DBA_TAB_PRIVS
'FLOWS_XXXXXX' ,
start with GRANTEE
WHERE
'HR', p is null = 'USER';
Privileges
connect
'IX' , by Granted
p = prior to
c; Role Granted to User:
SELECT * ,
'LBACSYS'
FROM DBA_TAB_PRIVS
'MDDATA' ,
WHERE
'MGMT_VIEW' GRANTEE , IN (SELECT granted_role
'OE' , FROM DBA_ROLE_PRIVS
'ORACLE_OCM' WHERE , GRANTEE = 'USER');
Granted System
'ORDDATA' , Privileges:
SELECT
'PM' , *
FROM DBA_SYS_PRIVS
'SCOTT' ,
'SH' , GRANTEE = 'USER';
WHERE
'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 wh


SELECT DBMS_METADATA.GET_DDL('PACKAGE_BODY',db.OBJECT_NAME,'db.owner')|| '/' from dba_objects db whe
object_type='PACKAGE BODY';
SELECT DBMS_METADATA.GET_DDL(db.OBJECT_TYPE,db.OBJECT_NAME,db.OWNER)|| '/' from dba_objects db wh
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;

select * from session_roles;


spool d1riskusercreate.sql
set pagesize 0
set escape on
select 'create user ' || U.username || ' identified ' ||
DECODE(password,
NULL, 'EXTERNALLY',
' by values ' || '''' || password || ''''
)
http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:494205100346718343
|| chr(10) ||
'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 of GET_DDL is
Q.max_bytes) ||
GET_DDL(object_type, name, schema, version, model, transform).
' on ' || default_tablespace ||
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','OR
||L.PASSWORD||' using ''' || L.host || ''''
DPLUGINS','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
select 'grant ' || GRANTED_ROLE || ' to ' || ROLE || ';' from
role_role_privs where role='&ROLE'
union
select 'grant ' || PRIVILEGE || ' to ' || ROLE || ';' from role_sys_privs
where role='&&ROLE'
union
select 'grant ' || PRIVILEGE || ' on ' || OWNER || '.' ||TABLE_NAME
|| ' to ' || GRANTEE || ';' from dba_tab_privs where
GRANTEE='&&ROLE' ;
'&&role')
end ) from dual
UNION ALL
select (case
when ((select count(*)
from dba_sys_privs
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 * from DBA_TAB_PRIVS where grantee like


upper('%&enter_username%');
select * from DBA_ROLE_PRIVS where grantee like
upper('%&enter_username%');
select * from DBA_SYS_PRIVS where grantee like
upper('%&enter_username%');
select * from DBA_COL_PRIVS where grantee like
upper('%&enter_username%');
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
exec:v_username := upper('&1');

select dbms_metadata.get_ddl('USER', u.username) AS ddl


from dba_users u
where u.username = :v_username select
union all dbms_me
select dbms_metadata.get_granted_ddl('TABLESPACE_QUOTA', tadata.get
tq.username) AS ddl _ddl('USE
from dba_ts_quotas tq R',
1_QUESTION_ID:494205100346718343
where tq.username = :v_username 'KPHU000
and rownum = 1 ') || '/'
union all usercreat
select dbms_metadata.get_granted_ddl('ROLE_GRANT', e from
rp.grantee) AS ddl dual;
from dba_role_privs rp SELECT
where rp.grantee = :v_username DBMS_M
and rownum = 1 ETADATA
union all .GET_GR
select dbms_metadata.get_granted_ddl('SYSTEM_GRANT', ANTED_
sp.grantee) AS ddl DDL('ROL
from dba_sys_privs sp E_GRAN
where sp.grantee = :v_username T','KPHU0
and rownum = 1 00') || '/'
union all FROM
select dbms_metadata.get_granted_ddl('OBJECT_GRANT', DUAL;
tp.grantee) AS ddl SELECT
from dba_tab_privs tp DBMS_M
where tp.grantee = :v_username ETADATA
and rownum = 1 .GET_GR
union all ANTED_
select dbms_metadata.get_granted_ddl('DEFAULT_ROLE', DDL('SYS
rp.grantee) AS ddl TEM_GR
from dba_role_privs rp ANT','KP
where rp.grantee = :v_username HU000') ||
and rp.default_role = 'YES' '/' FROM
and rownum = 1 DUAL;
union all SELECT
select to_clob('/* Start profile creation script in case they are DBMS_M
missing') AS ddl ETADATA
from dba_users u .GET_GR
where u.username = :v_username ANTED_
and u.profile <> 'DEFAULT' DDL('OBJ
and rownum = 1 ECT_GR
union all ANT','KP
select dbms_metadata.get_ddl('PROFILE', u.profile) AS ddl HU000') ||
from dba_users u '/' FROM
where u.username = :v_username DUAL;
and u.profile <> 'DEFAULT' select
union all DBMS_M
select to_clob('End profile creation script */') AS ddl ETADATA
from dba_users u .GET_GR
where u.username = :v_username ANTED_
and u.profile <> 'DEFAULT' DDL('TAB
and rownum = 1 LESPACE
/ _QUOTA',
'KPHU000
set linesize 80 pagesize 14 feedback on trimspool on verify on ') '/' 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 o.object_name,
d 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_id O = 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)',
6, o.sql_text,
'Exclusive')
and a.inst_id=b.inst_id lock_type,
order o.address,
decode(REQUEST,
by 1,2;
0, o.hash_value,
set'None',
lines 750 pages 9999
col
All sqlo.user_name,
blocking_status
1, 'Null',executed by aforsid a100
select s.schemaname,
s1.inst_id,s2.inst_id,s1.username
2, 'Row-S (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 l1.id1 = l2.id1
gv$lock.type
t.SQL_TEXT
FROM
fromand l2.id2
v$session= l2.id2
gv$lock join
sn, gv$session on gv$lock.sid=gv$session.sid and
order by s1.inst_id;
gv$lock.inst_id=gv$session.inst_id
v$lock m ,
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 dba_objects
and t.HASH_VALUE do on= lo.OBJECT_ID
sn.SQL_HASH_VALUE = do.OBJECT_ID
WHERE
and ((sn.SID (id1, =id2, gv$lock.type)
m.SID IN (
and m.REQUEST != 0)
orSELECT(sn.SIDid1, id2, type
= m.SID and FROM gv$lock=WHERE
m.REQUEST 0 and LMODErequest>0)
!= 4 and (ID1, ID2)
ORDER BY id1, request;
in
(select s.ID1, s.ID2
from v$lock S
where REQUEST != 0
and s.ID1 = m.ID1
and s.ID2 = m.ID2)))
order by sn.USERNAME, sn.SID, t.PIECE;
select sample_time, session_state, blocking_session,
owner||'.'||object_name||':'||nvl(subobject_name,'-') obj_name,
dbms_ROWID.ROWID_create (
1,
o.data_object_id,
current_file#,
current_block#,
current_row#
) row_id
from dba_hist_active_sess_history s, dba_objects o
where user_id = 92
and sample_time between
to_date('29-SEP-12 04.55.02 PM','dd-MON-yy hh:mi:ss PM')
and
to_date('29-SEP-12 05.05.02 PM','dd-MON-yy hh:mi:ss PM')
and event = 'enq: TX - row lock contention'
and o.data_object_id = s.current_obj#
order by 1,2;

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


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

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

Select /*+ ORDERED */


substr(s.ksusemnm,1,10)||'-'|| substr(s.ksusepid,1,10) "ORIGIN",
substr(g.K2GTITID_ORA,1,35) "GTXID",
substr(s.indx,1,4)||'.'|| substr(s.ksuseser,1,5) "LSESSION" ,
s2.username,
substr(
decode(bitand(ksuseidl,11),
1,'ACTIVE',
0, decode( bitand(ksuseflg,4096) , 0,'INACTIVE','CACHED'),
2,'SNIPED',
3,'SNIPED',
'KILLED'
),1,1
) "S",
substr(w.event,1,10) "WAITING"
from x$k2gte g, x$ktcxb t, x$ksuse s, v$session_wait w, v$session s2
where g.K2GTDXCB =t.ktcxbxba
and g.K2GTDSES=t.ktcxbses
and s.addr=g.K2GTDSES
and w.sid=s.indx
and s2.sid = w.sid;
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
FROM dba_objects Xaction',
a, join dba_objects do on lo.OBJECT_ID =
'CF', 'Control File',
gv$locked_object b do.OBJECT_ID
'IS', 'Instance
WHERE State',= b.object_id
a.object_id WHERE (id1, id2, gv$lock.type) IN (
'FS', 'File
ORDER BY 1, 2, 3, 4 Set', 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 lines
'RW', 750Wait',
'Row pages 9999
col blocking_status
'SQ', 'Sequence Number', for a100
SELECT
'TE', 'Extend s1.inst_id,s2.inst_id,
Table', 'Instance '||s1.INST_ID||'
'||'TT',
s1.username
'Temp Table', type) lock_type,|| ' ( SID=' || s1.sid ||
|| '@' || s1.machine
','|| s1.serial#||'
decode(LMODE, '||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
( 1,
SID=' 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 gv$sqltext
blocking_sessions
3, 'Row-X (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
decode(REQUEST, txt.piece);
order by
s1.inst_id=l1.inst_ids.sid, AND l1.sidand lw.request
|| ' is blocking >
' ||0l2.sid blocking_sessions
0,s2.sid=l2.sid
'None', AND FROMorder by s.sid, txt.piece);
s2.inst_id=l2.inst_id
1, 'Null', AND v$lock l1, v$lock l2
2,l1.BLOCK=1
'Row-S (SS)', AND WHERE
l2.request
3, 'Row-X (SX)', > 0 AND l1.block = 1 AND
l1.id1
4, 'Share', = l2.id1 AND l2.request > 0 AND
l2.id2
5, 'S/Row-X = l2.id2 ;
(SSX)', l1.id1 = l2.id1 AND
6, 'Exclusive', request) lock_requested, l1.id2 = l2.id2;
decode(BLOCK,
0, 'Not Blocking',
1, 'Blocking',
2, 'Global', block) status,
OWNER,
OBJECT_NAME
from v$locked_object lo,
dba_objects do,
v$lock l
where lo.OBJECT_ID = do.OBJECT_ID
AND l.SID = lo.SESSION_ID
and block=1;
col sql_id format a15
col inst_id format '9'
col sql_text format a50
col module format a10
col blocker_ses format '999999'
col blocker_ser format '999999'
SELECT distinct
a.sql_id ,
a.inst_id,
a.blocking_session blocker_ses,
a.blocking_session_serial# blocker_ser,
a.user_id,
s.sql_text,
a.module
FROM GV$ACTIVE_SESSION_HISTORY a,
gv$sql s
where a.sql_id=s.sql_id
and blocking_session is not null
and a.user_id <> 0 -- exclude SYS user
and a.sample_time > sysdate - 1
/

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


ics where stattype_locked is not null and owner not in ('SYS','SYSTEM');
select
INST_ID,s
id,BLOCK
ING_SES
SION,BL
OCKING_
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.seconds
_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-reg

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


SQL> oradebug -g all dump systemstate 266

SQL> oradebug setorapname diag

SQL> oradebug tracefile_name

Otherwise
tkprof if it is a single instance
ora10g_ora_5868.trc database,
tracea.prf run:
sort=fchcpu,prscpu,execpu

$ ps -ef| egrep '4711|4713'


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

SQL> connect / as sysdba

SQL> oradebug setorapname diag

SQL> oradebug dump hanganalyze 3

SQL> oradebug dump systemstate 266

SQL> oradebug tracefile_name

exec sys.dbms_system.set_ev([SID], [SERIAL], 10046, 12, '');


exec dbms_system.set_ev(si=>123, se=>1234, ev=>10046, le=>8, nm=>' ');

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


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

Find SID of that session


Find its OS pid from the following (This does not work for Windows)
select p.PID,p.SPID,s.SID from v$process p,v$session s where s.paddr = p.addr and s.sid = &SESSION_ID;
oradebug setospid spid??? (spid from above query)
oradebug unlimit
oradebug event 10046 trace name context forever,level 12;
execute DBMS_SQLDIAG.DUMP_TRACE(p_sql_id=>'&sid',
p_child_number=>0,
p_component=>'Optimizer',
p_file_id=>'TRACE_10053');
using oradebug to set trace through SQL*Plus
sqlplus -prelim / as sysdba
oradebug is a debugging utility that is essentially undocumented and is intended for use by Oracle support analysts for various
SQL*Plus:
of which is Release
that it can10.2.0.2.0
be used to - Production on Mon Dec
set trace. oradebug 11 17:28:14
is available from2006
svrmgrl before Oracle 9i and from SQL*Plus after. The fi
using this tool is to find the OS PID or the Oracle PID of the process you want to analyse. You can do this as follows:
SQL> oradebug setmypid
Statement
SQL> connect processed.
system/manager@sans as sysdba
SQL> oradebug unlimit
Connected.
Statement
SQL> col sid processed.
for 999999
SQL>
SQL> col serial#dump
oradebug systemstate 266
for 999999
SQL> col spid for a8
Metalink Note : 452358.1
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
rman v$session
rcvcat s,v$process ptarget user/passwd@target debug trace trace_file_name
rman/rman@catalog
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 no of duplicate rows in a table

Delete the duplicate rows in a table

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;'
select owner, object_type, substr(object_name,1,30) object_name, status
from dba_objects
from dba_objects
where status<>'VALID' where status='INVALID' order by object_type;
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_

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
ANDlines 750 pages 999
OWNER <> 'PUBLIC' )
col
ORDER owner BY for1a30
;
SELECT
col table_name owner,forconstraint_name,
a50 constraint_type, table_name, r_owner, r_constraint_name
colFROM all_constraints
column_name for a50
colWHERE
data_type owner='&OWNER'
for a30
AND constraint_name='&CONSTRAINT_NAME';
SELECT OWNER, TABLE_NAME, COLUMN_NAME, DATA_TYPE
FROM dba_tab_columns
WHERE DATA_TYPE IN ('CLOB', 'BLOB' , 'LOB', 'BFILE','NCLOB') and owner not in
('SYS','SYSTEM','CTXSYS','WMSYS','XDB','OUTLN') order by 1,2;
set serveroutput
SELECT COUNT(*) on FROM schema.table
DECLARE
WHERE rowid not in
l_sql CLOB
(SELECT :=
MIN(rowid) FROM schema.table GROUP BY PZINSKEY);
'CREATE PROCEDURE <OWNER>.drop_db_links_prc
IS
DELETE FROM schema.table
BEGINrowid not in
WHERE
FOR i MIN(rowid)
(SELECT IN (SELECTFROM * FROM user_db_links)
schema.table GROUP BY PZINSKEY);
LOOP
commit;
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
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;
/
procedure add(l in varchar2,i number default 0) is begin s:=s||chr(10)||rpad(' ',i)||l; end;
begin
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 != table_name,
select 100 then p_sam:='sample 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)
ind.index_name, ind.index_type, ind.num_rows num_rows',1);
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
group by leaf_blocks
table_name,group by '||k_lst,1);
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
where owner='&OWNER' and table_name='&TABLE_NAME'
from analyzedb.table_modifications t, and
(round((blocks*8),2)
all_tables a > round((num_rows*avg_row_len/1024),2))
order
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);
NT_NAME ||';' fromend if;
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;
/
t-owner-constraint-violated-child-record-found/
select
owner,table_name,blocks,num_rows,avg_row_len,roun
d(((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 from v$transaction t,
NVL(s.username, 'None') orauser,
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 s.sql_id = sq.sql_id
from
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
selectby 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
from dba_tablespaces
prompt << by this query:cselect
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'
/
and rs.usn = rn.usn
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 max(maxquerylen),max(tuned_undoretention)
, tr.status 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*102
4) 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-O
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

alter system set


"_HIGHTHRESHOLD_UNDORETENTION"=900
SCOPE=spfile;
OR
alter system set
"_FIRST_SPARE_PARAMER"=900 SCOPE=spfile;

and restart the instance.

Set "_undo_autotune" = false;


_smu_debug_mode=33554432
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

https://practicaloracle.wordpress.com/2012/11/08/auto-tuned-undo-retention/
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
hh24:mi:ss') sql_exec_start,c.rows_processed,a.status, select
-- c.sql_text ROUND(S
substr(c.sql_text,1,50) sql_text UM(temps
FROM v$session a, v$tempseg_usage b, v$sqlarea c, eg_size)/1
(select block_size from dba_tablespaces where 048576)
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_a
AND c.hash_value = a.sql_hash_value ctive
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
)select
"21", thread#, sequence#, name,
to_char(sum(decode(to_char(first_time,'HH24'),'22',1,0)),'99'
round(blocks*block_size/1024/1024) MBytes
)from
"22",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 by
group * 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

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

GG Monitoring Script

Query to find lag for integrated extract

Query to find lag for integrated replicat

configuring parallism in extract

Tuning Tips

Integrated capture parameters

About Manager
About Extract

About Replicat

About Long Running Transactions


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);
h 29

GGSCI Command History

2: start mgr
3: start
VIEW er *
GGSEVT
4: status all
...
ggsci > sh date
29: h 29
30: <Process_name>,
Send h 29 Report
View <process_name>, report
GGSCI (oelr5u7) 31> !4
status
h all
h 10
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
cat mon.sh RUNNING RBATCH 00:00:00 00:00:04
REPLICAT RUNNING RTEST 00:00:00 00:00:05
REPLICAT RUNNING
#!/bin/bash RTESTA 00:00:00 00:00:01
REPLICAT
get_info( ) RUNNING RTESTB 00:00:00 00:00:00
ggsci << eof
GGSCI
info all (oelr5u7) 32>
exit
eof
}

while true
do
get info > info.txt
date
cat info.txt | grep ABENDED
sleep 300
done

SELECT capture_name, (86400*(available_message_create_timecapture_message_create_time))


lag_in_secondsFROM GV$GOLDENGATE_CAPTURE;

SELECT r.apply_name, (86400*(r.dequeue_time -c.lwm_message_create_time)) latency_in_secondsFROM GV$GG_APPLY_

TRANLOGOPTIONS INTEGRATEDPARAMS (MAX_SGA_SIZE 2560, PARALLELISM 3)

https://jinyuwang.weebly.com/core-platform/oracle-goldengate-replication-performance

TRANLOGOPTIONS INTEGRATEDPARAMS (MAX_SGA_SIZE 1024, parallelism 2)


Replicat:
DBOPTIONS INTEGRATEDPARAMS (MAX_SGA_SIZE 1024, parallelism 2)

info all
status manager

send manager childstatus


info extract ext1, detail
send extract ext1 status
stats extract ext1
stats extract ext2 reportrate hr --> hr, min, sec can be used to check the processing rate
send extract myload2, getlag
lag extract ext2
view report ext1

SET LINES rep1,


info replicat 300 detail
COL
send start_time FOR
replicat rep1 A20
status
COL
stats sid FORrep1
replicat 99999
COL
stats serial#
replicatFOR 999999
myload2 reportrate sec --> hr, min, sec can be used to check the processing rate
COL
send username FOR A20
replicat myload2, getlag
COL status myload2*
lag replicat FOR A10
COL schemaname
view report rep1 FOR A10
COL process FOR A10
COL machine FOR A15
COL program FOR A30
COL module FOR A35
COL logon_time FOR A20
SELECT t.start_time,s.sid,s.serial#,s.username,
s.status, s.schemaname, s.process,s.machine,
s.program, s.module, used_ublk, used_urec,
TO_CHAR(s.logon_time,'mon-dd-yyyy HH24:MI:SS') logon_time
FROM v$transaction t, v$session s
WHERE s.saddr = t.ses_addR
ORDER BY start_time;
https://www.support.dbagenesis.com/post/golden-gate-performance-tuning-tips

OM GV$GG_APPLY_READER r, GV$GG_APPLY_COORDINATOR c WHERE r.apply# = c.apply# AND r.apply_name= c.apply_name;


Oracle Golden Gate Replication will not propagate transactions to the destination which have
NOT been committed on the source yet.
However Oracle Golden gate will write the open transaction data to the dirtemp directory in the
home directory.

This data will then be read back later when the transaction is committed and needs to be
propagated to the destination. This is especially true when bulk transactions are run,
processing a large account of the uncommitted data, which then has to be written temporarily
to the dirtemp location.
apply_name= c.apply_name;
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_CURRE
from
NT,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_DURATIO
N,
NEXT_RUN_DATE, MAX_RUN_DURATION,COMMENTS FROM
DBA_SCHEDULER_JOBS;
X$ Views

List the hidden parameters in the oracle database


undocumented init parameters:
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

History of no of process/session in oracle

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

select a.snap_id,a.begin_interval_time begin,a.end_interval_time end,b.*


from DBA_HIST_SNAPSHOT a join DBA_HIST_RESOURCE_LIMIT b on a.snap_id=b.snap_id
where a.BEGIN_INTERVAL_TIME > sysdate - interval '6' hour
and b.RESOURCE_NAME in ('processes','sessions') order by b.RESOURCE_NAME,a.snap_id;

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
create directory BDUMP as '/u01/app/oracle/admin/mysid/bdump';
----------------------------------------------------------------
column dbname new_value dbname print
create table
select name dbname from v$pdbs;
alert_log ( msg varchar2(80) )
column timendate new_value spooltime print
organization external (
select SYS_CONTEXT('USERENV', 'DB_UNIQUE_NAME')||'_'||SYS_CONTEXT('USERENV', 'SESSION_USER')||'_'||
type oracle_loader
to_char(sysdate,'dd-mon-yyyy-hh24-mi-ss') timeNdate from dual;
default directory BDUMP
spool
CREATE &dbname-&spooltime..log
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)
)
)
ERROR at lineRows
-- Generate 1:
ORA-00350:
while (l_cntlog 1 of instance sambaar (thread 1) needs to be archived
< l_rows)
ORA-00312:
loop online log 1 thread 1:
and we check/*+ its opened*/file descriptors
'/ora10gsoft/10.2.0/oradata/sambaar/redo01a.log'
insert APPEND into bigtab for our file:
ls -l /proc/2661/fd |
select rownum+l_cnt, grep test_rm
lrwx------ 1OWNER,
oracle dba 64 Mar 26 14:02
OBJECT_NAME, 66 -> /var/tmp/test_rm.dbf (deleted)
SUBOBJECT_NAME,
SQL> OBJECT_ID, DATA_OBJECT_ID,
SQL> OBJECT_TYPE, CREATED, LAST_DDL_TIME,
here
SQL>it alter
is: TIMESTAMP,
system checkpoint; STATUS, TEMPORARY,
ls -l /proc/2661/fd/66
GENERATED, SECONDARY
lrwx------
System 1 oracle
bigtab dba 64 Mar 26 14:02 /proc/2661/fd/66 -> /var/tmp/test_rm.dbf (deleted)
altered.
from
Run this
where rownum <= l_rows-l_cnt;
l_cnt := l_cnt + sql%rowcount;
$ cd $ORACLE_HOME/install
commit;
$ ./changePerm.sh
end loop;
In
SQL>
end;some other
alter unix, lsof
database dropmay be needed
logfile group 1;to map the file descriptor with the deleted file name
alter
/ database drop logfile group 1
*
ERROR
alter table atbigtab
line 1:add constraint
first we setprimary
ORA-00350:
bigtab_pk 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
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;
.
Template location
Database altered.
-------------------
select
c:\oracle\product\10.2.0\db_1\assistants\dbca\templates
samp.dbid,
SQL>
OEM Scripts
fu.name,
------------
samp.version,
\\networkdrive\k$\oracle\product\10.2.0\db_1\sysman\admin\emdrep\sql
detected_usages,
Database Creation
total_samples,
-------------------
decode(to_char(last_usage_date, 'MM/DD/YYYY, HH:MI:SS'),
C:\WINDOWS\system32\cmd
NULL, 'FALSE', /c call K:\oracle\product\10.2.0\db_1/bin/dbca.bat -progress_only -createDatabase -
templateName General_Purpose.dbc
to_char(last_sample_date, -gdbName HH:MI:SS'),
'MM/DD/YYYY, test -sid test 'TRUE',
-sysPassword 05f6050bc031e3dc104db3b733a0228c44 -
systemPassword
'FALSE') 05f6050bc031e3dc104db3b733a0228c44 -sysmanPassword 05c5f468c03129e8c2b5ed24021b2f7200
-dbsnmpPassword
currently_used, 05c5f468c03129e8c2b5ed24021b2f7200 -emConfiguration LOCAL -datafileJarLocation K:\oracle\
product\10.2.0\db_1\assistants\dbca\templates
first_usage_date, -datafileDestination K:\oracle\product\10.2.0\oradata -responseFile
NO_VALUE -characterset WE8MSWIN1252 -obfuscatedPasswords true -sampleSchema true -
last_usage_date,
recoveryAreaDestination
aux_count, NO_VALUE
feature_info,
last_sample_date,
begin
last_sample_period,
sys.dbms_system.ksdwrt(2, 'My own message');
sample_interval,
end;
mt.description
/
from
wri$_dbu_usage_sample samp,
wri$_dbu_feature_usage fu,
wri$_dbu_feature_metadata mt
where
samp.dbid = fu.dbid and
samp.version = fu.version and
fu.name = mt.name and
fu.name not like '_DBFUS_TEST%' and /* filter out test features */
bitand(mt.usg_det_method, 4) != 4 /* filter out disabled features */;
# Set up machine independent variables
stty erase '^H' kill "^U" intr "^C" eof "^D"
umask 002
export JAVA_COMPILER=NONE
export HOST=$(uname -n)
Sql>
exportalter system suspend;
PWD=`pwd`
Sql> select database_status from v$instance;
export PS1='$ORACLE_SID@$HOST: $PWD> '
if [ -s "$MAIL" ] # This is at Shell startup. In normal
Database_status
then echo "$MAILMSG" # operation, the Shell checks
-----------------
fi # periodically.
Suspended
http://www.orafaq.com/papers/dissassembling_the_data_block.pdf
SQL> select
Sql> alter active_state
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 '\' andx ISDEFAULT='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
I created the tablespace with this SQL
column dbname new_value dbname
create undo
this gives lot tablespace undotbs2
of space output during datafile
spool -WASTE noprint
'/u02/oracle/oradata/test/undotbs2.dbf' size 500m;
---------------------------------------------------------------- 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-db\folder\
Alter
column thetimendate
database new_value
to use the new UNDOnoprint
spooltime tablespace. &dbname..xls
select SYS_CONTEXT('USERENV',
SQL> select t.ts#, s.header_file, s.header_block 'DB_UNIQUE_NAME')||'_'|| select * from all_db_links;
alter system set undo_tablespace=undotbs2
SYS_CONTEXT('USERENV', scope=both;
'SESSION_USER')||'_'|| spool off
from v$tablespace t, dba_segments s
to_char(sysdate,'dd-mon-yyyy-hh24-mi-ss')
where s.owner = 'SCOTT' timeNdate from dual; SET MARKUP HTML OFF
spool &dbname-&spooltime..log
and s.segment_name='DEPARTMENT'
and t.name = s.tablespace_name;
Then take the original UNDO tablespace offline
TS# HEADER_FILE HEADER_BLOCK
alter tablespace undotbs1 offline;
----------
SELECT----------- ------------
utl_inaddr.get_host_address('yahoo.com') FROM dual;
Next drop the corrupted segment.
15 12 9
drop rollback segment "_SYSSMU22$";
Once these three data items are retrieved, the dbv command can
be applied to a particular segment:
Then finally drop the old UNDO tablespace

alter tablespace undotbs1 offline;


dbv userid=scott/tiger segment_id=15.12.9

alter system set log_archive_dest_1='location=/ora10gsoft/archsam


reopen';
Total Pages Examined
col ORIGINATING_TIMESTAMP : 4 for a40
The last step in resolving
col MESSAGE_TEXT for a80 ORA-00257 is to change the logs for
Total Pages
verification Processed
using:
set linesize 500 (Data) : 3 SELECT
SELECT originating_timestamp,
Total
SQL> Pages Failingswitch
alter system
originating_timestamp, (Data) :0
logfile; message_text
message_text FROM
Total
FROMPages Processed (Index): 0 sys.x$dbgalertext
sys.x$dbgalertext WHERE
Total
WHERE Pages Failing (Index): 0 message_text LIKE '%Instance
message_text LIKE '%Starting up%'; shutdown complete%';
Total Pages Processed (Other): 0

Total Pages Processed (Seg) : 1

Total Pages Failing (Seg) : 0

Total Pages Empty :0

Total Pages
Solaris Marked Corrupt-kv: 0
--> /usr/bin/isainfo cd $ORACLE_HOME/bin
Linux --> uname -m file oracl*
Total Pages Influx :0

Automating dbv
http://www.oracle.com/technetwork/articles/saternos-tables-090560.html
http://dbaoracletips.blogspot.com/2011/11/how-to-dropcreate-database-link-from.html
http://www.orafaq.com/wiki/ChangePerm_sh

This is used when when we loss our all redologs.


U can connect as user called OLD. But if u query it will show only
user as NEW. U can't connect as NEW also.

If you want to display your SID, your connected USER name


instead of “SQL>” you’ve to change “glogin.sql” in your
$ORACLE_HOME/sqlplus/admin directory as below

Revoking that privilege


ALTER USER apex_030200 REVOKE CONNECT THROUGH
system;
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_off
dmse_off
dv_off
lbac_off
part_off
rac_off
sdo_off
rat_off
olap_off
asm_off
ctx_off
Pwd verify function extract password

Backdoor Entry to oracle database

oracle password hack

extract dblink password

spoof OSUSER in v$session

Wallet
--ORA-28365: wallet is not open

Wallet status

Key info

Wallet status for cdb & pdb

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
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
B7DC823346DEB4CD69FE6F20B3F15821FEFF9F44430EE40C78CAEE37DF25F25C2BEDED
1DD2A61C72351E462BF1B844B2599E5125AE0135EAF7';

dbms_output.put_line ('Plain password: ' || utl_raw.cast_to_varchar2 ( dbms_crypto.decrypt


( substr (db_link_password, 19) , dbms_crypto.DES_CBC_PKCS5 , substr (db_link_password, 3,
16) ) ) );
end;
/

https://oraganism.wordpress.com/2009/10/06/spoofing-vsession-osuser/
Connect to container and check whether WALLET is OPEN or not ? If it is in OPEN state then
connect to PDB and check the same
--ORA-28365: wallet is not open
select status from v$encryption_wallet;
If the wallet is closed at Contaner DB then OPEN it using below command (run in container):

ADMINISTER KEY MANAGEMENT SET KEYSTORE open IDENTIFIED BY abc123


container=all;

If the WALLET IS OPENED in container but CLOSED in PDB level, then run below at container
level

ADMINISTER KEY MANAGEMENT SET KEYSTORE close IDENTIFIED BY abc123


container=all;
ADMINISTER KEY MANAGEMENT SET KEYSTORE open IDENTIFIED BY abc123
container=all;

Now check the wallet status at Container and PBD level:


select status from v$encryption_wallet;
set lines 750 pages 9999
col WRL_PARAMETER for a50
select INST_ID,WRL_TYPE,WRL_PARAMETER,STATUS,WALLET_TYPE from
gv$encryption_wallet;

set lines 300


col name for a10
col key_id for a60
col creation_time for a40
select p.con_id, p.name, p.open_mode, ek.key_id --, ek.creation_time, ek.KEY_USE
from v$pdbs p left outer join v$encryption_keys ek on (ek.con_id = p.con_id)
order by p.con_id;

set lines 300


col name for a15
col wrl_type for a10
col status for a20
select p.con_id, p.name, p.open_mode, ew.wrl_type, ew.wallet_type, ew.status
from v$pdbs p join v$encryption_wallet ew on (ew.con_id = p.con_id)
order by p.con_id;
col old_value format a30
col new_value format a30
break on instance skip 3
select instance_number instance, snap_id, time, parameter_name, old_value, new_value from (
select 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;
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/

https://database-heartbeat.com/2020/12/31/create-pdbs-in-a-data-guard-environment-with-tde-enabled/

select p.con_id, p.name, p.open_mode, ew.wrl_type, ew.wallet_type, ew.status


from v$pdbs p join v$encryption_wallet ew on (ew.con_id = p.con_id)
where p.name = 'PDB2';
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
-tde-enabled/
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


Oracle histogram/Reduce the rate of hard parsing/Tune
Oracle to reduce execution plan instability
Another reason that Oracle might choose bad execution plans
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
https://jazz.net/wiki/bin/view/Deployment/OracleSQL
http://www.nazmulhuda.info/oracle-choosing-bad-executing-plan-for-wrong-cardinality-estimation-and-use-oracle-dynamic-sam
Super
Harish
ampling-or-sql-profile-to-improve-better-execution-plan
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

Common questions

Powered by AI

SQL execution statistics can be monitored and analyzed using views like gv$sql_monitor where you can track sql_exec_start, elapsed_time, and cpu_time. Additionally, gv$sqlarea provides insights into SQL execution plans and resource usage by capturing metrics such as buffer_gets and physical reads/writes. These stats can be collated into reports using DBMS_SQLTUNE where report_sql_monitor_list can be invoked to generate detailed performance insights. This data helps in identifying execution bottlenecks and resource-intensive queries, aiding in performance tuning and optimization decisions .

Index fragmentation leads to inefficient data retrieval and increased input/output operations, impacting database performance. Fragmentation occurs due to frequent data modifications that leave fragmented free space within index leaf blocks. To address it, rebuild indexes using 'ALTER INDEX REBUILD' which compacts index nodes and reduces empty space, subsequently optimizing data access paths. It's also essential to monitor index health regularly to determine fragmentation levels and decide on suitable maintenance windows for performing rebuilds .

Oracle provides several diagnostic tools for troubleshooting RAC and clusterware issues including Oracle Trace File Analyzer (TFA), which collects diagnostic data across nodes, cluvfy for cluster verification, and Grid Control for centralized monitoring. These tools help verify configuration settings, diagnose network and storage issues, and resolve CRS and ASM-related errors, providing a comprehensive approach to maintaining cluster health and performance .

To assess and reclaim unused space in Oracle tablespaces, use DBA_FREE_SPACE and DBA_DATA_FILES to compare allocated space against actually used space. Querying DBA_SEGMENTS with the intent of identifying and analyzing high watermark positions versus current usage can also indicate reclaimable space. For reclamation, splitting tablespaces or resizing datafiles after verification of autoextensible and max size parameters ensures safe space recovery, guided by historical usage patterns and growth projections .

Historical snapshot data is crucial for performance tuning as it provides a timeline of performance metrics that helps identify trends and anomalies over time. By analyzing reports from dba_hist_sqlstat and dba_hist_active_sess_history, trends in execution times, resource consumption, and workload patterns can be discerned. This longitudinal view helps in diagnosing issues that stem from cumulative effects or sporadic spikes in resource use, guiding administrators in implementing corrective measures and strategic database optimizations .

When an ACFS file system fails to mount on boot, verify that the ACFS is properly registered and the parameters are configured correctly in the Oracle Cluster Registry (OCR). Ensure the ACFS Resource is enabled and check for any syntax errors in the ACFS commands. Make sure that the ACFS support is enabled, especially if there's a dependency on other filesystems or drivers being loaded first. You might also need to manually start the file system using 'acfsutil mount' command to ensure no configuration step was missed .

To resolve ORA-15063 errors when ASM disks go offline, you need to investigate and address disk or network issues causing the offline status. First, check the ASM alert logs to identify the exact problem such as connectivity or I/O errors . If the issue is with IO waits, ensure that the underlying disk subsystem is healthy and there are no network issues impacting the availability. Using ASMCMD and checking the output of diagnostic commands like 'kfed' can also help identify issues with disk headers or corruptions . Additionally, making sure the ASM is configured correctly with the right permissions and settings is essential to prevent these errors .

Oracle ASM simplifies storage management by abstracting physical storage complexities, allowing databases to leverage disk groups independently of individual disks. It enhances performance through its striping and mirroring features, which distribute data evenly across disks to optimize I/O operations. ASM also provides scalable storage management, enabling easy addition or removal of disks without service interruption, promoting efficient resource utilization and high availability .

When managing Oracle Scheduler jobs, follow best practices such as defining detailed job schedules with specific start and end dates, regular monitoring and logging of jobs via views like DBA_SCHEDULER_JOB_LOG to capture failures and durations, and using job chains for complex workflows. Implement failover policies and set appropriate job priorities to ensure critical tasks complete on time. Always test new jobs in a staging environment before deploying to production to minimize disruptions .

Asynchronous Change Data Capture (CDC) in Oracle databases captures data changes asynchronously, allowing for efficient data replication and integration tasks. CDC tracks changes to tables with minimal impact on the source database's performance, making it suitable for data warehousing and real-time analytics environments. The captured data can be stored in a staging area for downstream processes, enabling seamless data synchronization across diverse systems and supporting complex ETL operations .

You might also like