All in One DBA Scripts PDF
All in One DBA Scripts PDF
ARUN KUMAR
All in one Oracle DBA Scripts
Copyright © 2019 by Arun Kumar
ACKNOWLEDGEMENT
Your comments encourage us to produce quality content, please take a second and say ‘Hi’ to
me and let me and my team know what you thought of the book … p.s. It would mean the world
to me if you send a quick email to me ;)
Email: [email protected]
Arun Kumar
TABLE OF CONTENTS
ASM
Get ASM disk info
Get ASM disk group details
Drop an ASM disk
Monitor ASM disk rebalance
Execute runcluvfy.sh for RAC precheck
Copy ASM file to remote ASM instance
Mount/dismount ASM disk groups
Drop ASM diskgroup
Clock Synchronization status in RAC
Create ASM disk in Linux using oracleasm
AUDITING
Enable auditing in database
Statements audited in oracle
Privileges Audited in database
Audit records of a user
Enable audit for sys operations
Enable pure unified auditing 12c
Unified audit policies present in db
View unified audit report
Create unified audit policy
Enable auditing for datapump jobs
Move aud$ table to new tablespace
Check encryption wallet status
CRSCTL & RAC
Enable/Disable autorestart of CRS
Find the cluster name in RAC
Stop and start CRS
Find OCR and VD location
Find the grid version
Manual backup of OCR and list backups
Move voting disk to new diskgroup
Get node info using olsnodes
Get interface info in RAC
DATABASE INFO
Get redo log member info
Get DDL of all tablespaces
Get DDL of all privileges granted to user
Get size of the database
View hidden parameter setting
Get ACL details in database
Archive generation per hour
Find active transactions in DB
Find who locked your account
Find duplicate rows in table
Database growth per month
Resize datafile without ORA-03297
Get database uptime
Scn to timestamp and viceversa
Disable/enable all triggers of schema
Ger row_count of all the tables of a schema
Spool SQL query output to HTML
Monitor index usage
Get installed SQL patches in DB
Cleanup orphaned datapump jobs
Get Alert log location in db
Installed RDBMS components
Character Set info of database
View/modify AWR retention
Find optimal undo retention size
Purge old AWR snapshots
Modify moving window size
Open database link information
Utilization of current redo log ( in % )
Generate multiple AWR report
Table not having index on FK column
Get CPU memory info of DB server
Get database incarnation info
View timezone info in DB
DATAGUARD MONITORING
Check DB role (PRIMARY/STANDBY)
Monitor standby background process
View dataguard message or errors
Last log applied/Received in standby
Get standby redo log info
Monitor lag in standby including RAC
Monitor recovery progress in standby DB
Stop/start MRP process in standby
DB MONITORING
Explain plan of sql_id from cursor
Explain plan of sql_id from AWR
Explain plan of a SQL statement
Explain plan of a SQL baseline
Get bind values of a sql_id
Flush a SQL query from cursor
Enable trace for a sql_id
10053 OPTIMIZER TRACE
Enable trace for a session
Execution detail of a sql_id in cursor
PGA usage by sessions
Segments with high physical read
I/O usage of each tempfile
Current SGA usage
Top running queries from ASH
Find blocking sessions from ASH
Top CPU consuming sessions
Sessions holding library cache lock
Objects locked by library cache
Sessions accessing an object
SQLs doing full table scan
Dictionary cache hit ratio
Op SQL queries using literal values
Objects causing flushing of shared pool
Queries causing high physical read
Mutex sleep in database
SQL tuning advisor for sql_id from cursor
Run SGA target advisory
Run shared pool advisory
Generate addm report
File current running SQLs
File active sessions in oracle database
Find waitevent in database
Find sessions generating undo
Find the temp usage of the sessions
Find sessions generating lot of redo
Script to monitor tablespaces usage
Scripts to monitor undo tablespaces usage
Script to monitor TEMP tablespaces usage
Find blocking sessions
Find long running operations
Find locks present in database
Find queries triggered from a procedure
Get sid from OS pid
Kill all sessions of a sql_id
Kill all session of a user
Get parallel query detail
Kill snipped session in DB
Top Query with high elapsed time
Monitor parallel queries
Find the locked objects
Check open cursors
Session login history from ASH
Buffer Cache hit ratio
Find top disk_reads by an user
Get OS pid from sid
Get active sid of a pl/sql object
Find buffer cache usage
Monitor rollback transactions
Find column usage statistics
Get background process details
Oracle DB is 32bit or 64 bit?
Oracle license usage info
DB optimizer processing rate
Purge recyclebin in database
EXPDP/IMPDP
EXPDP with compression parameter
EXPDP /IMPDP with parallel option
EXPDP /IMPDP for schemas
EXPDP /IMPDP for TABLES
EXPDP with query clause
SQL file option with IMPDP
TABLE_EXISTS_ACTION option with IMPDP
EXCLUDE/INCLUDE option in EXPDP
EXPDP to multiple directories
EXPDP to ASM diskgroup
CLUSTER PARAMETER IN RAC
FLASHBACK TECH
Flashback a table to point in time
Recover a dropped table
Flashback query as of timestamp
Enable flashback for database
Create/drop flashback restore point
Flashback db using restore point
Flashback a procedure/package
How far we can flashback
Flashback area usage info
Enable archivelog mode in standalone DM
List flashback restore points
MULTITENANT (CB PBD)
Status of PDBS in multitenant
Tablespace info in Multitenant
Temp tablespace details in Multitenant
Show History of PDBS
Currently connected PDB name
Stop and start pluggable DB
Drop a pluggable database
Check undo mode in Multitenant
Is the Database is a Multitenant or not
Services associated with PDBs
View container DB information
NETWORK MANAGEMENT
Enable tracing for a listener
Create/drop database link
Create DM link w/o modifying tnsnames.ora
Modify scan listener port
Create static listener for oracle DM
Manage listener in oracle
Manage ACLS in oracle
Find active services in DM
Set local_listener in DM
View ACL information in DM
OBJECT MANAGEMENT
Move LOB segment to another tablespace
Find tables with LOB seg in DB
Space usage by LOB column
ACTUAL SPACE USED BY LOB:
Find chained rows in table
Object with mix or lowercase name
Find nested tables in DB
Create/drop database link
Top index sizes of table/schema
Managing columns of table
Find column usage statistics
Estimate space required for index creation
Compile invalid objects
Enable/disable triggers of a schema
Find dependents of an object
Index rebuild in oracle
OEM/CLOUD CONTROL
Stop/start OMS in cloud control
Stop/start agent in OME cloud control
Get OMS repository details
Get OMS /agent URL details
Target list monitored by OEM
Plugins installed on OMS server
Change sysman pwd in OEM cloud
Enable/disable em express 12c
PARTITIONING
Adding partitions 11g/12c
Dropping partition 11g/12c
Truncate partitions
Merge partition
Make a partition ready only (12CR2)
Split partition online (12cR2 only)
Non-partition to partition
Rename a partition
Get row_count of partitions of a table
Find the table partition keys
Move partition to new tablespace
RMAN SCRIPTS
RMAN full db backup run block script
RMAN INCR DB backup run block
RMAN tablespace backup run block
RMAN datafile(s) backup run block
Delete archive older than 1 day
Backup archivelogs using RMAN
Copy archive from ASM to File system
Backup archive b/w 2 sequence
Enable trace for RMAN
Recover dropped table with RMAN 12c
Monitor RMAN an backup progress
Restore archivelog from rman tape
Enable block change tracking
Check the syntax of RMAN commands
SCHEDULER & JOBS
Manage dbms_schedulerjobs
Create and scheduler a scheduler job
Drop a schedule
Scheduler shell script in dbms_scheduler
Monitor scheduler jobs
All scheduler windows
View all scheduler schedules
History of all scheduler job runs
log information for all Scheduler jobs
Get DDL of a scheduler job
Scheduler job detail in CDB
Copy scheduler job from one user to other
Definition of job in dbms_jobs
Enable/disable/dop a dbms_job
SRVCTL Commands
Stop and start db using SRVCTL
Add/Remove db using SRVCTL
Add/remove instance using SRVCTL
Stop and start instance using SRVCTL
Enable/disable db/instance using SRVCTL
Relocate a service
Add/remove a service
Stop/Start a service
Manage MGMTDB in 12c RAC
Set env variables using srvctl3
Enable trace for SRVCTL commands
STATISTICS
Gather stats for schema
Gather stats for a table
Lock/unlock statistics
Export import statistics
Check stale stats
Table statistics history
Publish Pending stats
Get statistics preference setting
View/modify stats retention in DB
Space used to store stats
Enable incremental stats collection
Delete statistics
Upgrade statistics in DB
TABLESPACE & DATA FILE
Create tablespace in oracle DB
Rename tablespace in oracle DB
Drop tablespace in oracle DB
Add/alter data file
Add/alter Temp file
Rename/move a data file
Checkpoint time of data files
Occupants usage in sysaux tablespace
USER MANAGEMENT
Create user in oracle
Alter an user
Change default tablespace of user
Tablespace quota for a user
View Privileges granted to a user
Grant table/column privilege to user
Connect to user without knowing password
Common user/role in CDB
User creation details in user$ table
Create /alter profile in database
Default users in oracle 12c
ASM
Get ASM disk info
set pagesize 2000
set lines 2000
set long 999
col path for a54
select name, path, header_status, total_mb free_mb, trunc(bytes_read/1024/1024) read_mb, trunc(bytes_written/1024/1024)
write_mb from v$asm_disk;
asm_power_limit integer 1
-- Check for ongoing rebalance operations and their power.
select INST_ID,GROUP_NUMBER, OPERATION, STATE, POWER, EST_RATE, EST_MINUTES from
GV$ASM_OPERATION;
- Alter the asm rebalance.
alter diskgroup SALDATA rebalance power 4;
Flashback a procedure/package
--- Like, tables ,If you have dropped or recreated a package/procedure, by using flashback ,we can get the proc code, before
drop.
-- get the object_id
SQL> select object_id from dba_objects where owner='DBACLASS' and object_name='VOL_DISCOUNT_INSERT';
OBJECT_ID
----------
2201943
-- Now get the flashback code using timestamp
select SOURCE from sys.source$ as of timestamp
to_timestamp('23-Apr-2017 10:00:20','DD-Mon-YYYY hh24:MI:SS')
where obj#=2201943 ;
Set local_listener in DM
-- Make the sure the a listener is already running with that port(i.e 1524 here)
alter system set LOCAL_LISTENER='(ADDRESS = (PROTOCOL = TCP)(HOST = 162.20.217.15)(PORT = 1524))'
scope=both;
alter system register;
select type, value from v$listener_network where TYPE='LOCAL LISTENER';
Truncate partitions
- SYNTAX : ALTER TABLE <SCHEMA_NAME>.<TABLE_NAME> TRUNCATE PARTITION <
PARTITION_NAME> < UPDATE GLOBAL INDEXES(optional)>;
--- NOTE: UPDATE GLOBAL INDEXES is required if GLOBAL INDEX is present
ALTER TABLE CMADMIN.DBACLASS TRUNCATE PARTITION DBACLASS_JAN UPDATE GLOBAL INDEXES;
--- In oracle 12c, we can truncate multiple partitions in one command
ALTER TABLE CMADMIN.DBACLASS TRUNCATE PARTITIONS DBACLASS_JAN, DBACLASS_FEB,
DBACLASS_MAR UPDATE GLOBAL INDEXES;
Merge partition
-- MERGE PARTITION - FOR COMBINING MULTIPLE PARTITIONS TO A NEW ONE ( 12C ONWARS)
-- SYNTAX : ALTER TABLE <SCHEMA_NAME>.<TABLE_NAME> MERGE PARTITIONS <
PARTITION1,PARTITION2,...> < UPDATE GLOBAL INDEXES(optional)>;
--- NOTE: UPDATE GLOBAL INDEXES is required if GLOBAL INDEX is present
ALTER TABLE CMADMIN.DBACLASS MERGE PARTITIONS DBACLASS_JAN, DBACLASS_FEB,
DBACLASS_MAR INTO partition DBACLASS_Q1;
Non-partition to partition
-- In Oracle 12cR2, we can convert non partitioned table to partitioned online using alter table command.
alter table BSSTDBA.ORDER_TAB modify
PARTITION BY RANGE (CREATED)
(partition created_2105_p8 VALUES LESS THAN (TO_DATE('01/09/2015', 'DD/MM/YYYY')),
partition created_2105_p9 VALUES LESS THAN (TO_DATE('01/10/2015', 'DD/MM/YYYY')),
partition created_2105_p10 VALUES LESS THAN (TO_DATE('01/11/2015', 'DD/MM/YYYY')),
partition created_2105_p11 VALUES LESS THAN (TO_DATE('01/12/2015', 'DD/MM/YYYY')),
partition created_2105_p12 VALUES LESS THAN (TO_DATE('01/01/2016', 'DD/MM/YYYY')),
PARTITION Created_MX VALUES LESS THAN (MAXVALUE)) ONLINE;
Rename a partition
ALTER TABLE employee RENAME PARTITION TAB3 TO TAB4;
Drop a schedule
BEGIN
DBMS_SCHEDULER.DROP_SCHEDULE(
schedule_name => 'DAILYBILLINGJOB_SCHED',
force => TRUE
);
END;
Scheduler shell script in dbms_scheduler
-- This feature in available from oracle 12c onward
-- Create an credential store:
BEGIN
dbms_credential.create_credential (
CREDENTIAL_NAME => 'ORACLEOSUSER',
USERNAME => 'oracle',
PASSWORD => 'oracle@98765',
DATABASE_ROLE => NULL,
WINDOWS_DOMAIN => NULL,
COMMENTS => 'Oracle OS User',
ENABLED => true
);
END;
/
-- Create the job:
exec dbms_scheduler.create_job(-
job_name=>'myscript4',-
job_type=>'external_script',-
job_action=>'/export/home/oracle/ttest.2.sh',-
enabled=>true,-
START_DATE=>sysdate,-
REPEAT_INTERVAL =>'FREQ=MINUTELY; byminute=1',-
auto_drop=>false,-
credential_name=>'ORACLEOSUSER');
Enable/disable/dop a dbms_job
-- Get the job number from dba_jobs.
select job "jobno",schema_user,what from dba_jobs;
-- Disable a job
EXEC DBMS_IJOB.BROKEN(jobno,TRUE);
-- Enable a job
EXEC DBMS_IJOB.BROKEN(jobno,FALSE);
-- REMOVE A DBMS_JOBS:
EXEC DBMS_IJOB.remove(jobno) ;
SRVCTL Commands
Stop and start db using SRVCTL
-- SYNTAX FOR STOP DB
--- srvctl stop database -d db_name [-o stop_options] where stop_options is normal/immediate(default)/transactional/abort
e.g
srvctl stop database -d PRODB -o normal
srvctl stop database -d PRODB -o immediate
srvctl stop database -d PRODB -o transactional
srvctl stop database -d PRODB -o abort
-- SYNTAX FOR START DB
-- srvctl start database -d db_name [-o start_options] where start_option is nomount/mount/open(default)
e.g
srvctl start database -d PRODB -o nomount
srvctl start database -d PRODB -o mount
srvctl start database -d PRODB -o open
Relocate a service
SYNTAX -
srvctl relocate service -d {database_name} -s {service_name} -i {old_inst_name} -r {new_inst_name}
EXAMPLE:(Relocating service PRDB_SRV from PREDB2 to PREDB1)
srvctl relocate service -d PREDB -s PRDB_SVC -i PREDB2 -t PREDB1
-- Check the status of service
srvctl status service -d PREDB -s PRDB_SVC
Add/remove a service
ADDING A SERVICE:
-------------------------------------------
SYNTAX:
------------
srvctl add servicec -d {DB_NAME} -s {SERVICE_NAME} -r {"preferred_list"} -a {"available_list"} [-P {BASIC | NONE
| PRECONNECT}]
EXAMPLE:
---------------
srvctl add service -d PREDB -s PRDB_SRV -r "PREDB1,PREDB2" -a "PREDB2" -P BASIC
REMOVING A SERVICE:
------------------------------------------
SYNTAX:
-------------
srvctl remove service -d {DB_NAME} -s {SERVICE_NAME}
EXAMPLE:
--------
srvctl remove service -d PREDB -s PRDB_SRV
Stop/Start a service
SYNTAX
srvctl start servicec -d {DB_NAME} -s {SERVICE_NAME}
srvctl stop servicec -d {DB_NAME} -s {SERVICE_NAME}
EXAMPLE:
---------------
srvctl start service -d PREDB -s PRDB_SRV
srvctl stop service -d PREDB -s PRDB_SRV
Lock/unlock statistics
--- Lock statistics
EXEC DBMS_STATS.lock_schema_stats('SCOTT');
EXEC DBMS_STATS.lock_table_stats('SCOTT', 'TEST');
EXEC DBMS_STATS.lock_partition_stats('SCOTT', 'TEST', 'TEST_JAN2016');
-- Unlock statistics
EXEC DBMS_STATS.unlock_schema_stats('SCOTT');
EXEC DBMS_STATS.unlock_table_stats('SCOTT', 'TEST');
EXEC DBMS_STATS.unlock_partition_stats('SCOTT', 'TEST', 'TEST_JAN2016');
--- check stats status:
SELECT stattype_locked FROM dba_tab_statistics WHERE table_name = 'TEST' and owner = 'SCOTT';
Delete statistics
-- Delete statistics of the complete database
EXEC DBMS_STATS.delete_database_stats;
-- Delete statistics of a single schema
EXEC DBMS_STATS.delete_schema_stats('DBACLASS');
-- Delete statistics of single tabale
EXEC DBMS_STATS.delete_table_stats('DBACLASS', 'DEPT');
-- Delete statistics of a column
EXEC DBMS_STATS.delete_column_stats('DBACLASS', 'DEPT', 'CLASS');
--Delete statistics of an index
EXEC DBMS_STATS.delete_index_stats('DBACLASS', 'CLASS_IDX');
--Delete dictionary statistics in db
EXEC DBMS_STATS.delete_dictionary_stats;
Upgrade statistics in DB
-- If we are importing stats table from higher version to lower version,
then before importing in the database, we need to upgrade the stats table.
EXECUTE DBMS_STATS.UPGRADE_STAT_TABLE(OWNNAME =>'RAJ',STATTAB =>'STAT_TEST');
TABLESPACE & DATA FILE
Create tablespace in oracle DB
-- Create New tablespace
Create tablespace DATA datafile '/u01/dbaclass/oradata/data01.dbf' size 5G autoextend on next 500M;
-- Create tablespace on ASM diskgroup
Create tablespace DATA datafile '+DATAG' size 5G autoextend on next 500M;
-- Create big tablespace:
CREATE BIGFILE TABLESPACE BIGTS datafile '/u01/dbaclass/oradata/bigts01.dbf' size 100G autoextend on NEXT 1G;
Alter an user
-- Change password of an user
ALTER USER SCOTT identified by NEW_PWD;
-- Change user profile;
ALTER USER SCOTT PROFILE SIEBEL_PROFILE;
-- Unlock/lock a user
ALTER USER SCOTT account unlock;
ALTER USER SCOTT account lock;
-- Make sure account expiry, so upon login, it will ask for new one
ALTER USER SCOTT password expire;
Email: [email protected]
DBA Genesis is currently the fastest & the most engaging learning platforms for DBAs across
the globe. Take your database administration skills to next level by enrolling into your first
course.
Facebook: https://www.facebook.com/dbagenesis/
Instagram: https://www.instagram.com/dbagenesis/
Twitter: https://twitter.com/DbaGenesis
Website: https://dbagenesis.com/
Contact us: https://dbagenesis.com/p/contact
All the best and goodbye for now!
Arun Kumar