Sunday 15 November 2015

Oracle DBA Interview Questions and Answers - Architecture

Oracle DBA Interview Questions and Answers - Architecture:
=================================================

1.) 11G Backgroung Processes?

The following process are added in 11g as new background processes.
1 dbrm DB resource manager 
2 dia0 Diagnosability process 
3 fbda Flashback data archiver process 
4 vktm Virtual Timekeeper 
5 w000 Space Management Co-ordination process 
6 smc0 Space Manager process 
NOTE : The above six are mandatory processes.
But 11g has 56 new processes added which can be queried using

If any one of these 6 mandatory background processes is killed/not running, the instance will be aborted ?

Background processes are started automatically when the instance is started.
Mandatory background processes are DBWn, LGWR, CKPT, SMON, PMON, and RECO. All other processes are optional, will be invoked if that particular feature is activated.
If any one of these 6 mandatory background processes is killed/not running, the instance will be aborted.
Any issues related to backgroud processes should be monitored and analyzed from the trace files generated and the alert log.

How to check the database status at os level ?.

$ ps -ef|grep pmon

How to check the listener status at os level?.

$ ps -ef|grep tnslsnr

How to check the oratab?

$cat /etc/oratab <Linux>

$ cat /var/opt/oracle/oratab <Solaries>


2). Literal Vs. Bind Variables?

Select * from emp where dept=10; what level should i configure for better performance Where Clause .... Literal or Bind Variables? Expalin?

3). What is a Baseline?

Incarnation? Explain in detail? Where the incarnation information will be stored? 

4). Hard Parse Vs. Soft Parse?

5). What is SGA_TARGET and SGA_MAX_SIZE ?

SGA_MAX_SIZE is the largest amount of memory that will be available for the SGA in the instance and it will be allocated from memory. You do not have to use it all, but it will be potentially wasted if you set it too high and don't use it. It is not a dynamic parameter. Basically it gives you room for the Oracle instance to grow.
SGA_TARGET is actual memory in use by the current SGA. This parameter is dynamic and can be increased up to the value of SGA_MAX_SIZE.
SGA_MAX_SIZE and SGA_TARGET both are the parameter are used to change the SGA SIZE.
SGA_MAX_SIZE sets the maximum value for sga_target.
SGA_TAGET is 10G feature used to change the sga size dynamically .it specifies the total amount of SGA memory available to an instance.
this feature is called Automatic Shared Memory Management. With ASMM, the parameters java_pool_size, shared_pool_size, large_pool_size and db_cache_size are affected. 

SGA_MAX_SIZE & SGA_TARGET:

http://maxwellmiranda.wordpress.com/2009/09/17/sga_max_size-sga_targe/
SGA_MAX_SIZE sets the overall amount of memory the SGA can consume but is not dynamic.
The SGA_MAX_SIZE parameter is the max allowable size to resize the SGA Memory area parameters. If the SGA_TARGET is set to some value then the Automatic Shared Memory Management (ASMM) is enabled, the SGA_TARGET value can be adjusted up to the SGA_MAX_SIZE parameter, not more than SGA_MAX_SIZE parameter value.
I.e. If SGA_MAX_SIZE=4GB and SGA_TARGET=2GB, later period of time, if you want you can resize your SGA_TARGET parameter to the value of SGA_MAX_SIZE i.e. 4GB, you can’t resize the SGA_TARGET value to more than 4GB.
It is significant that SGA_TARGET includes the entire memory for the SGA, in contrast to earlier releases in which memory for the internal and fixed SGA was added to the sum of the configured SGA memory parameters. Thus, SGA_TARGET gives you precise control over the size of the shared memory region allocated by the database. If SGA_TARGET is set to a value greater than SGA_MAX_SIZE at startup, then the latter is bumped up to accommodate SGA_TARGET
Do not dynamically set or unset the SGA_TARGET parameter. This should be set only at startup.
SGA_TARGET is a database initialization parameter (introduced in Oracle 10g) that can be used for automatic SGA memory sizing.
SGA_TARGET provides the following:

  Single parameter for total SGA size 
  Automatically sizes SGA components
 Memory is transferred to where most needed
 Uses workload information 
 Uses internal advisory predictions 
 STATISTICS_LEVEL must be set to TYPICAL 
 SGA_TARGET is dynamic 
 Can be increased till SGA_MAX_SIZE
 Can be reduced till some component reaches minimum size
 Change in value of SGA_TARGET affects only automatically sized components

6). If I keep SGA_TARGET =0 then what will happen ?

Disable automatic SGA tuning by setting sga_target=0
Disable ASMM by setting SGA_TARGET=0
http://www.orafaq.com/wiki/SGA_target
SGA_TARGET is a database initialization parameter (introduced in Oracle 10g) that can be used for automatic SGA memory sizing.
Default value     0 (SGA auto tuning is disabled)
What happens when you run ALTER DATABASE OPEN RESETLOGS ?
The current online redo logs are archived, the log sequence number is reset to 1, new database incarnation is created, and the online redo logs are given a new time stamp and SCN.
The reason to do the open the database with the resetlogs is that after doing an incomplete recovery , the data files and control files still don't come to the same point of the redo log files. And as long as the database is not consistent within all the three file-data, redo and control, you can't open the database. The resetlogs clause would reset the log sequence numbers within the log files and would start them from 0 thus enabling you to open the database but on the cost of losing all what was there in the redo log files. 

7). In what scenarios open resetlogs required ?

An ALTER DATABASE OPEN RESETLOGS statement is required,
1.after incomplete recovery (Point in Time Recovery) or
2.recovery with a backup control file.
3. recovery with a control file recreated with the reset logs option.
http://onlineappsdba.com/index.php/2009/09/11/oracle-database-incarnation-open-resetlogs-scn/
http://web.njit.edu/info/limpid/DOC/backup.102/b14191/osrecov009.htm
Whenever you perform incomplete recovery or recovery with a backup control file, you must reset the online logs when you open the database. The new version of the reset database is called a new incarnation..


8) .Difference between RESETLOGS and NORESETLOGS ?

http://oracleappstechnology.blogspot.in/2008/05/difference-between-resetlogs-and.html

After recover database operation, open the database with: ALTER DATABASE OPEN [NO]RESETLOGS
NORESETLOGS:
The NORESETLOGS option does not clear the redo log files during startup and the online redo logs to be used for recovery. Only used in scenario where MANUAL RECOVERY is started, CANCEL is used, and then RECOVER DATABASE is started.

RESETLOGS:
CAUTION: Never use RESETLOGS unless necessary.
Once RESETLOGS is used then the redo log files cannot be used and any completed transactions in those redo logs are lost!!
Before using the RESETLOGS option take an offline backup of the database.

9) .What is SCN (System Change Number) ?

The system change number (SCN) is an ever-increasing value that uniquely identifies a committed version of the database at a point in time. Every time a user commits a transaction Oracle records a new SCN in redo logs.
Oracle uses SCNs in control files datafile headers and redo records. Every redo log file has both a log sequence number and low and high SCN. The low SCN records the lowest SCN recorded in the log file while the high SCN records the highest SCN in the log file.

10).What is Database Incarnation ?

Database incarnation is effectively a new “version” of the database that happens when you reset the online redo logs using “alter database open resetlogs;”.
Database incarnation falls into following category Current, Parent, Ancestor and Sibling
i) Current Incarnation : The database incarnation in which the database is currently generating redo.
ii) Parent Incarnation : The database incarnation from which the current incarnation branched following an OPEN RESETLOGS operation.
iii) Ancestor Incarnation : The parent of the parent incarnation is an ancestor incarnation. Any parent of an ancestor incarnation is also an ancestor incarnation.
iv) Sibling Incarnation : Two incarnations that share a common ancestor are sibling incarnations if neither one is an ancestor of the other.

11). How to view Database Incarnation history of Database ?

Using SQL> select * from v$database_incarnation;
Using RMAN>LIST INCARNATION;
However, you can use the RESET DATABASE TO INCARNATION command to specify that SCNs are to be interpreted in the frame of reference of another incarnation.
•For example my current database INCARNATION is 3 and now I have used
FLASHBACK DATABASE TO SCN 3000;then SCN 3000 will be search in current incarnation which is 3. However if I want to get back to SCN 3000 of INCARNATION 2 then I have to use,
RMAN> RESET DATABASE TO INCARNATION 2;
RMAN> RECOVER DATABASE TO SCN 3000;

12). What is difference between oracle SID and Oracle service name?

Oracle SID is the unique name that uniquely identifies your instance/database where as the service name is the TNS alias can be same or different as SID.

What are the steps to install oracle on Linux system? List two kernel parameter that effect oracle installation?

Initially set up disks and kernel parameters, then create oracle user and DBA group, and finally run installer to start the installation process. The SHMMAX & SHMMNI two kernel parameter required to set before installation process.

13).What are bind variables?

With bind variable in SQL, oracle can cache queries in a single time in the SQL cache area. This avoids a hard parse each time, which saves on various locking and latching resource we use to check object existence and so on.

14).What is the difference between data block/extent/segment?

A data block is the smallest unit of logical storage for a database object. As objects grow they take chunks of additional storage that are composed of contiguous data blocks. These groupings of contiguous data blocks are called extents. All the extents that an object takes when grouped together are considered the segment of the database object.

15). What is the difference between PGA and UGA?

When you are running dedicated server then process information stored inside the process global area (PGA) and when you are using shared server then the process information stored inside user global area (UGA).

16).What is SGA? Define structure of shared pool component of SGA?

The system global area is a group of shared memory area that is dedicated to oracle instance. All oracle process uses the SGA to hold information. The SGA is used to store incoming data and internal control information that is needed by the database. You can control the SGA memory by setting the parameter db_cache_size, shared_pool_size and log_buffer.
Shared pool portion contain three major area: 
Library cache (parse SQL statement, cursor information and execution plan), 
data dictionary cache (contain cache, user account information, privilege user information, segments and extent information, 
data buffer cache for parallel execution message and control structure.

17).What is the difference between SMON and PMON processes?

SMON (System Monitor) performs recovery after instance failure, monitor temporary segments and extents; clean temp segment, coalesce free space. It is mandatory process of DB and starts by default.
PMON (Process Monitor) failed process resources. In shared server architecture monitor and restarts any failed dispatcher or server process. It is mandatory process of DB and starts by default.

What is a system change number (SCN)?SCN is a value that is incremented whenever a dirty read occurs.

SCN is incremented whenever a deadlock occurs.
SCN is a value that keeps track of explicit locks.
SCN is a value that is incremented whenever database changes are made.

What is the main purpose of ‘CHECKPOINT’ in oracle database? How do you automatically force the oracle to perform a checkpoint?

 A checkpoint is a database event, which synchronize the database blocks in memory with the datafiles on disk. It has two main purposes: To establish a data consistency and enable faster database Recovery.

The following are the parameter that will be used by DBA to adjust time or interval of how frequently its checkpoint should occur in database.
LOG_CHECKPOINT_TIMEOUT = 3600;  # Every one hour
LOG_CHECKPOINT_INTERVAL = 1000; # number of OS blocks.

18). What happens when we fire SQL statement in Oracle?

First it will check the syntax and semantics in library cache, after that it will create execution plan. 
If already data is in buffer cache it will directly return to the client. 
If not it will fetch the data from datafiles and write to the database buffer cache after that it will send server and finally server send to the client.

19). What is the use of large pool, which case you need to set the large pool?


You need to set large pool if you are using: MTS (Multi thread server) and RMAN Backups. Large pool prevents RMAN & MTS from competing with other sub system for the same memory. RMAN uses the large pool for backup & restore when you set the DBWR_IO_SLAVES or BACKUP_TAPE_IO_SLAVES parameters to simulate asynchronous I/O. If neither of these parameters is enabled, then Oracle allocates backup buffers from local process memory rather than shared memory. Then there is no use of large pool.

20). What does database do during the mounting process?

While mounting the database oracle reads the data from controlfile which is used for verifying physical database files during sanity check. Background processes are started before mounting the database only.

21). What are logfile states?

“CURRENT” state means that redo records are currently being written to that group. It will be until a log switch occurs. At a time there can be only one redo group current.
If a redo group containing redo’s of a dirty buffer that redo group is said to be ‘ACTIVE’ state. As we know log file keep changes made to the data blocks then data blocks are modified in buffer cache (dirty blocks). These dirty blocks must be written to the disk (RAM to permanent media).
And when a redolog group contains no redo records belonging to a dirty buffer it is in an "INACTIVE" state. These inactive redolog can be overwritten.
One more state ‘UNUSED’ initially when you create new redo log group its log file is empty on that time it is unused. Later it can be any of the above mentioned state.

22). What is log switch?

The point at which oracle ends writing to one online redo log file and begins writing to another is called a log switch. Sometimes you can force the log switch.
ALTER SYSTEM SWITCH LOGFILE;
How to check Oracle database version?
SQL> Select * from v$version;

23). Explain Oracle Architecture?

Oracle Instance:
a means to access an Oracle database,always opens one and only one database and consists of memory structures and background process.
Oracle server:
a DBMS that provides an open, comprehensive, integrated approach to information management,Consists of an Instance and a database.
Oracle database:
a collection of data that is treated as a unit,Consists of Datafiles, Control files, Redo log files. (optional param file, passwd file, archived log)

Instance memory Structures:
-------------------------------- System Global Area (SGA):

Allocated at instance startup, and is a fundamental component of an Oracle Instance.

SGA Memory structures:

----------------------------- Includes Shared Pool,  Database Buffer Cache, Redo Log Buffer among others.

Shared Pool :

--------------- Consists of two key performance-related memory structures Library Cache and  Data Dictionary Cache.

Library Cache:
----------------------- Stores information about the most recently used SQL and PL/SQL statements and enables the sharing of commonly used statements.

Data Dictionary Cache :
--------------------------------- Stores collection of the most recently used definitions in the database Includes db files, tables, indexes, columns etc. Improves perf. During the parse phase, the server process looks at the data dictionary for information to resolve object names and validate access.

Database Buffer Cache:
------------------------------- Stores copies of data blocks that have been retrieved from the datafiles. Everything done here.

Redo Log Buffer :
---------------------------- Records all changes made to the database data blocks, Primary purpose is recovery. Redo entries contain information to reconstruct or redo changes.

User process:
---------------------- Started at the time a database User requests connection to the Oracle server. requests interaction with the Oracle server, does not interact directly with the Oracle server.

Server process:
---------------------- Connects to the Oracle Instance and is Started when a user establishes a session.
fulfills calls generated and returns results.
Each server process has its own nonshared PGA when the process is started.
Server Process Parses and run SQL statements issued through the application, Reads necessary data blocks from datafiles on disk into the shared database buffers of the SGA, if the blocks are not already present in the SGA and Return results in such a way that the application can process the information.
In some situations when the application and Oracle Database operate on the same computer, it is possible to combine the user process and corresponding server process into a single process to reduce system overhead.

Program Global Area (PGA):  
---------------------------------- Memory area used by a single Oracle server process.
Allocated when the server process is started, deallocated when the process is terminated and used by only one process.
Used to process SQL statements and to hold logon and other session information.

Background processes: 
------------------------------ Started when an Oracle Instance is started.
Background Processes Maintains and enforces relationships between physical and memory structures
There are two types of database processes:
      1.      Mandatory background processes
      2.      Optional background processes

Mandatory background processes:
--------------------------------------------- – DBWn, PMON, CKPT,  LGWR,  SMON

Optional background processes:
----------------------------------------- – ARCn, LMDn, RECO, CJQ0, LMON, Snnn, Dnnn, Pnnn, LCKn, QMNn

DBWn writes when:
-----------------------
• Checkpoint occurs
• Dirty buffers reach threshold
• There are no free buffers
• Timeout occurs
• RAC ping request is made
• Tablespace OFFLINE
• Tablespace READ ONLY
• Table DROP or TRUNCATE
• Tablespace BEGIN BACKUP

Log Writer (LGWR) writes:
• At commit
• When 1/3rd full
• When there is 1 MB of redo
• Every 3 seconds
• Before DBWn writes

System Monitor (SMON) Responsibilities:

• Instance recovery
– Rolls forward changes in redo logs
– Opens database for user access
– Rolls back uncommitted transactions
• Coalesces free space
• Deallocates temporary segments.

Process Monitor (PMON) Cleans up after failed processes by:

• Rolling back the transaction
• Releasing locks
• Releasing other resources
• Restarting dead dispatchers

Checkpoint (CKPT) Responsible for:

• Signaling DBWn at checkpoints
• Updating datafile headers with checkpoint information
• Updating control files with checkpoint information

Archiver (ARCn):

• Optional background process
• Automatically archives online redo logs when ARCHIVELOG mode is set
• Preserves the record of all changes made to the database

24). Why do you run orainstRoot and ROOT.SH once you finalize the Installation?

orainstRoot.sh needs to be run to change the Permissions and groupname to 770 and to dba.
Root.sh (ORACLE_HOME) location needs to be run to create a ORATAB in /etc/oratab or /opt/var/oratab in Solaris and to copy dbhome, oraenv and coraenv to /usr/local/bin.
orainstRoot.sh
[root@oracle11g ~]# /u01/app/oraInventory/orainstRoot.sh
Changing permissions of /u01/app/oraInventory to 770.
Changing groupname of /u01/app/oraInventory to dba.
The execution of the script is complete
root.sh
[root@oracle11g ~]# /u01/app/oracle/product/11.1.0/db_1/root.sh
Running Oracle 11g root.sh script...
The following environment variables are set as:
ORACLE_OWNER= oracle
ORACLE_HOME= /u01/app/oracle/product/11.1.0/db_1
Enter the full pathname of the local bin directory: [/usr/local/bin]:
Copying dbhome to /usr/local/bin ...
Copying oraenv to /usr/local/bin ...
Copying coraenv to /usr/local/bin ...
Creating /etc/oratab file...
Entries will be added to the /etc/oratab file as needed by
Database Configuration Assistant when a database is created
Finished running generic part of root.sh script.
Now product-specific root actions will be performed.
Finished product-specific root actions.
For Oracle installation on unix/linux, we will be prompted to run a script 'root.sh' from the oracle inventory directory.this script needs to run the first time only when any oracle product is installed on the server. 
It creates the additional directories and sets appropriate ownership and permissions on files for root user.


25). Oracle Database 11g New Feature for DBAs?

1) Automatic Diagnostic Repository [ADR]
2) Database Replay
3) Automatic Memory Tuning
4) Case sensitive password
5) Virtual columns and indexes
6) Interval Partition and System Partition
7) The Result Cache
8) ADDM RAC Enhancements
9) SQL Plan Management and SQL Plan Baselines
10) SQL Access Advisor & Partition Advisor
11) SQL Query Repair Advisor
12) SQL Performance Analyzer (SPA) New
13) DBMS_STATS Enhancements
14) The Result Cache
15) Total Recall (Flashback Data Archive)
Note: The above are only top new features, there are other features as well introduced in 11g which will be included subsequently

26). What is the Difference Between Local Inventory and Global Inventory?

What is oraInventory ?

oraInventory is repository (directory) which store/records oracle software products & their oracle_homes location on a machine. This Inventory now a days in XML format and called as XML Inventory where as in past it used to be in binary format & called as binary Inventory.
There are basically two kind of inventories,
One is Local Inventory (also called as Oracle Home Inventory) and other is  Global Inventory (also called as Central Inventory).

What is Global Inventory ?

Global Inventory holds information about Oracle Products on a Machine. These products can be various oracle components like database, oracle application server, collaboration suite, soa suite, forms & reports or discoverer server . This global Inventory location will be determined by file oraInst.loc in /etc (on Linux) or /var/opt/oracle (solaris). If you want to see list of oracle products on machine check for file inventory.xml under ContentsXML in oraInventory Please note if you have multiple global Inventory on machine check all oraInventory directories)
You will see entry like
HOME NAME=”ORA10g_HOME” LOC=”/u01/oracle/10.2.0/db” TYPE=”O” IDX=”1?/
What is Local Inventory ?
Inventory inside each Oracle Home is called as local Inventory or oracle_home Inventory. This Inventory holds information to that oracle_home only.
What is Oracle Home Inventory?
Oracle home inventory or local inventory is present inside each Oracle home. It only contains information relevant to a particular Oracle home. This file is located in the following location:
$ORACLE_HOME/inventory
It contains the following files and folders:
·         Components File
·         Home Properties File
·         Other Folders

28). Can I have multiple Global Inventory on a machine ?

Quite common questions is that can you have multiple global Inventory and answer is YES you can have multiple global Inventory but if your upgrading or applying patch then change Inventory Pointer oraInst.loc to respective location. If you are following single global Inventory and if you wish to uninstall any software then remove it from Global Inventory as well.

29). What to do if my Global Inventory is corrupted ?

No need to worry if your global Inventory is corrupted, you can recreate global Inventory on machine using Universal Installer and attach already Installed oracle home by option
-attachHome
./runInstaller -silent -attachHome -invPtrLoc $location_to_oraInst.loc
ORACLE_HOME=”Oracle_Home_Location” ORACLE_HOME_NAME=”Oracle_Home_Name”
CLUSTER_NODES=”{}”


Backup & Delete - Archivelogs and RMAN backups

Backup and Delete - Archivelogs and RMAN backups:
===================================================


sqlplus "/as sysdba"

archive log list;

!df -h or !df -kgt

show parameter db_recovery;

NAME                      TYPE         VALUE
----                      ----         -----
db_recovery_file_dest     string       +FLASHDG
db_recovery_file_dest_size big integer 150G

if +FRA,
select * from V$FLASH_RECOVERY_AREA_USAGE;
(see what kind of files are available in the Flash Recovery Area)

set pages 9999 lines 300
col name format a40
select name,
to_char(space_limit, '999,999,999,999') as space_limit,
to_char(space_limit - space_used + space_reclaimable,
'999,999,999,999') as space_available,
round((space_used - space_reclaimable)/space_limit * 100, 1) as pct_full
from v$recovery_file_dest;

NAME SPACE_LIMIT SPACE_USED SPACE_RECLAIMABLE NUMBER_OF_FILES
---- ----------- ---------- ----------------- ---------------


if SPACE_USED is full, then increase the db_recovery_file_dest_size

rman target /
crosscheck archivelog all;
delete expired archivelog all;
crosscheck backup;

SQL>alter system set db_recovery_file_dest_size=200G scope=both;
System altered.


rman target /

show all;
LIST BACKUP OF ARCHIVELOG FROM TIME 'sysdate-1'; ------List all archivelog backups for the past 24 hours
list backup of archivelog all completed before 'sysdate -1';

list backup of archivelog all;
list backup of archivelog all tag 'TAGXXX';
list archivelog all backed up 1 times to DEVICE TYPE DISK completed before 'sysdate-7';


crosscheck archivelog all;
list expired archivelog ALL;
delete expired archivelog all;

delete obsolete device type disk;
crosscheck backup;
delete expired backup device type disk;
delete expired backupset device type disk;


ls -ltr archivebackup.cmd

nohup rman target / cmdfile=archivebackup.cmd log=archivebackup_dbname_DDMONYY.log &
nohup: appending output to `nohup.out'

tail -f archivebackup_dbname_DDMONYY.log

+FRA/+RECO01 filled with archivelogs
====================================

Backup archivelogs to disk
--------------------------
run
{
allocate channel ch1 type DISK;
allocate channel ch2 type DISK;
allocate channel ch3 type DISK;
allocate channel ch4 type DISK;
BACKUP ARCHIVELOG ALL FILESPERSET 10 DELETE INPUT;
}

Backup archivelogs to disk (specified location,if there is no space to take bakup at archive default location)
--------------------------------------------------------------------------------------------------------------
RUN
{
allocate channel ch1 type DISK;
allocate channel ch2 type DISK;
allocate channel ch3 type DISK;
allocate channel ch4 type DISK;
BACKUP ARCHIVELOG ALL format '/location/arch_%d_%p_%s.rman' FILESPERSET 10 DELETE INPUT;
}

Backup archivelogs to tape (PROD Environment)
--------------------------
run
{
allocate channel ch1 type 'sbt_tape';
allocate channel ch2 type 'sbt_tape';
allocate channel ch3 type 'sbt_tape';
allocate channel ch4 type 'sbt_tape';
BACKUP ARCHIVELOG ALL FILESPERSET 10 DELETE INPUT;
}

+FRA filled with Bacupsets (PROD Environment)
==========================
Move older backupset to tape (to keep more recent backups on disk and older backups only on tape)
-------------------------------------------------------------------------------------------------
run
{
allocate channel ch1 type 'sbt_tape';
allocate channel ch2 type 'sbt_tape';
allocate channel ch3 type 'sbt_tape';
allocate channel ch4 type 'sbt_tape';
BACKUP BACKUPSET COMPLETED BEFORE 'SYSDATE-7' DELETE INPUT;
}

if required,
BACKUP BACKUPSET ALL FILESPERSET 10 DELETE INPUT;

Delete BACKUPSET backed up to tape/disk (PROD Environment)
-----------------------------------------
DELETE NOPROMPT BACKUPSET COMPLETED BEFORE 'SYSDATE-14' DEVICE TYPE DISK;

+FRA filled with Bacupsets (NON-PROD Environment)
==========================
Move older backupset to tape (to keep more recent backups on disk and older backups only on tape)
-------------------------------------------------------------------------------------------------
run
{
allocate channel ch1 type 'sbt_tape';
allocate channel ch2 type 'sbt_tape';
allocate channel ch3 type 'sbt_tape';
allocate channel ch4 type 'sbt_tape';
DELETE BACKUPSET COMPLETED BEFORE 'SYSDATE-4';
}

Delete archivelogs backed up to tape/disk (PROD Environment)
-----------------------------------------
DELETE archivelog UNTIL TIME 'SYSDATE-7' BACKED UP 1 TIMES TO DEVICE TYPE DISK;
DELETE archivelog UNTIL TIME 'SYSDATE-7' BACKED UP 1 TIMES TO DEVICE TYPE SBT_TAPE;

Delete archivelogs backed up to tape/disk (NON-PROD Environment)
-----------------------------------------
DELETE archivelog all BACKED UP 1 TIMES TO DEVICE TYPE DISK;

list archivelog all backed up 1 times to DEVICE TYPE DISK completed before 'sysdate-7';
delete archivelog all backed up 1 times to DEVICE TYPE DISK completed before 'sysdate-7';

backup archivelog [all] [until time 'sysdate']| [sequence between 100 to 110 thread 1] as filesperset 5 delete

input;

backup archivelog from sequence 100 until sequence 110 thread 1 delete input;

backup archivelog from logseq 100 until logseq 110 thread 1 delete input;

report obsolete;
DELETE OBSOLETE REDUNDANCY = 3;
DELETE OBSOLETE RECOVERY WINDOW OF 7 DAYS;



Archivelog deletion using RMAN:
================================

rman target /

list archivelog all backed up 1 times to DEVICE TYPE DISK completed before 'sysdate-3';

delete noprompt archivelog all backed up 1 times to DEVICE TYPE DISK completed before 'sysdate-3';

If you know that the logs are unavailable because you deleted them by using an operating system utility, then run the 

following command at the RMAN prompt to update RMAN metadata:
CROSSCHECK ARCHIVELOG ALL;

It is always better to use RMAN to delete logs than to use an operating system utility. The easiest method to remove 

unwanted logs is to specify the DELETE INPUT option when backing up archived logs. 

For example, enter:
BACKUP DEVICE TYPE sbt ARCHIVELOG ALL DELETE ALL INPUT;


DELETE COMPRESS FILES OS LEVEL:
=================================

To list files dated Apr 24
--------------------------
ls -lrt | grep 'Apr 24' | awk -F' ' '{print$9}'

To delete files dated Apr 24
----------------------------
rm -rf `ls -lrt | grep 'Apr 24' | awk -F' ' '{print$9}'`

To list files of Month Apr
--------------------------
ls -lrt | grep 'Apr' | awk -F' ' '{print$9}'
ls -lrt *.trc|grep 'Apr'|xargs rm -rf  {}\;

To delete files of Month Apr
----------------------------
rm -rf `ls -lrt | grep 'Apr' | awk -F' ' '{print$9}'`

To list files older than 60 days
--------------------------------
find . -name "*.trc" -depth -mtime +60 -exec ls -l {} \; 
find /path/to/files* -mtime +60 -print

To delete files older than 60 days
----------------------------------
find . -name "*.trc" -depth -mtime +60 -exec rm {} \; 
find /path/to/files* -mtime +60 -exec rm {} \;
find /path/to/files* -type f -mtime +60 -print0 | xargs -r rm -rf

COMPRESS
--------
nohup compress *.arc &
ls -lrt *.arc|awk '{print "compress "$9}' >ARC_LIST.txt

Jobs_Info

Jobs Status Info:
---------------------

Scheduler jobs

set lines 300 pages 100
col JOB_ACTION for a50
select job_name, owner,job_action,state,NEXT_RUN_DATE from dba_scheduler_jobs;

enable a broken job
(use this to enable job in a schema, if you want to enable job of different schema, use dbms_ijob)

exec dbms_job.broken(JOB=>43, NEXT_DATE=>'SYSDATE + 1', broken=>FALSE);
exec dbms_job.broken(JOB=>43, NEXT_DATE=>TO_DATE('09-JUN-11 12:30 AM','DD-MON-YY HH:MI AM'), broken=>FALSE);

Breaking a job

dbms_ijob.broken(<job_number>, Boolean);

change interval of a job

exec dbms_job.next_date(83,TO_DATE('14-JUL-11 12:30 AM','DD-MON-YY HH:Mi PM'));
exec dbms_job.interval(83,'SYSDATE + 1');

disable a job

exec dbms_scheduler.disable('AUTO_SPACE_ADVISOR_JOB');

drop job

exec dbms_scheduler.drop_job('ADV_SEGMENTADV_7420699');

User_Sessions_Info

ow to find SQL,SQL_ID history on Oracle
Session related Queries

Last/Latest Running SQL
-----------------------
set pages 50000 lines 32767
col "Last SQL" for 100
SELECT t.inst_id,s.username, s.sid, s.serial#,t.sql_id,t.sql_text "Last SQL"
FROM gv$session s, gv$sqlarea t
WHERE s.sql_address =t.address AND
s.sql_hash_value =t.hash_value
/

Current Running SQLs
--------------------
set pages 50000 lines 32767
col HOST_NAME for a20
col EVENT for a40
col MACHINE for a30
col SQL_TEXT for a50
col USERNAME for a15

select sid,serial#,a.sql_id,a.SQL_TEXT,S.USERNAME,i.host_name,machine,S.event,S.seconds_in_wait sec_wait,
to_char(logon_time,'DD-MON-RR HH24:MI') login
from gv$session S,gV$SQLAREA A,gv$instance i
where S.username is not null
--  and S.status='ACTIVE'
AND S.sql_address=A.address
and s.inst_id=a.inst_id and i.inst_id = a.inst_id
and sql_text not like 'select S.USERNAME,S.seconds_in_wait%'
/

Current Running SQLs
--------------------
set pages 50000 lines 32767
col program format a20
col sql_text format a50

select b.sid,b.status,b.last_call_et,b.program,c.sql_id,c.sql_text
from v$session b,v$sqlarea c
where b.sql_id=c.sql_id
/

Last/Latest Running SQL
----------------------- 
set pages 50000 lines 32767
select inst_id,sample_time,session_id,session_serial#,sql_id from gv$active_session_history
where sql_id is not null 
order by 1 desc
/

SQLs Running from longtime
--------------------------
alter session set nls_date_format = 'dd/mm/yyyy hh24:mi';
set pages 50000 lines 32767
col target format a25
col opname format a40
select sid
      ,opname
      ,target
      ,round(sofar/totalwork*100,2)   as percent_done
      ,start_time
      ,last_update_time
      ,time_remaining
from 
       v$session_longops
/

Active Sessions running for more than 1 hour
---------------------------------------------
set pages 50000 lines 32767
col USERNAME for a10
col MACHINE for a15
col PROGRAM for a40

SELECT USERNAME,machine,inst_id,sid,serial#,PROGRAM,
to_char(logon_time,'dd-mm-yy hh:mi:ss AM')"Logon Time",
ROUND((SYSDATE-LOGON_TIME)*(24*60),1) as MINUTES_LOGGED_ON,
ROUND(LAST_CALL_ET/60,1) as Minutes_FOR_CURRENT_SQL
From gv$session
WHERE STATUS='ACTIVE'
AND USERNAME IS NOT NULL and ROUND((SYSDATE-LOGON_TIME)*(24*60),1) > 60
ORDER BY MINUTES_LOGGED_ON DESC;

Session details associated with SID and Event waiting for
---------------------------------------------------------
set pages 50000 lines 32767
col EVENT for a40

select a.sid, a.serial#, a.status, a.program, b.event,to_char(a.logon_time, 'dd-mon-yy hh24:mi') LOGON_TIME,to_char

(Sysdate, 'dd-mon-yy-hh24:mi') CURRENT_TIME, (a.last_call_et/3600) "Hrs connected" from v$session a,v$session_wait b where 

a.sid in(&SIDs) and a.sid=b.sid order by 8;

Session details associated with Oracle SID
-------------------------------------------
set head off
set verify off
set echo off
set pages 1500
set linesize 100
set lines 120
prompt
prompt Details of SID / SPID / Client PID
prompt ==================================
select /*+ CHOOSE*/
'Session  Id.............................................: '||s.sid,
'Serial Num..............................................: '||s.serial#,
'User Name ..............................................: '||s.username,
'Session Status .........................................: '||s.status,
'Client Process Id on Client Machine ....................: '||'*'||s.process||'*'  Client,
'Server Process ID ......................................: '||p.spid Server,
'Sql_Address ............................................: '||s.sql_address,
'Sql_hash_value .........................................: '||s.sql_hash_value,
'Schema Name ..... ......................................: '||s.SCHEMANAME,
'Program  ...............................................: '||s.program,
'Module .................................................: '|| s.module,
'Action .................................................: '||s.action,
'Terminal ...............................................: '||s.terminal,
'Client Machine .........................................: '||s.machine,
'LAST_CALL_ET ...........................................: '||s.last_call_et,
'S.LAST_CALL_ET/3600 ....................................: '||s.last_call_et/3600
from v$session s, v$process p
where p.addr=s.paddr and
s.sid=nvl('&sid',s.sid) 
/
set head on

Checking for Active Transactions SID
------------------------------------
select username,t.used_ublk,t.used_urec from v$transaction t,v$session s where t.addr=s.taddr;

Session details from Session longops
-------------------------------------
select inst_id,SID,SERIAL#,OPNAME,SOFAR,TOTALWORK,START_TIME,LAST_UPDATE_TIME, username from gv$session_longops;


Session details with SPID
-------------------------
select sid, serial#, USERNAME, STATUS, OSUSER, PROCESS,
MACHINE, MODULE, ACTION, to_char(LOGON_TIME,'yyyy-mm-dd hh24:mi:ss')
from v$session where paddr in (select addr from v$process where spid = '&spid')

To find Undo Generated For a given session
------------------------------------------
select  username,
t.used_ublk ,t.used_urec
from    gv$transaction t,gv$session s
where   t.addr=s.taddr and
s.sid='&sid';

To list count of connections from other machines
------------------------------------------------
select count(1),machine from gv$session where inst_id='&inst_id' group by machine;

To get total count of sessions and processes
--------------------------------------------
select count(*) from v$session;

select count(*) from v$process;

select (select count(*) from v$session) sessions, (select count(*) from v$process) processes from dual;

To find sqltext thru sqladdress
-------------------------------
select sql_address from v$session where sid=1999;

select sql_text from v$sqltext where ADDRESS='C00000027FF00AF0' order by PIECE;

To find sqltext for different sql hashvalue
-------------------------------------------
select hash_value,sql_text from v$sql where hash_value in (1937378691,1564286875,
248741712,2235840973,2787402785)

To list long running forms user sessions
----------------------------------------
select s.sid,s.process,p.spid,s.status ,s.action,s.module, (s.last_call_et/3600) from
v$session s, v$process p where round(last_call_et/3600) >4 and action like '%FRM%' and
p.addr=s.paddr ;

To list inactive Sessions respective username
---------------------------------------------
SELECT username,count(*) num_inv_sess
FROM v$session
where last_call_et > 3600
and username is not null
AND STATUS='INACTIVE'
group by username
order by num_inv_sess DESC;

SELECT count(*) FROM v$session where last_call_et > 43200 and username is not null AND
STATUS='INACTIVE';
SELECT count(*) FROM v$session where last_call_et > 3600 and username is not null AND
STATUS='INACTIVE';

To find session id with set of SPIDs
------------------------------------
select sid from v$session, v$process where addr=paddr and spid in ('11555','26265','11533');

To find Sql Text given SQLHASH & SQLADDR
----------------------------------------
select piece,sql_text from v$sqltext where HASH_VALUE = &hash and ADDRESS ='&addr' order by piece;
select piece,sql_text from v$sqltext where  ADDRESS ='&addr' order by piece;


ocks on Database


Locks on Database
-----------------
set pages 50000 lines 32767 
select object_name,s.inst_id,s.sid,s.serial#,p.sid,s.osuser,s.server,s.machine,s.status 
from gv$locked_object l,gv$session s,gv$process p,dba_objects o 
where
l.object_id=o.object_id and 
l.session_id=s.sid and 
s.paddr=p.addr;


Query to find which is locking the other session:
------------------------------------------------

set pages 50000 lines 32767
col SQL_TEXT for a60
col FIRST_LOAD_TIME a20

select sesion.sid,sesion.status,sesion.username,sql_text,sqlarea.first_load_time 
from gv$sqlarea sqlarea, gv$session sesion
where sesion.sql_hash_value = sqlarea.hash_value
and sesion.sql_address = sqlarea.address
and sesion.sid=161
and sesion.username is not null;

SID STATUS USERNAME  SQL_TEXT FIRST_LOAD_TIME
--- ------ --------  -------- ---------------

To find the Sid and their longops:
--------------------------------

set pages 50000 lines 32767
col OPNAME form a22

select l.sid,l.serial#,l.OPNAME,l.SOFAR,l.TOTALWORK,l.TIME_REMAINING,l.ELAPSED_SECONDS from gv$session_longops l,gv$session 

s where s.sid=l.sid and s.serial#=l.serial#;

     SID SERIAL#    OPNAME   SOFAR      TOTALWORK  TIME_REMAINING ELAPSED_SECONDS
-------- ---------- -------- ---------- ---------- -------------- ---------------

To find the locks for the sid:
-----------------------------

set pages 50000 lines 32767
col OWNER for a20
col NAME for a20

SELECT * FROM dba_dml_locks where SESSION_ID='&sid';

SESSION_ID OWNER NAME MODE_HELD MODE_REQUESTE LAST_CONVERT BLOCKING_OTHERS
---------- ----- ---- --------- ------------- ------------ ---------------


To find any holding sessions:
----------------------------

select * from dba_blockers;

HOLDING_SESSION
---------------
            161

To find waiters:
---------------

set pages 50000 lines 32767
col LOCK_TYPE for a10
col MODE_HELD for a10
col MODE_REQUESTED for a10

select * from dba_waiters;


WAITING_SESSION HOLDING_SESSION LOCK_TYPE MODE_HELD MODE_REQUESTED LOCK_ID1 LOCK_ID2
--------------- --------------- --------- --------- -------------- -------- --------
                             
Blocking details:
----------------

set pages 50000 lines 32767

select distinct s1.username || '@' || s1.machine || ' ( INST=' || s1.inst_id || ' SID=' || s1.sid || ' ) is blocking ' || 

s2.username || '@' || s2.machine || ' ( INST=' || s1.inst_id || ' SID=' || s2.sid || ' ) ' as blocking_status from gv$lock 

l1, gv$session s1, gv$lock l2, gv$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 and l1.inst_id = s1.inst_id;

set pages 50000 lines 32767

col BLOCKER for a20
col BLOCKEE for a20
select
(select username from v$session where sid = a.sid ) blocker,
a.sid, 'is blocking ',
(select username from v$session where sid =b.sid) blockee,
b.sid
from v$lock a, v$lock b
where a.block =1
and b.request > 0
and a.id1 = b.id1
and a.id2 = b.id2;  2    3    4    5    6    7    8    9   10

BLOCKER SID       'ISBLOCKING' BLOCKEE SID
------- ---------- ----------  ------- -------- 

Find locks:
----------

set pages 50000 lines 32767

select 'Sid '||a.sid||' waiting on Sid '||b.sid||' for object '||c.owner||'.'|| c.object_name||' since '||round

(d.last_call_et/60)||' Minutes'||decode(f.status,'INACTIVE','
and Sid '||f.sid||' is inactive since '||round(f.last_call_et/60)||' Minutes.','.')
from gv$lock a,gv$lock b, gv$session d,dba_objects c,gv$locked_object e,gv$session f 
where a.request!=0 and a.type=b.type
and b.lmode!=0 and b.lmode!=1 and a.id1=b.id1 and a.id2=b.id2 and b.request=0 and b.block=1 and a.sid=d.sid and
d.sid=e.session_id and d.status='ACTIVE' and e.object_id=c.object_id and b.sid=f.sid order by d.last_call_et desc;

Another way to find locks:
-------------------------

set pages 50000 lines 32767
select l1.sid, ' IS BLOCKING ', l2.sid from gv$lock l1, gv$lock l2 
where l1.block =1 and l2.request > 0 and l1.id1=l2.id1 and l1.id2=l2.id2;


List of blocking session:
-------------------------
set pages 9999 lines 300 
select 
   blocking_session, 
   sid, 
   serial#, 
   wait_class,
   seconds_in_wait
from 
   v$session
where 
   blocking_session is not NULL
order by 
   blocking_session;

BLOCKING_SESSION        SID    SERIAL# WAIT_CLASS           SECONDS_IN_WAIT
---------------- ---------- ---------- -------------------- ---------------


Particular user query:
----------------------
set pages 9999 lines 300 
select a.sid, a.serial#, b.sql_text
    from v$session a, v$sqlarea b
    where a.sql_address=b.address
    and a.username='EODSBTCH';

Time since last user activity
-----------------------------
set pages 9999 lines 300 
set lines 100 pages 999
select username
,      floor(last_call_et / 60) "Minutes"
,      status
from   v$session
where  username is not null
order by last_call_et
/

Sessions sorted by logon time
-----------------------------
set pages 9999 lines 300 
set lines 100 pages 999
col ID        format a15
col osuser    format a15
col login_time    format a14
select     username
,    osuser
,    sid || ',' || serial# "ID"
,    status
,    to_char(logon_time, 'hh24:mi dd/mm/yy') login_time
,    last_call_et
from    v$session
where    username is not null
order    by login_time
/

Show user info including os pid
-------------------------------
set pages 9999 lines 300 
col "SID/SERIAL" format a10
col username format a15
col osuser format a15
col program format a40
select    s.sid || ',' || s.serial# "SID/SERIAL"
,    s.username
,    s.osuser
,    p.spid "OS PID"
,    s.program
from    v$session s
,    v$process p
Where    s.paddr = p.addr
order     by to_number(p.spid)
/

Show a users current sql
------------------------
set pages 9999 lines 300 
Select sql_text
from   v$sqlarea
where  (address, hash_value) in
(select sql_address, sql_hash_value 
        from v$session
        where username like '&username')
/

Session status associated with the specified os process id
----------------------------------------------------------
set pages 9999 lines 300 
select    s.username
,    s.sid
,    s.serial#
,    p.spid
,    last_call_et
,    status
from     V$SESSION s
,    V$PROCESS p
where    s.PADDR = p.ADDR
and    p.spid='&pid'
/




Longops Query using v$session_longops

Longops.sql
----------- 
set pages 50000 lines 32767
col OPNAME for a10
col SID form 9999
col SERIAL form 9999999
col PROGRAM for a10
col USERNAME for a10
col SQL_TEXT for a40
col START_TIME for a10
col LAST_UPDATE_TIME for a10
col TARGET for a25
col MESSAGE for a25alter session set nls_date_format = 'DD-MM-YYYY HH24:MI:SS';
SELECT inst_id,sid, serial#, sql_id, opname, username, target, sofar, totalwork, start_time,last_update_time,round

(time_remaining/60,2) "REMAIN MINS", round(elapsed_seconds/60,2) "ELAPSED MINS", round((time_remaining

+elapsed_seconds)/60,2) "TOTAL MINS", ROUND(SOFAR/TOTALWORK*100,2) "%_COMPLETE", message
FROM gv$session_longops 
WHERE OPNAME NOT LIKE 'RMAN%' AND OPNAME NOT LIKE '%aggregate%' AND TOTALWORK != 0 AND sofar<>totalwork AND time_remaining 

> 0 
/

Note:
Get the SID from v$session_longops and plug it into v$session to check the SQL command details.

Current Running SQLs
--------------------
set pages 50000 lines 32767
col program format a40
col sql_text format a130

select b.sid,b.status,b.last_call_et,b.program,c.sql_id,c.sql_text from v$session b,v$sqlarea c
where b.sql_id=c.sql_id and b.sid='&sid'


set pages 50000 lines 32767
col USERNAME for a10
col OSUSER for a10
col MACHINE for a10

select s.sid,s.serial#,p.spid,s.username,s.osuser,s.status,s.process fg_pid,s.longon_time,s.machine,p.spid bg_pid from gv

$session s,gv$process p where s.addr=p.addr and s.sid='&sid'
/

$ps -ef | grep <spid>

set pages 50000 lines 32767
SELECT INST_ID, SID, SERIAL#, SQL_ID,USERNAME, PROGRAM, MACHINE, SERVICE_NAME
FROM GV$SESSION
WHERE SID IN ('<SID_NO.1>','<SID_NO.2>')
/
Active Running SQLs
--------------------
 set pages 50000 lines 32767
col SPID for a10
col PROGRAM for a15
col OSUSER for a10
col ACTION for a10
col EVENT for a25
col SQL_TEXT for a25
col MACHINE for a10
col P1TEXT for a10 
col P2TEXT for a10
col P3TEXT for a10  
SELECT b.sid, b.serial#, a.spid, b.sql_id, b.program, b.osuser, b.machine, b.type,
b.event, b.action, b.p1text, b.p2text, b.p3text, b.state, c.sql_text,b.logon_time
FROM v$process a, v$session b, v$sqltext c WHERE a.addr=b.paddr
AND b.sql_hash_value = c.hash_value
AND b.STATUS = 'ACTIVE'
AND b.sid = '&sid' ORDER BY a.spid, c.piece
/

OR - Use the below Query 

Longops.sql
----------- 
set pages 50000 lines 32767
col OPNAME for a10
col SID form 9999
col SERIAL form 9999999
col PROGRAM for a10
col USERNAME for a10
col SQL_TEXT for a40
col START_TIME for a10
col LAST_UPDATE_TIME for a10
col TARGET for a25
col MESSAGE for a25

alter session set nls_date_format = 'DD-MM-YYYY HH24:MI:SS';

SELECT l.inst_id,l.sid, l.serial#, l.sql_id, l.opname, l.username, l.target, l.sofar, l.totalwork, 

l.start_time,l.last_update_time,round(l.time_remaining/60,2) "REMAIN MINS", round(l.elapsed_seconds/60,2) "ELAPSED MINS", 

round((l.time_remaining+l.elapsed_seconds)/60,2) "TOTAL MINS", ROUND(l.SOFAR/l.TOTALWORK*100,2) "%_COMPLETE", 

l.message,s.sql_text 
FROM gv$session_longops l 

LEFT OUTER JOIN v$sql s on s.hash_value=l.sql_hash_value and s.address=l.sql_address and s.child_number=0
WHERE l.OPNAME NOT LIKE 'RMAN%' AND l.OPNAME NOT LIKE '%aggregate%' AND l.TOTALWORK != 0 AND l.sofar<>l.totalwork AND 

l.time_remaining > 0
/
ow to find SQL,SQL_ID history on Oracle
Session related Queries

Last/Latest Running SQL
-----------------------
set pages 50000 lines 32767
col "Last SQL" for 100
SELECT t.inst_id,s.username, s.sid, s.serial#,t.sql_id,t.sql_text "Last SQL"
FROM gv$session s, gv$sqlarea t
WHERE s.sql_address =t.address AND
s.sql_hash_value =t.hash_value
/

Current Running SQLs
--------------------
set pages 50000 lines 32767
col HOST_NAME for a20
col EVENT for a40
col MACHINE for a30
col SQL_TEXT for a50
col USERNAME for a15

select sid,serial#,a.sql_id,a.SQL_TEXT,S.USERNAME,i.host_name,machine,S.event,S.seconds_in_wait sec_wait,
to_char(logon_time,'DD-MON-RR HH24:MI') login
from gv$session S,gV$SQLAREA A,gv$instance i
where S.username is not null
--  and S.status='ACTIVE'
AND S.sql_address=A.address
and s.inst_id=a.inst_id and i.inst_id = a.inst_id
and sql_text not like 'select S.USERNAME,S.seconds_in_wait%'
/

Current Running SQLs
--------------------
set pages 50000 lines 32767
col program format a20
col sql_text format a50

select b.sid,b.status,b.last_call_et,b.program,c.sql_id,c.sql_text
from v$session b,v$sqlarea c
where b.sql_id=c.sql_id
/

Last/Latest Running SQL
----------------------- 
set pages 50000 lines 32767
select inst_id,sample_time,session_id,session_serial#,sql_id from gv$active_session_history
where sql_id is not null 
order by 1 desc
/

SQLs Running from longtime
--------------------------
alter session set nls_date_format = 'dd/mm/yyyy hh24:mi';
set pages 50000 lines 32767
col target format a25
col opname format a40
select sid
      ,opname
      ,target
      ,round(sofar/totalwork*100,2)   as percent_done
      ,start_time
      ,last_update_time
      ,time_remaining
from 
       v$session_longops
/

Active Sessions running for more than 1 hour
---------------------------------------------
set pages 50000 lines 32767
col USERNAME for a10
col MACHINE for a15
col PROGRAM for a40

SELECT USERNAME,machine,inst_id,sid,serial#,PROGRAM,
to_char(logon_time,'dd-mm-yy hh:mi:ss AM')"Logon Time",
ROUND((SYSDATE-LOGON_TIME)*(24*60),1) as MINUTES_LOGGED_ON,
ROUND(LAST_CALL_ET/60,1) as Minutes_FOR_CURRENT_SQL
From gv$session
WHERE STATUS='ACTIVE'
AND USERNAME IS NOT NULL and ROUND((SYSDATE-LOGON_TIME)*(24*60),1) > 60
ORDER BY MINUTES_LOGGED_ON DESC;

Session details associated with SID and Event waiting for
---------------------------------------------------------
set pages 50000 lines 32767
col EVENT for a40

select a.sid, a.serial#, a.status, a.program, b.event,to_char(a.logon_time, 'dd-mon-yy hh24:mi') LOGON_TIME,to_char

(Sysdate, 'dd-mon-yy-hh24:mi') CURRENT_TIME, (a.last_call_et/3600) "Hrs connected" from v$session a,v$session_wait b where 

a.sid in(&SIDs) and a.sid=b.sid order by 8;

Session details associated with Oracle SID
-------------------------------------------
set head off
set verify off
set echo off
set pages 1500
set linesize 100
set lines 120
prompt
prompt Details of SID / SPID / Client PID
prompt ==================================
select /*+ CHOOSE*/
'Session  Id.............................................: '||s.sid,
'Serial Num..............................................: '||s.serial#,
'User Name ..............................................: '||s.username,
'Session Status .........................................: '||s.status,
'Client Process Id on Client Machine ....................: '||'*'||s.process||'*'  Client,
'Server Process ID ......................................: '||p.spid Server,
'Sql_Address ............................................: '||s.sql_address,
'Sql_hash_value .........................................: '||s.sql_hash_value,
'Schema Name ..... ......................................: '||s.SCHEMANAME,
'Program  ...............................................: '||s.program,
'Module .................................................: '|| s.module,
'Action .................................................: '||s.action,
'Terminal ...............................................: '||s.terminal,
'Client Machine .........................................: '||s.machine,
'LAST_CALL_ET ...........................................: '||s.last_call_et,
'S.LAST_CALL_ET/3600 ....................................: '||s.last_call_et/3600
from v$session s, v$process p
where p.addr=s.paddr and
s.sid=nvl('&sid',s.sid) 
/
set head on

Checking for Active Transactions SID
------------------------------------
select username,t.used_ublk,t.used_urec from v$transaction t,v$session s where t.addr=s.taddr;

Session details from Session longops
-------------------------------------
select inst_id,SID,SERIAL#,OPNAME,SOFAR,TOTALWORK,START_TIME,LAST_UPDATE_TIME, username from gv$session_longops;


Session details with SPID
-------------------------
select sid, serial#, USERNAME, STATUS, OSUSER, PROCESS,
MACHINE, MODULE, ACTION, to_char(LOGON_TIME,'yyyy-mm-dd hh24:mi:ss')
from v$session where paddr in (select addr from v$process where spid = '&spid')

To find Undo Generated For a given session
------------------------------------------
select  username,
t.used_ublk ,t.used_urec
from    gv$transaction t,gv$session s
where   t.addr=s.taddr and
s.sid='&sid';

To list count of connections from other machines
------------------------------------------------
select count(1),machine from gv$session where inst_id='&inst_id' group by machine;

To get total count of sessions and processes
--------------------------------------------
select count(*) from v$session;

select count(*) from v$process;

select (select count(*) from v$session) sessions, (select count(*) from v$process) processes from dual;

To find sqltext thru sqladdress
-------------------------------
select sql_address from v$session where sid=1999;

select sql_text from v$sqltext where ADDRESS='C00000027FF00AF0' order by PIECE;

To find sqltext for different sql hashvalue
-------------------------------------------
select hash_value,sql_text from v$sql where hash_value in (1937378691,1564286875,
248741712,2235840973,2787402785)

To list long running forms user sessions
----------------------------------------
select s.sid,s.process,p.spid,s.status ,s.action,s.module, (s.last_call_et/3600) from
v$session s, v$process p where round(last_call_et/3600) >4 and action like '%FRM%' and
p.addr=s.paddr ;

To list inactive Sessions respective username
---------------------------------------------
SELECT username,count(*) num_inv_sess
FROM v$session
where last_call_et > 3600
and username is not null
AND STATUS='INACTIVE'
group by username
order by num_inv_sess DESC;

SELECT count(*) FROM v$session where last_call_et > 43200 and username is not null AND
STATUS='INACTIVE';
SELECT count(*) FROM v$session where last_call_et > 3600 and username is not null AND
STATUS='INACTIVE';

To find session id with set of SPIDs
------------------------------------
select sid from v$session, v$process where addr=paddr and spid in ('11555','26265','11533');

To find Sql Text given SQLHASH & SQLADDR
----------------------------------------
select piece,sql_text from v$sqltext where HASH_VALUE = &hash and ADDRESS ='&addr' order by piece;
select piece,sql_text from v$sqltext where  ADDRESS ='&addr' order by piece;


ocks on Database


Locks on Database
-----------------
set pages 50000 lines 32767 
select object_name,s.inst_id,s.sid,s.serial#,p.sid,s.osuser,s.server,s.machine,s.status 
from gv$locked_object l,gv$session s,gv$process p,dba_objects o 
where
l.object_id=o.object_id and 
l.session_id=s.sid and 
s.paddr=p.addr;


Query to find which is locking the other session:
------------------------------------------------

set pages 50000 lines 32767
col SQL_TEXT for a60
col FIRST_LOAD_TIME a20

select sesion.sid,sesion.status,sesion.username,sql_text,sqlarea.first_load_time 
from gv$sqlarea sqlarea, gv$session sesion
where sesion.sql_hash_value = sqlarea.hash_value
and sesion.sql_address = sqlarea.address
and sesion.sid=161
and sesion.username is not null;

SID STATUS USERNAME  SQL_TEXT FIRST_LOAD_TIME
--- ------ --------  -------- ---------------

To find the Sid and their longops:
--------------------------------

set pages 50000 lines 32767
col OPNAME form a22

select l.sid,l.serial#,l.OPNAME,l.SOFAR,l.TOTALWORK,l.TIME_REMAINING,l.ELAPSED_SECONDS from gv$session_longops l,gv$session 

s where s.sid=l.sid and s.serial#=l.serial#;

     SID SERIAL#    OPNAME   SOFAR      TOTALWORK  TIME_REMAINING ELAPSED_SECONDS
-------- ---------- -------- ---------- ---------- -------------- ---------------

To find the locks for the sid:
-----------------------------

set pages 50000 lines 32767
col OWNER for a20
col NAME for a20

SELECT * FROM dba_dml_locks where SESSION_ID='&sid';

SESSION_ID OWNER NAME MODE_HELD MODE_REQUESTE LAST_CONVERT BLOCKING_OTHERS
---------- ----- ---- --------- ------------- ------------ ---------------


To find any holding sessions:
----------------------------

select * from dba_blockers;

HOLDING_SESSION
---------------
            161

To find waiters:
---------------

set pages 50000 lines 32767
col LOCK_TYPE for a10
col MODE_HELD for a10
col MODE_REQUESTED for a10

select * from dba_waiters;


WAITING_SESSION HOLDING_SESSION LOCK_TYPE MODE_HELD MODE_REQUESTED LOCK_ID1 LOCK_ID2
--------------- --------------- --------- --------- -------------- -------- --------
                             
Blocking details:
----------------

set pages 50000 lines 32767

select distinct s1.username || '@' || s1.machine || ' ( INST=' || s1.inst_id || ' SID=' || s1.sid || ' ) is blocking ' || 

s2.username || '@' || s2.machine || ' ( INST=' || s1.inst_id || ' SID=' || s2.sid || ' ) ' as blocking_status from gv$lock 

l1, gv$session s1, gv$lock l2, gv$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 and l1.inst_id = s1.inst_id;

set pages 50000 lines 32767

col BLOCKER for a20
col BLOCKEE for a20
select
(select username from v$session where sid = a.sid ) blocker,
a.sid, 'is blocking ',
(select username from v$session where sid =b.sid) blockee,
b.sid
from v$lock a, v$lock b
where a.block =1
and b.request > 0
and a.id1 = b.id1
and a.id2 = b.id2;  2    3    4    5    6    7    8    9   10

BLOCKER SID       'ISBLOCKING' BLOCKEE SID
------- ---------- ----------  ------- -------- 

Find locks:
----------

set pages 50000 lines 32767

select 'Sid '||a.sid||' waiting on Sid '||b.sid||' for object '||c.owner||'.'|| c.object_name||' since '||round

(d.last_call_et/60)||' Minutes'||decode(f.status,'INACTIVE','
and Sid '||f.sid||' is inactive since '||round(f.last_call_et/60)||' Minutes.','.')
from gv$lock a,gv$lock b, gv$session d,dba_objects c,gv$locked_object e,gv$session f 
where a.request!=0 and a.type=b.type
and b.lmode!=0 and b.lmode!=1 and a.id1=b.id1 and a.id2=b.id2 and b.request=0 and b.block=1 and a.sid=d.sid and
d.sid=e.session_id and d.status='ACTIVE' and e.object_id=c.object_id and b.sid=f.sid order by d.last_call_et desc;

Another way to find locks:
-------------------------

set pages 50000 lines 32767
select l1.sid, ' IS BLOCKING ', l2.sid from gv$lock l1, gv$lock l2 
where l1.block =1 and l2.request > 0 and l1.id1=l2.id1 and l1.id2=l2.id2;


List of blocking session:
-------------------------
set pages 9999 lines 300 
select 
   blocking_session, 
   sid, 
   serial#, 
   wait_class,
   seconds_in_wait
from 
   v$session
where 
   blocking_session is not NULL
order by 
   blocking_session;

BLOCKING_SESSION        SID    SERIAL# WAIT_CLASS           SECONDS_IN_WAIT
---------------- ---------- ---------- -------------------- ---------------


Particular user query:
----------------------
set pages 9999 lines 300 
select a.sid, a.serial#, b.sql_text
    from v$session a, v$sqlarea b
    where a.sql_address=b.address
    and a.username='EODSBTCH';

Time since last user activity
-----------------------------
set pages 9999 lines 300 
set lines 100 pages 999
select username
,      floor(last_call_et / 60) "Minutes"
,      status
from   v$session
where  username is not null
order by last_call_et
/

Sessions sorted by logon time
-----------------------------
set pages 9999 lines 300 
set lines 100 pages 999
col ID        format a15
col osuser    format a15
col login_time    format a14
select     username
,    osuser
,    sid || ',' || serial# "ID"
,    status
,    to_char(logon_time, 'hh24:mi dd/mm/yy') login_time
,    last_call_et
from    v$session
where    username is not null
order    by login_time
/

Show user info including os pid
-------------------------------
set pages 9999 lines 300 
col "SID/SERIAL" format a10
col username format a15
col osuser format a15
col program format a40
select    s.sid || ',' || s.serial# "SID/SERIAL"
,    s.username
,    s.osuser
,    p.spid "OS PID"
,    s.program
from    v$session s
,    v$process p
Where    s.paddr = p.addr
order     by to_number(p.spid)
/

Show a users current sql
------------------------
set pages 9999 lines 300 
Select sql_text
from   v$sqlarea
where  (address, hash_value) in
(select sql_address, sql_hash_value 
        from v$session
        where username like '&username')
/

Session status associated with the specified os process id
----------------------------------------------------------
set pages 9999 lines 300 
select    s.username
,    s.sid
,    s.serial#
,    p.spid
,    last_call_et
,    status
from     V$SESSION s
,    V$PROCESS p
where    s.PADDR = p.ADDR
and    p.spid='&pid'
/




Longops Query using v$session_longops

Longops.sql
----------- 
set pages 50000 lines 32767
col OPNAME for a10
col SID form 9999
col SERIAL form 9999999
col PROGRAM for a10
col USERNAME for a10
col SQL_TEXT for a40
col START_TIME for a10
col LAST_UPDATE_TIME for a10
col TARGET for a25
col MESSAGE for a25alter session set nls_date_format = 'DD-MM-YYYY HH24:MI:SS';
SELECT inst_id,sid, serial#, sql_id, opname, username, target, sofar, totalwork, start_time,last_update_time,round

(time_remaining/60,2) "REMAIN MINS", round(elapsed_seconds/60,2) "ELAPSED MINS", round((time_remaining

+elapsed_seconds)/60,2) "TOTAL MINS", ROUND(SOFAR/TOTALWORK*100,2) "%_COMPLETE", message
FROM gv$session_longops 
WHERE OPNAME NOT LIKE 'RMAN%' AND OPNAME NOT LIKE '%aggregate%' AND TOTALWORK != 0 AND sofar<>totalwork AND time_remaining 

> 0 
/

Note:
Get the SID from v$session_longops and plug it into v$session to check the SQL command details.

Current Running SQLs
--------------------
set pages 50000 lines 32767
col program format a40
col sql_text format a130

select b.sid,b.status,b.last_call_et,b.program,c.sql_id,c.sql_text from v$session b,v$sqlarea c
where b.sql_id=c.sql_id and b.sid='&sid'


set pages 50000 lines 32767
col USERNAME for a10
col OSUSER for a10
col MACHINE for a10

select s.sid,s.serial#,p.spid,s.username,s.osuser,s.status,s.process fg_pid,s.longon_time,s.machine,p.spid bg_pid from gv

$session s,gv$process p where s.addr=p.addr and s.sid='&sid'
/

$ps -ef | grep <spid>

set pages 50000 lines 32767
SELECT INST_ID, SID, SERIAL#, SQL_ID,USERNAME, PROGRAM, MACHINE, SERVICE_NAME
FROM GV$SESSION
WHERE SID IN ('<SID_NO.1>','<SID_NO.2>')
/
Active Running SQLs
--------------------
 set pages 50000 lines 32767
col SPID for a10
col PROGRAM for a15
col OSUSER for a10
col ACTION for a10
col EVENT for a25
col SQL_TEXT for a25
col MACHINE for a10
col P1TEXT for a10 
col P2TEXT for a10
col P3TEXT for a10  
SELECT b.sid, b.serial#, a.spid, b.sql_id, b.program, b.osuser, b.machine, b.type,
b.event, b.action, b.p1text, b.p2text, b.p3text, b.state, c.sql_text,b.logon_time
FROM v$process a, v$session b, v$sqltext c WHERE a.addr=b.paddr
AND b.sql_hash_value = c.hash_value
AND b.STATUS = 'ACTIVE'
AND b.sid = '&sid' ORDER BY a.spid, c.piece
/

OR - Use the below Query 

Longops.sql
----------- 
set pages 50000 lines 32767
col OPNAME for a10
col SID form 9999
col SERIAL form 9999999
col PROGRAM for a10
col USERNAME for a10
col SQL_TEXT for a40
col START_TIME for a10
col LAST_UPDATE_TIME for a10
col TARGET for a25
col MESSAGE for a25

alter session set nls_date_format = 'DD-MM-YYYY HH24:MI:SS';

SELECT l.inst_id,l.sid, l.serial#, l.sql_id, l.opname, l.username, l.target, l.sofar, l.totalwork, 

l.start_time,l.last_update_time,round(l.time_remaining/60,2) "REMAIN MINS", round(l.elapsed_seconds/60,2) "ELAPSED MINS", 

round((l.time_remaining+l.elapsed_seconds)/60,2) "TOTAL MINS", ROUND(l.SOFAR/l.TOTALWORK*100,2) "%_COMPLETE", 

l.message,s.sql_text 
FROM gv$session_longops l 

LEFT OUTER JOIN v$sql s on s.hash_value=l.sql_hash_value and s.address=l.sql_address and s.child_number=0
WHERE l.OPNAME NOT LIKE 'RMAN%' AND l.OPNAME NOT LIKE '%aggregate%' AND l.TOTALWORK != 0 AND l.sofar<>l.totalwork AND 

l.time_remaining > 0
/