Friday, 11 October 2019

oracle scripts


Ref  https://aodba.com/category/oracle-scripts/
Oracle DBA scripts -

Must have pdf guide to perform your daily DBA tasks

Index
How to check users, roles and privileges in Oracle
How to check high resource intensive SQL in Oracle
How to check execution plan of a query
How to backup archivelog for specific sequence RMAN
How to check last CPU applied in Oracle
How to check biggest table in Oracle
How to check database backups via sqlplus
How to display date and time in query output
How to check scheduler jobs in Oracle
How to check datapump export progress
How to drop all schema objects in Oracle
How to find memory used by Oracle
How to check last user login Oracle
How to check CPU cores in Linux
How to delete files older than X days in Linux
How to analyze wait events in Oracle
How to set DISPLAY variable in Linux
Crontab error - Permission Denied
How to check FRA location utilization in Oracle
How to check last modified table in Oracle
How to check single table size in oracle
How to check database PITR after refresh
How to check archive generation in Oracle
How to disable firewall in Linux 7
How to check database lock conflict in Oracle
How to check database size in Oracle
How to configure yum server in linux
How to check query plan change in oracle
How to force users change password on first login Linux
How to check datafile utilization in Oracle
How to estimate flashback destination space
How to check temp tablespace utilization
How to check users, roles and privileges in Oracle
How to check users, roles and privileges in
Oracle

Query to check the granted roles to a user

SELECT *
FROM DBA_ROLE_PRIVS
WHERE GRANTEE = '&USER';

Query to check privileges granted to a user

SELECT *
FROM DBA_TAB_PRIVS
WHERE GRANTEE = 'USER';

Privileges granted to a role which is granted to a user

SELECT * FROM DBA_TAB_PRIVS WHERE GRANTEE IN
(SELECT granted_role FROM DBA_ROLE_PRIVS WHERE GRANTEE = '&USER') order by 3;
Query to check if user is having system privileges
SELECT *
FROM DBA_SYS_PRIVS
WHERE GRANTEE = '&USER';
Query to check permissions granted to a role
select * from ROLE_ROLE_PRIVS where ROLE = '&ROLE_NAME';
select * from ROLE_TAB_PRIVS where ROLE = '&ROLE_NAME';
select * from ROLE_SYS_PRIVS where ROLE = '&ROLE_NAME';

| How to check users, roles and privileges in Oracle

How to check high resource intensive SQL in

Oracle

Database performance is a major concern for a DBA. SQLs are the ones
which needs proper DB management in order to execute well. At times the
application team might tell you that the database is running slow. You can
run below query to get the top 5 resource intensive SQL with SQL ID and
then give it to application team to optimize them.

col Rank for a4
SELECT *
FROM (SELECT RANK () OVER
(PARTITION BY "Snap Day" ORDER BY "Buffer Gets" + "Disk Reads" DESC) AS "Rank", i1.*
FROM (SELECT TO_CHAR (hs.begin_interval_time, 'MM/DD/YY' ) "Snap Day",
SUM (shs.executions_delta) "Execs",
SUM (shs.buffer_gets_delta) "Buffer Gets",
SUM (shs.disk_reads_delta) "Disk Reads",
ROUND ( (SUM (shs.buffer_gets_delta)) / SUM (shs.executions_delta), 1 ) "Gets/Exec",
ROUND ( (SUM (shs.cpu_time_delta) / 1000000) / SUM (shs.executions_delta), 1 ) "CPU/Exec(S)",
ROUND ( (SUM (shs.iowait_delta) / 1000000) / SUM (shs.executions_delta), 1 ) "IO/Exec(S)",
shs.sql_id "Sql id",
REPLACE (CAST (DBMS_LOB.SUBSTR (sht.sql_text, 50) AS VARCHAR (50) ), CHR (10), '' ) "Sql"
FROM dba_hist_sqlstat shs INNER JOIN dba_hist_sqltext sht
ON (sht.sql_id = shs.sql_id)
INNER JOIN dba_hist_snapshot hs
ON (shs.snap_id = hs.snap_id)
HAVING SUM (shs.executions_delta) > 0
GROUP BY shs.sql_id, TO_CHAR (hs.begin_interval_time, 'MM/DD/YY'),
CAST (DBMS_LOB.SUBSTR (sht.sql_text, 50) AS VARCHAR (50) )
ORDER BY "Snap Day" DESC) i1
ORDER BY "Snap Day" DESC)
WHERE "Rank" <= 5 AND "Snap Day" = TO_CHAR (SYSDATE, 'MM/DD/YY');

| How to check high resource intensive SQL in Oracle

How to check execution plan of a query

First get the sql ID and then you can use below command to generate
execution plan of a query in oracle
SELECT * FROM table(DBMS_XPLAN.DISPLAY_CURSOR('2t3nwk8h97vph',0));
In case you have more IDs, use below command to supply sql id every time
you run the query
SELECT * FROM table(DBMS_XPLAN.DISPLAY_CURSOR('&sql_id',0));

DBA | How to check execution plan of a query
How to backup archivelog for specific
sequence RMAN
When you issue archive backup commands via RAMN, it will backup all the
archive logs. Sometimes, you might need to backup only a particular
archive log sequence. Below command will help you backup archive logs
between specific sequence
RMAN> BACKUP ARCHIVELOG FROM SEQUENCE 288 UNTIL SEQUENCE 388 DELETE INPUT;
The above command will backup archive logs from 288 to 388 sequence
number.

DBA | How to backup archivelog for specific sequence RMAN
How to check last CPU applied in Oracle
Generally if you have one single database install then checking the
database inventory will give you the latest patch details. But! if we have
multiple database in single oracle home then it might not give correct
results. There might be a chance that one DB is applied with latest patches
and others are not. In such cases, we need to check last CPU applied by
logging into the database using below query:
Query to Check Last CPU Applied on a Database:
col VERSION for a15;
col COMMENTS for a50;
col ACTION for a10;
set lines 500;
select ACTION,VERSION,COMMENTS,BUNDLE_SERIES from registry$history;
What are Critical Patch Updates (CPUs)?
Critical Patch Updates are sets of patches containing 􀁓xes for security
􀁔aws in Oracle products. The Critical Patch Update program (CPU) was
introduced in January 2005 to provide security 􀁓xes on a 􀁓xed, publicly
available schedule to help customers lower their security management
costs.

DBA | How to check last CPU applied in Oracle
How to check biggest table in Oracle
As a DBA, you must keep an eye on the largest tables in the database.
There are many things that get impacted with the largest objects like DB
performance, growth, index rebuild etc. The below query gives you the top
10 largest tables in oracle database.
Query to check top 10 largest tables in Oracle
SELECT * FROM
(select
SEGMENT_NAME,
SEGMENT_TYPE,
BYTES/1024/1024/1024 GB,
TABLESPACE_NAME
from
dba_segments
order by 3 desc ) WHERE
ROWNUM <= 10
DBA | How to check biggest table in Oracle
How to check database backups via sqlplus
Checking Database backups are one of the main focus areas of a DBA.
Time to time, DBA needs to check database backup status and see if its
completed, failed, running etc. Also, DBA must be able to get the backup
start time, end time and even the backup size for reference purpose. The
below query gives answers to all the backup details in oracle
Query to check database backup status
set linesize 500
col BACKUP_SIZE for a20
SELECT
INPUT_TYPE "BACKUP_TYPE",
--NVL(INPUT_BYTES/(1024*1024),0)"INPUT_BYTES(MB)",
--NVL(OUTPUT_BYTES/(1024*1024),0) "OUTPUT_BYTES(MB)",
STATUS,
TO_CHAR(START_TIME,'MM/DD/YYYY:hh24:mi:ss') as START_TIME,
TO_CHAR(END_TIME,'MM/DD/YYYY:hh24:mi:ss') as END_TIME,
TRUNC((ELAPSED_SECONDS/60),2) "ELAPSED_TIME(Min)",
--ROUND(COMPRESSION_RATIO,3)"COMPRESSION_RATIO",
--ROUND(INPUT_BYTES_PER_SEC/(1024*1024),2) "INPUT_BYTES_PER_SEC(MB)",
--ROUND(OUTPUT_BYTES_PER_SEC/(1024*1024),2) "OUTPUT_BYTES_PER_SEC(MB)",
--INPUT_BYTES_DISPLAY "INPUT_BYTES_DISPLAY",
OUTPUT_BYTES_DISPLAY "BACKUP_SIZE",
OUTPUT_DEVICE_TYPE "OUTPUT_DEVICE"
--INPUT_BYTES_PER_SEC_DISPLAY "INPUT_BYTES_PER_SEC_DIS",
--OUTPUT_BYTES_PER_SEC_DISPLAY "OUTPUT_BYTES_PER_SEC_DIS"
FROM V$RMAN_BACKUP_JOB_DETAILS
where start_time > SYSDATE -10
and INPUT_TYPE != 'ARCHIVELOG'
ORDER BY END_TIME DESC
/
Query to check archive Backup status
In the 3rd last line and INPUT_TYPE != 'ARCHIVELOG', just remove '!' to
get archivelog backup details

DBA | How to check database backups via sqlplus
How to display date and time in query output
By default, when you query a date column, oracle will only display dates
and not time. Below query enables Oracle to display both date and time for
a particular session
alter session set nls_date_format='dd-Mon-yyyy hh:mi:sspm';
Note – this is only session level query.

DBA | How to display date and time in query output
How to check scheduler jobs in Oracle
Below command will help you check Scheduler jobs which are con􀁓gured
inside database
SELECT JOB_NAME, STATE FROM DBA_SCHEDULER_JOBS where job_name='RMAN_BACKUP';
Query to check currently running scheduler jobs
SELECT * FROM ALL_SCHEDULER_RUNNING_JOBS;
All the DBA Scheduler jobs create logs. You can query below and check the
details of job logs
select log_id, log_date, owner, job_name
from ALL_SCHEDULER_JOB_LOG
where job_name like 'RMAN_B%' and log_date > sysdate-2;
select log_id,log_date, owner, job_name, status, ADDITIONAL_INFO
from ALL_SCHEDULER_JOB_LOG
where log_id=113708;

DBA | How to check scheduler jobs in Oracle
How to check datapump export progress
Sometimes when you run datapump export, it might take a lot of time.
Meanwhile client might ask you for the % of export completed. Use below
query to get the details of how much % export is done.
SELECT SID, SERIAL#, USERNAME, CONTEXT, SOFAR, TOTALWORK,
ROUND(SOFAR/TOTALWORK*100,2) "%_COMPLETE"
FROM V$SESSION_LONGOPS WHERE TOTALWORK != 0 AND SOFAR <> TOTALWORK;

DBA | How to check datapump export progress
How to drop all schema objects in Oracle
The below script will drop all the objects owned by a schema. This will not
delete the user but only deletes the objects
SET SERVEROUTPUT ON SIZE 1000000
set verify off
BEGIN
FOR c1 IN (SELECT OWNER,table_name, constraint_name FROM dba_constraints
WHERE constraint_type = 'R' and owner=upper('&shema_name')) LOOP
EXECUTE IMMEDIATE
'ALTER TABLE '||' "'||c1.owner||'"."'||c1.table_name||'" DROP CONSTRAINT ' || c1.constraint_name;
END LOOP;
FOR c1 IN (SELECT owner,object_name,object_type FROM dba_objects
where owner=upper('&shema_name')) LOOP
BEGIN
IF c1.object_type = 'TYPE' THEN
EXECUTE IMMEDIATE 'DROP '||c1.object_type||' "'||c1.owner||'"."'||c1.object_name||'" FORCE';
END IF;
IF c1.object_type != 'DATABASE LINK' THEN
EXECUTE IMMEDIATE 'DROP '||c1.object_type||' "'||c1.owner||'"."'||c1.object_name||'"';
END IF;
EXCEPTION
WHEN OTHERS THEN
NULL;
END;
END LOOP;
EXECUTE IMMEDIATE('purge dba_recyclebin');
END;
/

DBA | How to drop all schema objects in Oracle
How to find memory used by Oracle
select decode( grouping(nm), 1, 'total', nm ) nm, round(sum(val/1024/1024)) mb
from
(
select 'sga' nm, sum(value) val
from v$sga
union all
select 'pga', sum(a.value)
from v$sesstat a, v$statname b
where b.name = 'session pga memory'
and a.statistic# = b.statistic#
)
group by rollup(nm);

DBA | How to find memory used by Oracle
How to check last user login Oracle
While performing database audits, you might need to check who logged in
last into the database. The query will help you find out last user who logged
in to database
select username, timestamp, action_name from dba_audit_session
where action_name='LOGON' and
rownum<10 and username not in ('SYS','DBSNMP','DUMMY','SYSTEM','RMAN');

DBA | How to check last user login Oracle
How to check CPU cores in Linux
Command to check CPU info on Linux
cat /proc/cpuinfo|grep processor|wc -l
OR
nproc --all
OR
getconf _NPROCESSORS_ONLN
Command to check CPU info on Solaris
psrinfo -v|grep "Status of processor"|wc -l
Command to check CPU info on AIX
lsdev -C|grep Process|wc -l
Command to check CPU info on HP/UX
ioscan -C processor | grep processor | wc -l

DBA | How to check CPU cores in Linux
How to delete files older than X days in Linux
Find 􀁓les older than X days and save ouput into a
file
The below Linux command will help you to 􀁓nd 􀁓les older than 35 days in a
specific directory path and save the ouput in backupfiles.log
Here the directory we are searching is /backup/logs and -mtime speci􀁓es
the modi􀁓ed time of a 􀁓le. We are saving the list of all the 􀁓les which are
older than 35 days in backupfiles.log
find /backup/logs -type f -mtime +35 -print > backupfiles.log &
Find 􀁓les older than 7 days and print output on
screen
If you want to print 􀁓les older than 7 days on screen and do not want to
save it into a file, use below command
find /backup/logs -type f -mtime +7 -print
Find 􀁓les in current directory older than 28 days
and remove them
Below linux command will 􀁓nd all the 􀁓les under current location (as we
have speci􀁓ed . dot), search 􀁓le name starting with arc h and ending with
log. check file create time with -ctime older than 28 days and then remove
those files using rm -f
find . -name arch\*log -ctime +28 -exec rm -f {} \;

DBA | How to delete files older than X days in Linux
How to analyze wait events in Oracle
User below query to get the top wait classes in Oracle database
Select wait_class, sum(time_waited), sum(time_waited)/sum(total_waits)
Sum_Waits
From v$system_wait_class
Group by wait_class
Order by 3 desc;
From the above query, supply each wait class into below query to get the
top wait events in database with respect to particular wait class
Select a.event, a.total_waits, a.time_waited, a.average_wait
From v$system_event a, v$event_name b, v$system_wait_class c
Where a.event_id=b.event_id
And b.wait_class#=c.wait_class#
And c.wait_class = '&Enter_Wait_Class'
order by average_wait desc;
DBA | How to analyze wait events in Oracle
How to set DISPLAY variable in Linux
Whenever you want to invoke graphical interface in Linux, You must know
how to set DISPLAY variable in order to open the GUI. Linux by default does
not allow you to open any GUI (Linux Oracle Installer) until you enable the
GUI display.
Use below command to enable Linux GUI interface at command prompt as
root user:
# xhost +
Sometimes, even after issuing above command, you wont be able to
invoke GUI because of “DISPLAY not set” error. In such case, you must
export the display environmental variable:
# echo $DISPLAY
# export DISPLAY=:0.0;
Now you can invoke any Linux GUI interface by directly running the
installer!

DBA | How to set DISPLAY variable in Linux
Crontab error - Permission Denied
When you try to schedule backups under corntab as Oracle user, you
might encounter crontab permission error
[oracle@plcdbprod ~]$ crontab -l
cron/oracle: Permission denied
The error is because of permission issues on /usr/bin/crontab 􀁓le. Login as
root user and find the crontab permissions on /usr/bin/crontab
[root@plcdbprod ~]# ls -l /usr/bin/crontab
-rwxr-xr-x 1 root root 315432 Jul 15 2008 /usr/bin/crontab
Give the below permissions to /usr/bin/crontab file
[root@plcdbprod ~]# chmod 4755 /usr/bin/crontab
[root@plcdbprod ~]# ls -l /usr/bin/crontab
-rwsr-xr-x 1 root root 315432 Jul 15 2008 /usr/bin/crontab
Login as oracle user and check your crontab -e.
Happy Learning!!!

DBA | Crontab error
How to check FRA location utilization in
Oracle
Flash Recovery Area must be monitored regularly. Sometimes FRA runs our
of space and a DBA must be able to gather FRA space utilization. It is very
important to monitor space usage in the fast recovery area to ensure that
it is large enough to contain backups and other recovery-related files.
Below script gives you Flash Recovery Area utilization details:
set linesize 500
col NAME for a50
select name, ROUND(SPACE_LIMIT/1024/1024/1024,2) "Allocated Space(GB)",
round(SPACE_USED/1024/1024/1024,2) "Used Space(GB)",
round(SPACE_RECLAIMABLE/1024/1024/1024,2) "SPACE_RECLAIMABLE (GB)" ,
(select round(ESTIMATED_FLASHBACK_SIZE/1024/1024/1024,2)
from V$FLASHBACK_DATABASE_LOG) "Estimated Space (GB)"
from V$RECOVERY_FILE_DEST;

DBA | How to check FRA location utilization in Oracle
How to check last modified table in Oracle
As a DBA, application team sometimes might ask you to provide details of
last modi􀁓ed table in oracle. The table modi􀁓cation can be insert, update
or delete. Below queries get details of last or latest modi􀁓ed table in oracle
database. Run the queries depending upon the database version.
Last modified table in oracle 10g and Above
set linesize 500;
select TABLE_OWNER, TABLE_NAME, INSERTS, UPDATES, DELETES,
to_char(TIMESTAMP,'YYYY-MON-DD HH24:MI:SS')
from all_tab_modifications
where table_owner<>'SYS' and
EXTRACT(YEAR FROM TO_DATE(TIMESTAMP, 'DD-MON-RR')) > 2010
order by 6;
In 9i, table monitoring has to be enabled manually or else the
all_tab_modifcations wont keep record of changes. 10g onwards, oracle by
default records the modifications
Last modified table in oracle for 9i db
col object for a20;
col object_name for a20;
SELECT OWNER, OBJECT_NAME, OBJECT_TYPE,
to_char(LAST_DDL_TIME,'YYYY-MON-DD HH24:MI:SS')
from dba_objects where LAST_DDL_TIME=(select max(LAST_DDL_TIME)
from dba_objects WHERE object_type='TABLE');
DBA | How to check last modified table in Oracle
How to check single table size in oracle
Once you run the query, it will ask your table name. Enter the table name in
the format of owner.tablename. Eg - scott.emp
select segment_name,segment_type, sum(bytes/1024/1024/1024) GB
from dba_segments
where segment_name='&Your_Table_Name'
group by segment_name,segment_type;
DBA | How to check single table size in oracle
How to check database PITR after refresh
Database refresh is common task for a DBA. But after every database
refresh, you must check the PITR date and time. This should be checked
before you issue OPEN RESETLOGS command.
Query to Check PITR – Issue it before OPEN
RESETLOGS
select distinct to_char(checkpoint_time,'dd/mm/yyyy hh24:mi:ss') checkpoint_time
from v$datafile_header ;
DBA | How to check database PITR after refresh
How to check archive generation in Oracle
The below query gives results of archive generation in oracle database. Use
below query to 􀁓nd the archive space requirements and you can use it to
estimate the archive destination size perfectly well.
SELECT A.*,
Round(A.Count#*B.AVG#/1024/1024/1024) Daily_Avg_gb
FROM
(SELECT
To_Char(First_Time,'YYYY-MM-DD') DAY,
Count(1) Count#,
Min(RECID) Min#,
Max(RECID) Max#
FROM v$log_history
GROUP
BY To_Char(First_Time,'YYYY-MM-DD')
ORDER
BY 1 DESC
) A,
(SELECT
Avg(BYTES) AVG#,
Count(1) Count#,
Max(BYTES) Max_Bytes,
Min(BYTES) Min_Bytes
FROM
v$log ) B;

DBA | How ot check archive generation in Oracle
How to disable firewall in Linux 7
Disabling 􀁓rewall in Linux 5/7 versions is little bit di􀁣erent than Linux 7.
Sometimes you need to disable 􀁓rewall in Linux 7 version as part of
Database installation pre-requisites. This article will help you to 􀁓nd the
status of firewall and then enable / disable it.
Firewall Status
The below command will show you the current status “Active” in case
firewall is running:
# systemctl status firewalld
Firewall stop / start
You can start/stop Linux firewall with below commands:
# service firewalld stop
# service firewalld start
Firewall Disable / Enable
You can enable/disable 􀁓rewall completely on Linux with below
commands:
# systemctl disable firewalld
# systemctl enable firewalld

DBA | How to disable firewall in Linux 7
How to check database lock conflict in Oracle
Database lock con􀁔icts are one of the issues which DBA needs to deal
with. The database locks can keep users waiting for very long and we much
know how to check database locks. Users reporting that their query is
taking too long to execute, then you must also check if there are any locks
on the objects being accessed (unless its a select query). Use below
queries to check the database locks:
Checking Lock Conflicts in 10g and Above:
select a.SID "Blocking Session", b.SID "Blocked Session"
from v$lock a, v$lock b
where a.SID != b.SID and a.ID1 = b.ID1 and a.ID2 = b.ID2 and
b.request > 0 and a.block = 1;
Checking Lock Conflicts in 9i Systems:
select s1.username || '@' || s1.machine
|| ' ( SID=' || s1.sid || ' ) is blocking '
|| s2.username || '@' || s2.machine
|| ' ( SID=' || s2.sid || ' ) ' AS blocking_status
from v$lock l1, v$session s1, v$lock l2, v$session s2
where s1.sid=l1.sid and s2.sid=l2.sid
and l1.BLOCK=1 and l2.request > 0
and l1.id1 = l2.id1
and l2.id2 = l2.id2 ;
Query to Check Lock is Table Level or Row Level
col session_id head 'Sid' form 9999
col object_name head "Table|Locked" form a30
col oracle_username head "Oracle|Username" form a10 truncate
col os_user_name head "OS|Username" form a10 truncate
col process head "Client|Process|ID" form 99999999
col owner head "Table|Owner" form a10
col mode_held form a15
select lo.session_id,lo.oracle_username,lo.os_user_name,
lo.process,do.object_name,do.owner,
decode(lo.locked_mode,0, 'None',1, 'Null',2, 'Row Share (SS)',
3, 'Row Excl (SX)',4, 'Share',5, 'Share Row Excl (SSX)',6, 'Exclusive',
to_char(lo.locked_mode)) mode_held
from gv$locked_object lo, dba_objects do
where lo.object_id = do.object_id
order by 5
/

DBA | How to check database lock conflict in Oracle
How to check database size in Oracle
A DBA works on many aspects of database like cloning, backup,
performance tuning etc. In every aspect of database administration, most
of the times resolution depends upon the size of database. For example,

DBA can implement DB FULL backup strategy on a very small database
when compared to DB INCREMENTAL strategy on a very large database.
Use below script to check db size along with Used space and free space in
database:
col "Database Size" format a20
col "Free space" format a20
col "Used space" format a20
select round(sum(used.bytes) / 1024 / 1024 / 1024 ) || ' GB' "Database Size"
, round(sum(used.bytes) / 1024 / 1024 / 1024 ) -
round(free.p / 1024 / 1024 / 1024) || ' GB' "Used space"
, round(free.p / 1024 / 1024 / 1024) || ' GB' "Free space"
from (select bytes
from v$datafile
union all
select bytes
from v$tempfile
union all
select bytes
from v$log) used
, (select sum(bytes) as p
from dba_free_space) free
group by free.p
/

DBA | How to check database size in Oracle
How to configure yum server in linux
In this article, we will learn how to con􀁓gure yum server in di􀁣erent Oracle
Linux versions. YUM repository is a software package manager which
allows you to easily install, update or delete RPMs. Most of the required
RPM packages come along with the Linux installer CD. But! if you have
internet connection, you can con􀁓gure YUM repository on Linux and this
will remove installer CD or iso file dependency.
Most of the times when you want to install packages (RPMs) for Oracle
products, it really becomes tough to identify and install each package.
Good news is! you can connect to Yum server and get the packages at one
shot!
Download and configure yum server
Download and copy the appropriate yum con􀁓guration 􀁓le in place, by
running the following commands as root:
cd /etc/yum.repos.d
For Oracle Linux 7
# wget http://public-yum.oracle.com/public-yum-ol7.repo
For Oracle Linux 6
# wget http://public-yum.oracle.com/public-yum-ol6.repo
For Oracle Linux 5
# wget http://public-yum.oracle.com/public-yum-el5.repo
Download and install Oracle Linux
Download and install Oracle Linux and make sure your are able to connect
to internet. Start using yum server with below commands:
# yum list --> to list all the contents of yum repository
# yum install oracle-validated --> to install oracle-valudated package
# yum install libaio-devel* --> to install libaio-devel rpm
The oracle-validated package will install all the packages required to install
Oracle Database and RAC on OEL 5.

DBA | How to configure yum server in linux
How to check query plan change in oracle
If you would like to 􀁓nd out change in SQL plan of a query, below script will
help you 􀁓nd the SQL plan ID for previous executions and check if there is
any change in SQL plan ID.

set pagesize 1000
set linesize 200
column begin_interval_time format a20
column milliseconds_per_execution format 999999990.999
column rows_per_execution format 999999990.9
column buffer_gets_per_execution format 999999990.9
column disk_reads_per_execution format 999999990.9
break on begin_interval_time skip 1
SELECT
to_char(s.begin_interval_time,'mm/dd hh24:mi')
AS begin_interval_time,
ss.plan_hash_value,
ss.executions_delta,
CASE
WHEN ss.executions_delta > 0
THEN ss.elapsed_time_delta/ss.executions_delta/1000
ELSE ss.elapsed_time_delta
END AS milliseconds_per_execution,
CASE
WHEN ss.executions_delta > 0
THEN ss.rows_processed_delta/ss.executions_delta
ELSE ss.rows_processed_delta
END AS rows_per_execution,
CASE
WHEN ss.executions_delta > 0
THEN ss.buffer_gets_delta/ss.executions_delta
ELSE ss.buffer_gets_delta
END AS buffer_gets_per_execution,
CASE
WHEN ss.executions_delta > 0
THEN ss.disk_reads_delta/ss.executions_delta
ELSE ss.disk_reads_delta
END AS disk_reads_per_execution
FROM wrh$_sqlstat ss
INNER JOIN wrm$_snapshot s ON s.snap_id = ss.snap_id
WHERE ss.sql_id = '&sql_id'
AND ss.buffer_gets_delta > 0
ORDER BY s.snap_id, ss.plan_hash_value;

DBA | How to check query plan change in oracle
How to force users change password on first
login Linux
How to force users change their passwords upon 􀁓rst login in Linux? How
to make sure user changes password at next login time in Linux?
You can force a user to change their password upon 􀁓rst time login to
Linux server. You can even force existing users to change their passwords
on next login. This is done using c hage command in Linux. The chage
command will change the user password expiry information.
The below chage command will make user password expired. Hence, this
will force user to provide a new password. Here we are forcing oracle user
to change password on next login
# chage -d 0 oracle
The option -d 0 will mark the password expired and hence, user will be
forced to change password.

DBA | How to force users change password on first login Linux
How to check datafile utilization in Oracle
When you want to shrink a data􀁓le, you must always check the single
data􀁓le utilization. In case if you shrink data􀁓le more than the used size, it
will fail. Below query gives the data􀁓le utilization and depending upon the
datafile free space, you can shrink it
col file_name for a60;
set pagesize 500;
set linesize 500;
SELECT SUBSTR (df.NAME, 1, 40) file_name, df.bytes / 1024 / 1024 allocated_mb,
((df.bytes / 1024 / 1024) - NVL (SUM (dfs.bytes) / 1024 / 1024, 0))
used_mb,
NVL (SUM (dfs.bytes) / 1024 / 1024, 0) free_space_mb
FROM v$datafile df, dba_free_space dfs
WHERE df.file# = dfs.file_id(+)
GROUP BY dfs.file_id, df.NAME, df.file#, df.bytes
ORDER BY file_name;

DBA | How to check datafile utilization in Oracle
How to estimate flashback destination space
Sometimes application team will ask DBA to enable 􀁔ashback for x
number of days. In such case, a DBA needs to estimate the 􀁔ashback
space required for x number of days in order to store the 􀁔ashback logs.
The flashback log size is same as archive log size generated in a database.
Check the archive generation size via below query
Take the average per day size of archives generated
Multiply the average archive size with x number of days
Ask storage team to add the required space for flashback file system

Check archive generation size via below query:
select to_char(COMPLETION_TIME,'DD-MON-YYYY') Arch_Date,count(*) No#_Logs,
sum((BLOCKS*512)/1024/1024/1024) Arch_LogSize_GB
from v$archived_log
where to_char(COMPLETION_TIME,'DD-MON-YYYY')>=trunc(sysdate-7) and DEST_ID=1
group by to_char(COMPLETION_TIME,'DD-MON-YYYY')
order by to_char(COMPLETION_TIME,'DD-MON-YYYY');
Note: Take average size * 30 days to get 1 month flashback space size.

DBA | How to estimate flashback destination space

How to check temp tablespace utilization
set lines 200
select TABLESPACE_NAME, sum(BYTES_USED/1024/1024),sum(BYTES_FREE/1024/1024)
from V$TEMP_SPACE_HEADER group by TABLESPACE_NAME;
SELECT A.tablespace_name tablespace, D.GB_total,
SUM (A.used_blocks * D.block_size) / 1024 / 1024 /1024 GB_used,
D.mb_total - SUM (A.used_blocks * D.block_size) / 1024 / 1024 / 1024 GB_free
FROM v$sort_segment A,
(
SELECT B.name, C.block_size, SUM (C.bytes) / 1024 / 1024 /1024 GB_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.GB_total;

Thursday, 10 October 2019

query is running slow--cpu utilization 100%

query is running slow.


select sid,opname,target,round(sofar/totalwork*100,2) as percent_done,start_time,last_update_time,time_remaining
from v$session_longops;


select sid,inst_id,opname,totalwork,sofar,start_time,time_remaining
from gv$session_longops
where totalwork<>sofar
/


SQL> select event
from v$session
where sid =  2    3  1071;

EVENT
----------------------------------------------------------------
db file sequential read

SQL> select p1,p2 from v$session where sid=1071;

        P1         P2
---------- ----------
         9  108379037

SQL> select SID, state, event, p1, p2,username from v$session where sid=1071;

       SID STATE
---------- -------------------
EVENT                                                                    P1
---------------------------------------------------------------- ----------
        P2
----------
USERNAME
--------------------------------------------------------------------------------
      1071 WAITED SHORT TIME
db file sequential read                                                   9
 108379059
OMIRO


SQL> select owner, segment_name
from dba_extents
where file_id = 9
and 108379059 between block_id
and block_id + blocks;  2    3    4    5

OWNER
--------------------------------------------------------------------------------
SEGMENT_NAME
--------------------------------------------------------------------------------
OMSS
CSW_SY_WHSE_TRACE_FACTS_M02




SQL> select event from v$session where sid=1071;

EVENT
----------------------------------------------------------------
PGA memory operation



select * from v$system_event where event = 'db file sequential read';
For session-level diagnosis, query the V$SESSION_EVENT view and identify the live session that registers a significant amount of time on this event using the query below. Once the session is identified, the DBA can take the necessary steps to find the root cause of this symptom.

select *
from   v$session_event
where  event = 'db file sequential read'
order by time_waited;


select segment_name, partition_name, segment_type, tablespace_name
from   dba_extents a, v$session_wait b
where  b.p2 between a.block_id and (a.block_id + a.blocks - 1)
and    a.file_id  = b.p1
and    b.event    = 'db file sequential read';
The SQL statement associated with this event can be obtained using this query:
select a.sid, a.serial#, a.username, a.osuser, b.sql_text
from   v$session a, v$sqltext b
where  a.sql_hash_value = b.hash_value
and    a.sql_address    = b.address
and    a.sid in (select sid
                 from   v$session_wait
                 where  event = 'db file sequential read')
order by a.sid, b.hash_value, b.piece;






Wednesday, 9 October 2019

oracle 19c new features

source : Refer http://dineshbandelkar.com/oracle-database-19c-new-features/

Automatic Indexing

The automatic indexing feature automates the index management tasks in an Oracle database. Automatic indexing automatically creates, rebuilds, and drops indexes in a database based on the changes in application workload, thus improving database performance. The automatically managed indexes are known as auto indexes.

 col DESCRIPTION for a30
 col ADVISOR_NAME for a25
 col task_name for a30
 select TASK_NAME,DESCRIPTION,ADVISOR_NAME,CREATED,LAST_MODIFIED,LAST_EXECUTION,EXECUTION_START,EXECUTION_END,STATUS,PROGRESS_METRIC
 from dba_advisor_tasks;


 Task Run for Every 15 minutes

 col TASK_NAME for a30
 col EXECUTION_NAME for a30
 set lines 200 pages 5000
 select TASK_NAME,EXECUTION_NAME,EXECUTION_START,EXECUTION_END,STATUS,REQUESTED_DOP,ACTUAL_DOP
 from dba_advisor_executions 
 where TASK_NAME in ('SYS_AUTO_INDEX_TASK','SYS_AI_SPM_EVOLVE_TASK','SYS_AI_VERIFY_TASK')
 order by EXECUTION_START;



TYPE OF INDEX

Refer  http://dbakeeda.blogspot.com/search/label/Indexing

Index Types and their Descriptions

1. B-tree Index: Default, balanced tree index, good for high-cardinality (high degree of distinct values) columns.

2. B-tree cluster Index:  Used with clustered tables.

3. Hash cluster Index:  Used with hash clusters.

4. Function-based Index:  Good for columns that have SQL functions applied to them.

5. Indexed virtual column Index:  Good for columns that have SQL functions applied to them; viable alternative. to using a function-based index.

6. Reverse-key Index:  Useful to balance I/O in an index that has many sequential inserts.

7. Key-compressed Index:  Useful for concatenated indexes where the leading column is often repeated, compresses leaf block entries.

8. Bitmap Index:  Useful in data warehouse environments with low-cardinality columns. these indexes aren’t appropriate for online transaction processing (OLTP) databases
where rows are heavily updated.

9. Bitmap join:  Useful in data warehouse environments for queries that join fact and
dimension tables.

10. Global partitioned:  Global index across all partitions in a partitioned table.

11. Local partitioned: Local index based on individual partitions in a partitioned table.

12. Domain:  Specific for an application or cartridge

In the next topic I will cover the details of B-tree index.




Oracle Index metadata for given table

Index metadata for given table ....

create index statement for given table


ORCL\sys> !cat indx_meta.sql

set heading off
set feedback off
set verify off
prompt set linesize 200
prompt set long 2000
select 'select dbms_metadata.get_ddl(' || '''TABLE'',' || '''' ||table_name||''',' || '''' || owner||''') from dual ;'
from dba_tables where table_name ='&Table_name' ;

set verify on
set heading on
set feedback on

----- out put

ORCL\sys> @indx_meta
set linesize 200
set long 2000
Enter value for table_name: USR_SITES

select dbms_metadata.get_ddl('TABLE','USR_SITES','PROD1') from dual ;






out put of the script

select dbms_metadata.get_ddl('TABLE','USR_SITES','CPROD1') from dual ;


DBMS_METADATA.GET_DDL('TABLE','USER_SITES','CCCPROD1')
--------------------------------------------------------------------------------

CREATE TABLE "PROD1"."USR_SITES"
( "USER_OBJECT_ID" VARCHAR2(16) NOT NULL ENABLE,
"SITE_NO" VARCHAR2(12) NOT NULL ENABLE,
"SITE_DATE_ADDED" DATE NOT NULL ENABLE,
"TANDC_DATE_ACCEPTED" DATE,
CONSTRAINT "USR_SITES_USPK1" PRIMARY KEY ("USER_OBJECT_ID", "SITE_NO")
USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
STORAGE(INITIAL 1048576 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT)
TABLESPACE "DM_CCCPROD1_DOCBASE" ENABLE
) PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING
STORAGE(INITIAL 1048576 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT)
TABLESPACE "PROD1"



1 row selected.


===

or

SELECT DBMS_METADATA.GET_DDL('INDEX',INDEX_NAME,OWNER) FROM DBA_indexes
WHERE TABLE_NAME='USR_SITES'
/

DBMS_METADATA.GET_DDL('INDEX',INDEX_NAME,OWNER)
--------------------------------------------------------------------------------

CREATE UNIQUE INDEX "PROD1"."USR_SITES_USPK1" ON "PROD1"."USER_SITES" (
"USER_OBJECT_ID", "SITE_NO")
PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
STORAGE(INITIAL 1048576 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT)
TABLESPACE "PROD1"

AMM RAC database and switch RAC database to ASMM

Calculate the current memory usage for our AMM RAC database and switch RAC database to ASMM

SQL> select sum(bytes/1024/1024) Current_SGA_SIZE_in_MB from v$sgastat;
CURRENT_SGA_SIZE_IN_MB
----------------------
        904.844437
SQL> select sum(bytes/1024/1024) MAX_SGA_SIZE_in_MB from  v$sgainfo    where name = 'Maximum SGA Size';
MAX_SGA_SIZE_IN_MB
------------------
    1592.84766
SQL> show parameter memory_max_target;
NAME                     TYPE     VALUE
------------------------------------ ----------- ------------------------------
memory_max_target             big integer 1600M
SQL> select (value/1024/1024) Current_PGA_IN_USE_in_MB from v$pgastat where name = 'total PGA inuse';
CURRENT_PGA_IN_USE_IN_MB
------------------------
          122.085938
SQL> select (value/1024/1024) MAX_PGA_ALLOCATED_in_MB from v$pgastat where name = 'maximum PGA allocated';
MAX_PGA_ALLOCATED_IN_MB
-----------------------
         167.658203
SQL> select (value/1024/1024) PGA_TARGET_in_MB    from v$pgastat where name = 'aggregate PGA target parameter';
PGA_TARGET_IN_MB
----------------
         480
Our current AMM uses the following memory
 - memory reserved  for PGA/SGA: 1600 MByte 
 - current PGA size 120 MB
 - current SGA size 904 MB
 - free memory for future PGA/SGA usage: ~ 600 MByte

For switching ASMM this can be translated into 
  SGA_MAX_SIZE             : 1400 MByte
  SGA_TARGET               : 1000 MByte
  PGA_AGGREGATE_TARGET     :  480 Mbyte

For further tuning check : V$PGA_TARGET_ADVICE

Execute the  following commands.
Disable AMM
  SQL> alter system reset memory_max_target scope=spfile  sid='*';
  SQL> alter system reset memory_target  scope=spfile  sid='*';

Enable ASMM
  SQL> alter system set SGA_MAX_SIZE=1400m scope=spfile  sid='*';
  SQL> alter system set SGA_TARGET=1000m scope=spfile  sid='*'; 
  SQL> alter system set PGA_AGGREGATE_TARGET=480m scope=spfile  sid='*';  

Reboot database and verify that we have switched from AMM to ASMM
SQL> show parameter memory
NAME                     TYPE     VALUE
------------------------------------ ----------- ------------------------------
memory_max_target             big integer 0
memory_target                 big integer 0
--> AMM disabled 

SQL> show parameter sga
NAME                     TYPE          VALUE
------------------------ ----------- ------------------------------
sga_max_size             big integer 1408M
sga_target               big integer 912M

SQL> show parameter pga
NAME                     TYPE     VALUE
------------------------ ----------- ------------------------------
pga_aggregate_target     big integer 480M

--> ASMM enabled !

 Review impact on OS resources after switchging for AMM to ASMM

The switch from AMM to ASMM frees space in /dev/shm but allocates shared memomry for the SGA
$ ipcs -m
------ Shared Memory Segments --------
key        shmid      owner      perms      bytes      nattch     status                             
0x00000000 3145746    oracle     640        16777216   41                      
0x00000000 3178515    oracle     640        1459617792 41                      
0xe1106fe8 3211284    oracle     640        2097152    41                      

$ df -h
Filesystem            Size  Used Avail Use% Mounted on
tmpfs                 2.0G  200M  1.9G  10% /dev/shm

Friday, 4 October 2019

Moving the LOB from one Tablespace to another Tablespace


As a part of changing the Bigfile Tablespace to normal Tablespace, :

Post activities considerations:

Check the size of LOB in the Tablespace which we are going to move.
check the count of objects using dba_lobs, dba_indexes, dba_tables with corresponding Tablespace.
Create the necessary tablespace and datafiles with sufficient space.
Change the default tablespace if needed to the new one.
Give quota to the user as unlimited for the created tablespace.
use the below script and generate the .sql file for the movement.

Moving LOB:

SQL> spool /home/oracle/movelob.sql

SET HEADING OFF
SET pagesize 200
SET linesize 200
select 'ALTER TABLE <owner>.'||TABLE_NAME||' MOVE LOB('||COLUMN_NAME||') STORE AS (TABLESPACE <Tablespace_name>) parallel 5 nologging;' from dba_lobs where TABLESPACE_NAME='<Tablespace_name>';
Note: The above query will include all the LOB,LOBSEGMENT,LOBINDEXES


Moving Table:

SQL> spool /home/oracle/moveTables.sql
SET HEADING OFF
SET PAGESIZE 200
SET LINESIZE 200
select ' ALTER TABLE <owner>.'||TABLE_NAME||' MOVE TABLESPACE <Tablespace_name>) parallel 5 nologging;' from dba_tables where owner='<owner name>';

Moving Index:

SQL> spool /home/oracle/moveIndex.sql

SET HEADING OFF
SET long 9999
SET linesize 200
select 'alter index <owner>.'||index_name||' from dba_indexes 'rebuild tablespace <Tablespace_name>)   online parallel 3 nologging;' where owner='<owner>.';


Run the queries and generate the sql scripts 
Make sure that there is no unwanted space in the sql script.
Move the Huge size LOB separately and the corresponding tables and indexes to make sure that huge volumes moves first.
Next move the Remaining LOB then Tables and Index correspondingly using the scripts.
Then check with the old tablespace if there are any objects left, if so move those to the new tablespace
Check the counts with previously taken counts if every this is fine ,then if needed drop the tablespace with the datafiles.
Have Your LOB in new tablespace :-)

Oracle 12c Multitenant Backup and Recovery


Single RMAN backup database command will backup the root container database as well as all the pluggable databases.
[oracle@db12c ~]$ rman  target /
Recovery Manager: Release 12.1.0.2.0 – Production on Tue Sep 6 10:05:37 2016
Copyright (c) 1982, 2014, Oracle and/or its affiliates.  All rights reserved.
connected to target database: DB12C (DBID=1373556589)
RMAN> backup database FORMAT '/rman_bak/%d_%T_%s_%p.BAK';
Starting backup at 06-SEP-16
using target database control file instead of recovery catalog
allocated channel: ORA_DISK_1
channel ORA_DISK_1: SID=388 device type=DISK
channel ORA_DISK_1: starting full datafile backup set
channel ORA_DISK_1: specifying datafile(s) in backup set
input datafile file number=00003 name=/u01/app/oracle/oradata/db12c/sysaux01.dbf
input datafile file number=00001 name=/u01/app/oracle/oradata/db12c/system01.dbf
input datafile file number=00004 name=/u01/app/oracle/oradata/db12c/undotbs01.dbf
input datafile file number=00006 name=/u01/app/oracle/oradata/db12c/users01.dbf
channel ORA_DISK_1: starting piece 1 at 06-SEP-16
channel ORA_DISK_1: finished piece 1 at 06-SEP-16
piece handle=/rman_bak/DB12C_20160906_2_1.BAK tag=TAG20160906T100637 comment=NONE
channel ORA_DISK_1: backup set complete, elapsed time: 00:00:26
channel ORA_DISK_1: starting full datafile backup set
channel ORA_DISK_1: specifying datafile(s) in backup set
input datafile file number=00009 name=/u01/app/oracle/oradata/db12c/prodb1/sysaux01.dbf
input datafile file number=00008 name=/u01/app/oracle/oradata/db12c/prodb1/system01.dbf
input datafile file number=00010 name=/u01/app/oracle/oradata/db12c/prodb1/prodb1_users01.dbf
channel ORA_DISK_1: starting piece 1 at 06-SEP-16
channel ORA_DISK_1: finished piece 1 at 06-SEP-16
piece handle=/rman_bak/DB12C_20160906_3_1.BAK tag=TAG20160906T100637 comment=NONE
channel ORA_DISK_1: backup set complete, elapsed time: 00:00:25
channel ORA_DISK_1: starting full datafile backup set
channel ORA_DISK_1: specifying datafile(s) in backup set
input datafile file number=00012 name=/u01/app/oracle/oradata/db12c/prodb2/sysaux01.dbf
input datafile file number=00011 name=/u01/app/oracle/oradata/db12c/prodb2/system01.dbf
input datafile file number=00013 name=/u01/app/oracle/oradata/db12c/prodb2/prodb2_users01.dbf
channel ORA_DISK_1: starting piece 1 at 06-SEP-16
channel ORA_DISK_1: finished piece 1 at 06-SEP-16
piece handle=/rman_bak/DB12C_20160906_4_1.BAK tag=TAG20160906T100637 comment=NONE
channel ORA_DISK_1: backup set complete, elapsed time: 00:00:07
channel ORA_DISK_1: starting full datafile backup set
channel ORA_DISK_1: specifying datafile(s) in backup set
input datafile file number=00007 name=/u01/app/oracle/oradata/db12c/pdbseed/sysaux01.dbf
input datafile file number=00005 name=/u01/app/oracle/oradata/db12c/pdbseed/system01.dbf
channel ORA_DISK_1: starting piece 1 at 06-SEP-16
channel ORA_DISK_1: finished piece 1 at 06-SEP-16
piece handle=/rman_bak/DB12C_20160906_5_1.BAK tag=TAG20160906T100637 comment=NONE
channel ORA_DISK_1: backup set complete, elapsed time: 00:00:15
Finished backup at 06-SEP-16
Starting Control File and SPFILE Autobackup at 06-SEP-16
piece handle=/u01/app/oracle/product/12.1.0/db_1/dbs/c-1373556589-20160906-00 comment=NONE
Finished Control File and SPFILE Autobackup at 06-SEP-16

Backups can also be performed at the pluggable database level.
RMAN> backup pluggable database prodb1 FORMAT '/rman_bak/%d_%T_%s_%p.BAK';
Starting backup at 06-SEP-16
using channel ORA_DISK_1
channel ORA_DISK_1: starting full datafile backup set
channel ORA_DISK_1: specifying datafile(s) in backup set
input datafile file number=00009 name=/u01/app/oracle/oradata/db12c/prodb1/sysaux01.dbf
input datafile file number=00008 name=/u01/app/oracle/oradata/db12c/prodb1/system01.dbf
input datafile file number=00010 name=/u01/app/oracle/oradata/db12c/prodb1/prodb1_users01.dbf
channel ORA_DISK_1: starting piece 1 at 06-SEP-16
channel ORA_DISK_1: finished piece 1 at 06-SEP-16
piece handle=/rman_bak/DB12C_20160906_11_1.BAK tag=TAG20160906T102038 comment=NONE
channel ORA_DISK_1: backup set complete, elapsed time: 00:00:07
Finished backup at 06-SEP-16
Starting Control File and SPFILE Autobackup at 06-SEP-16
piece handle=/u01/app/oracle/product/12.1.0/db_1/dbs/c-1373556589-20160906-03 comment=NONE
Finished Control File and SPFILE Autobackup at 06-SEP-16
RMAN> 
RMAN> backup pluggable database prodb2 FORMAT '/rman_bak/%d_%T_%s_%p.BAK';
Starting backup at 06-SEP-16
using channel ORA_DISK_1
channel ORA_DISK_1: starting full datafile backup set
channel ORA_DISK_1: specifying datafile(s) in backup set
input datafile file number=00012 name=/u01/app/oracle/oradata/db12c/prodb2/sysaux01.dbf
input datafile file number=00011 name=/u01/app/oracle/oradata/db12c/prodb2/system01.dbf
input datafile file number=00013 name=/u01/app/oracle/oradata/db12c/prodb2/prodb2_users01.dbf
channel ORA_DISK_1: starting piece 1 at 06-SEP-16
channel ORA_DISK_1: finished piece 1 at 06-SEP-16
piece handle=/rman_bak/DB12C_20160906_13_1.BAK tag=TAG20160906T102159 comment=NONE
channel ORA_DISK_1: backup set complete, elapsed time: 00:00:07
Finished backup at 06-SEP-16
Starting Control File and SPFILE Autobackup at 06-SEP-16
piece handle=/u01/app/oracle/product/12.1.0/db_1/dbs/c-1373556589-20160906-04 comment=NONE
Finished Control File and SPFILE Autobackup at 06-SEP-16

We can also use RMAN to connect to an individual pluggable database instead of the container database.
RMAN> list backup of database;
using target database control file instead of recovery catalog
List of Backup Sets
===================

BS Key  Type LV Size       Device Type Elapsed Time Completion Time
——- —- — ———- ———– ———— —————
16      Full    679.84M    DISK        00:00:07     06-SEP-16    
        BP Key: 16   Status: AVAILABLE  Compressed: NO  Tag: TAG20160906T102707
        Piece Name: /rman_bak/DB12C_20160906_16_1.BAK
  List of Datafiles in backup set 16
  File LV Type Ckp SCN    Ckp Time  Name
  —- — —- ———- ——— —-
  8       Full 2508046    06-SEP-16 /u01/app/oracle/oradata/db12c/prodb1/system01.dbf
  9       Full 2508046    06-SEP-16 /u01/app/oracle/oradata/db12c/prodb1/sysaux01.dbf
  10      Full 2508046    06-SEP-16 /u01/app/oracle/oradata/db12c/prodb1/prodb1_users01.dbf
RMAN> 
RMAN> list backup by file;

List of Datafile Backups
========================
File Key     TY LV S Ckp SCN    Ckp Time  #Pieces #Copies Compressed Tag
—- ——- –  – – ———- ——— ——- ——- ———- —
8    16      B  F  A 2508046    06-SEP-16 1       1       NO         TAG20160906T102707
9    16      B  F  A 2508046    06-SEP-16 1       1       NO         TAG20160906T102707
10   16      B  F  A 2508046    06-SEP-16 1       1       NO         TAG20160906T102707

Loss of Tempfile at pluggable database level.Temp file is automatically created when the pluggable database is closed and opened.
SQL> select name from v$tempfile;
NAME
——————————————————————————–
/u01/app/oracle/oradata/db12c/temp01.dbf
/u01/app/oracle/oradata/db12c/pdbseed/pdbseed_temp012016-08-10_05-31-03-PM.dbf
/u01/app/oracle/oradata/db12c/prodb1/temp012016-08-10_05-31-03-PM.dbf
/u01/app/oracle/oradata/db12c/prodb2/temp012016-08-10_05-31-03-PM.dbf
SQL> alter session set container=prodb1;
Session altered.
SQL> select name from v$tempfile;
NAME
——————————————————————————–
/u01/app/oracle/oradata/db12c/prodb1/temp012016-08-10_05-31-03-PM.dbf
SQL> !rm -rf /u01/app/oracle/oradata/db12c/prodb1/temp012016-08-10_05-31-03-PM.dbf 
SQL> !ls -l /u01/app/oracle/oradata/db12c/prodb1/temp012016-08-10_05-31-03-PM.dbf
ls: cannot access /u01/app/oracle/oradata/db12c/prodb1/temp012016-08-10_05-31-03-PM.dbf: No such file or directory
SQL> alter pluggable database prodb1 close immediate;
Pluggable database altered.
SQL> alter pluggable database prodb1 open read write;
Pluggable database altered.
SQL> select name from v$tempfile;
NAME
——————————————————————————–
/u01/app/oracle/oradata/db12c/prodb1/temp012016-08-10_05-31-03-PM.dbf
SQL> !ls -l /u01/app/oracle/oradata/db12c/prodb1/temp*
-rw-r—– 1 oracle oinstall 20979712 Sep  6 10:37 /u01/app/oracle/oradata/db12c/prodb1/temp012016-08-10_05-31-03-PM.dbf
SQL> show pdbs
    CON_ID CON_NAME                       OPEN MODE  RESTRICTED
———- —————————— ———- ———-
         3 PRODB1                         READ WRITE NO

Loss of Non-System data file at pluggable database level.
[oracle@db12c ~]$ sqlplus sys@prodb1 as sysdba
SQL*Plus: Release 12.1.0.2.0 Production on Tue Sep 6 10:46:17 2016
Copyright (c) 1982, 2014, Oracle.  All rights reserved.
Enter password: 
Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 – 64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real Application Testing options
SQL> select name from v$datafile;
NAME
——————————————————————————–
/u01/app/oracle/oradata/db12c/undotbs01.dbf
/u01/app/oracle/oradata/db12c/prodb1/system01.dbf
/u01/app/oracle/oradata/db12c/prodb1/sysaux01.dbf
/u01/app/oracle/oradata/db12c/prodb1/prodb1_users01.dbf
SQL> !rm -rf /u01/app/oracle/oradata/db12c/prodb1/sysaux01.dbf
SQL> !ls -l /u01/app/oracle/oradata/db12c/prodb1/sysaux01.dbf
ls: cannot access /u01/app/oracle/oradata/db12c/prodb1/sysaux01.dbf: No such file or directory
SQL> alter tablespace sysaux offline;
alter tablespace sysaux offline
*
ERROR at line 1:
ORA-01116: error in opening database file 9
ORA-01110: data file 9: '/u01/app/oracle/oradata/db12c/prodb1/sysaux01.dbf'
ORA-27041: unable to open file
Linux-x86_64 Error: 2: No such file or directory
Additional information: 3
SQL> shutdown immediate
Pluggable Database closed.
SQL> startup
ORA-01113: file 10 needs media recovery
ORA-01110: data file 10:
'/u01/app/oracle/oradata/db12c/prodb1/prodb1_users01.dbf'

SQL> conn / as sysdba
Connected.
SQL> show pdbs
    CON_ID CON_NAME                       OPEN MODE  RESTRICTED
———- —————————— ———- ———-
         2 PDB$SEED                       READ ONLY  NO
         3 PRODB1                         MOUNTED
         4 PRODB2                         READ WRITE NO

[oracle@db12c ~]$ rman target sys/oracle@prodb1
Recovery Manager: Release 12.1.0.2.0 – Production on Tue Sep 6 11:09:14 2016
Copyright (c) 1982, 2014, Oracle and/or its affiliates.  All rights reserved.
connected to target database: DB12C (DBID=1373556589, not open)
RMAN> select name from v$datafile;
using target database control file instead of recovery catalog

NAME                                                                          
——————————————————————————–
/u01/app/oracle/oradata/db12c/undotbs01.dbf
 
/u01/app/oracle/oradata/db12c/prodb1/system01.dbf
 
/u01/app/oracle/oradata/db12c/prodb1/sysaux01.dbf
 
/u01/app/oracle/oradata/db12c/prodb1/prodb1_users01.dbf
 
RMAN> restore tablespace sysaux;
Starting restore at 06-SEP-16
allocated channel: ORA_DISK_1
channel ORA_DISK_1: SID=773 device type=DISK
channel ORA_DISK_1: starting datafile backup set restore
channel ORA_DISK_1: specifying datafile(s) to restore from backup set
channel ORA_DISK_1: restoring datafile 00009 to /u01/app/oracle/oradata/db12c/prodb1/sysaux01.dbf
channel ORA_DISK_1: reading from backup piece /rman_bak/DB12C_20160906_16_1.BAK
channel ORA_DISK_1: piece handle=/rman_bak/DB12C_20160906_16_1.BAK tag=TAG20160906T102707
channel ORA_DISK_1: restored backup piece 1
channel ORA_DISK_1: restore complete, elapsed time: 00:00:07
Finished restore at 06-SEP-16
RMAN> recover tablespace sysaux;
Starting recover at 06-SEP-16
using channel ORA_DISK_1
starting media recovery
media recovery complete, elapsed time: 00:00:00
Finished recover at 06-SEP-16

[oracle@db12c ~]$ sqlplus sys/oracle@prodb1 as sysdba
SQL*Plus: Release 12.1.0.2.0 Production on Tue Sep 6 11:12:03 2016
Copyright (c) 1982, 2014, Oracle.  All rights reserved.

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 – 64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real Application Testing options
SQL> recover datafile 10;
Media recovery complete.
SQL> recover datafile 8;
Media recovery complete.
SQL> alter pluggable database prodb1 open read write;
Pluggable database altered.
SQL> alter tablespace sysaux online;
Tablespace altered.

SQL> show pdbs
    CON_ID CON_NAME                       OPEN MODE  RESTRICTED
———- —————————— ———- ———-
         3 PRODB1                         READ WRITE NO

Loss of SYSTEM tablespace datafile at pluggable database level.
The entire container database has to be shut down and mounted and pluggable database recovered.
SQL> !rm -rf /u01/app/oracle/oradata/db12c/prodb1/system01.dbf
SQL> !ls -l  /u01/app/oracle/oradata/db12c/prodb1/system01.dbf
ls: cannot access /u01/app/oracle/oradata/db12c/prodb1/system01.dbf: No such file or directory
SQL> alter session set container=prodb1;
Session altered.
SQL> shutdown abort
Pluggable Database closed.

To recover the pluggable database we need to connect to the container database, shutdown the container database (this will shutdown all other pluggable databases) , mount the container database and then recover the pluggable database.
[oracle@db12c ~]$ sqlplus / as sysdba
SQL*Plus: Release 12.1.0.2.0 Production on Tue Sep 6 13:26:26 2016
Copyright (c) 1982, 2014, Oracle.  All rights reserved.

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 – 64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real Application Testing options
SQL> show pdbs
    CON_ID CON_NAME                       OPEN MODE  RESTRICTED
———- —————————— ———- ———-
         2 PDB$SEED                       READ ONLY  NO
         3 PRODB1                         MOUNTED
         4 PRODB2                         READ WRITE NO
        
SQL> shutdown immediate
Database closed.
Database dismounted.
ORACLE instance shut down.
SQL> startup mount
ORACLE instance started.
Total System Global Area 3238002688 bytes
Fixed Size                  2929600 bytes
Variable Size            2046823488 bytes
Database Buffers         1174405120 bytes
Redo Buffers               13844480 bytes
Database mounted.

[oracle@db12c ~]$ rman target /
Recovery Manager: Release 12.1.0.2.0 – Production on Tue Sep 6 13:29:19 2016
Copyright (c) 1982, 2014, Oracle and/or its affiliates.  All rights reserved.
connected to target database: DB12C (DBID=1373556589, not open)
RMAN> restore tablespace prodb1:system;
Starting restore at 06-SEP-16
using target database control file instead of recovery catalog
allocated channel: ORA_DISK_1
channel ORA_DISK_1: SID=1144 device type=DISK
channel ORA_DISK_1: starting datafile backup set restore
channel ORA_DISK_1: specifying datafile(s) to restore from backup set
channel ORA_DISK_1: restoring datafile 00008 to /u01/app/oracle/oradata/db12c/prodb1/system01.dbf
channel ORA_DISK_1: reading from backup piece /rman_bak/DB12C_20160906_21_1.BAK
channel ORA_DISK_1: piece handle=/rman_bak/DB12C_20160906_21_1.BAK tag=TAG20160906T111604
channel ORA_DISK_1: restored backup piece 1
channel ORA_DISK_1: restore complete, elapsed time: 00:00:03
Finished restore at 06-SEP-16
RMAN> recover tablespace prodb1:system;
Starting recover at 06-SEP-16
using channel ORA_DISK_1
starting media recovery
media recovery complete, elapsed time: 00:00:00
Finished recover at 06-SEP-16
RMAN> alter database open;
Statement processed
RMAN> recover datafile 10;
Starting recover at 06-SEP-16
using channel ORA_DISK_1
starting media recovery
media recovery complete, elapsed time: 00:00:00
Finished recover at 06-SEP-16
RMAN> recover datafile 9;
Starting recover at 06-SEP-16
using channel ORA_DISK_1
starting media recovery
media recovery complete, elapsed time: 00:00:00
Finished recover at 06-SEP-16
RMAN> alter pluggable database all open read write;
Statement processed

Loss of SYSTEM data file at the Container database level.
Note:If we lose the container database SYSTEM datafile we cannot connect to any of the pluggable databases as well.
We have to shutdown abort the container database and then mount the container database and perform offline recovery of the SYSTEM tablespace.
SQL> !rm -rf /u01/app/oracle/oradata/db12c/system01.dbf
SQL> select count(*) from dba_objects;
select count(*) from dba_objects
                     *
ERROR at line 1:
ORA-01116: error in opening database file 1
ORA-01110: data file 1: '/u01/app/oracle/oradata/db12c/system01.dbf'
ORA-27041: unable to open file
Linux-x86_64 Error: 2: No such file or directory
Additional information: 3

SQL> alter session set container=prodb1;
Session altered.
SQL> alter session set container=prodb2;
Session altered.
SQL> alter session set container=CDB$ROOT;
Session altered.
SQL> show pdbs
    CON_ID CON_NAME                       OPEN MODE  RESTRICTED
———- —————————— ———- ———-
         2 PDB$SEED                       READ ONLY  NO
         3 PRODB1                         READ WRITE NO
         4 PRODB2                         READ WRITE NO
SQL> alter system flush buffer_cache;
System altered.
SQL> shutdown abort
ORACLE instance shut down.

[oracle@db12c ~]$ rman target /
Recovery Manager: Release 12.1.0.2.0 – Production on Tue Sep 6 13:59:16 2016
Copyright (c) 1982, 2014, Oracle and/or its affiliates.  All rights reserved.
connected to target database (not started)
RMAN> startup mount
Oracle instance started
database mounted
Total System Global Area    3238002688 bytes
Fixed Size                     2929600 bytes
Variable Size               2046823488 bytes
Database Buffers            1174405120 bytes
Redo Buffers                  13844480 bytes
RMAN> restore tablespace system;
Starting restore at 06-SEP-16
using target database control file instead of recovery catalog
allocated channel: ORA_DISK_1
channel ORA_DISK_1: SID=769 device type=DISK
channel ORA_DISK_1: starting datafile backup set restore
channel ORA_DISK_1: specifying datafile(s) to restore from backup set
channel ORA_DISK_1: restoring datafile 00001 to /u01/app/oracle/oradata/db12c/system01.dbf
channel ORA_DISK_1: reading from backup piece /rman_bak/DB12C_20160906_20_1.BAK
channel ORA_DISK_1: piece handle=/rman_bak/DB12C_20160906_20_1.BAK tag=TAG20160906T111604
channel ORA_DISK_1: restored backup piece 1
channel ORA_DISK_1: restore complete, elapsed time: 00:00:15
Finished restore at 06-SEP-16
RMAN> recover tablespace system;
Starting recover at 06-SEP-16
using channel ORA_DISK_1
starting media recovery
media recovery complete, elapsed time: 00:00:00
Finished recover at 06-SEP-16
RMAN> alter database open;
Statement processed
RMAN> alter pluggable database all open read write;
Statement processed

Featured post

Restircted session due to sync filed with ora-65177

Application is unable to connect the database due to restricted session. sql> show pdbs; SQL> show con_name CON_NAME -----------------...