Friday 30 October 2015

Real Time Linux & Unix Useful Commands

Real Time Linux & Unix Useful Commands:
-------------------------------------------------------
compress Listener log file in Linux and real time useful commands:
=================================================
Unix Level Useful commands
=========================

Step:-1
-------
cd /u01/app/oracle/10.2.0/db_1/network/admin --- listener log location

du -sh *|sort -n

du -sh listener.log

Step:-2
-------
vi filecompress.sh

cd /u01/app/oracle/10.2.0/db_1/network/admin --- listener log location

cp listener.log listener_currentdate.log

cat /dev/null > listener.log

-- press esc key
:wq

Run the filecompress.sh in nohup
---------------------------------

nohup sh -x filecompress.sh > filecompress.log 2>> filecompress.err &

Step:-3
-------

gzip -9 listener_currentdate.log

du -sh *.gz

--- OR ---

tar -zcvf listener_currentdate.tar.gz listener_currentdate.log

du -sh *.tar.gz


All the platforms (Linux, Solaries, AIX,IBMAIX,Sunsolaries) and it is very useful editing commands:
===============================================================================================

vi Editor Commands
vi Editor Commands

$ vi <filename>

Option ==> Action
vi     ==> Starts editing session in memory.
vi     ==> Starts session and opens the specified file.
vi *   ==> Opens first file that matches the wildcard pattern. Use :n to navigate to the next matched file.
view   ==> Opens file in read-only mode.
vi -R  ==> Opens file in read-only mode.
vi -r  ==> Recovers file and recent edits after abnormal abort from editing session (like a system crash).
vi +n  ==> Opens file at specified line number n.
vi +   ==> Opens file at the last line.
vi +/  ==> Opens file at first occurrence of specified string pattern.

Common Techniques to Enter vi Insert Mode:

Enter Insert Command ==> Action

i ==> Insert text in front of the cursor.
a ==> Insert text after the cursor.
I ==> Insert text at the beginning of the line.
A ==> Insert text at the end of the line.
o ==> Insert text below the current line.
O ==> Insert text above the current line.

Useful vi Exit Commands

Exit Command ==> Action
:wq ==> Save and exit.
ZZ  ==> Save and exit.
:x  ==> Save and exit.
:w  ==> Save the current edits without exiting.
:w! ==> Override file protections and save.
:q  ==> Exit the file.
:q! ==> Exit without saving.
:n  ==> Edit next file.
:e! ==> Return to previously saved version.

Common Navigation Commands

Command               ==> Action
j (or down arrow)     ==> Move down a line.
k (or up arrow)       ==> Move up a line.
h (or left arrow)     ==> Move one character left.
l (or right arrow)    ==> Move one character right.
Ctrl+f (or Page Down) ==> Scroll down one screen.
Ctrl+b (or Page Up)   ==> Scroll up one screen.
1G ==> Go to first line in file.
G  ==> Go to last line in file.
nG ==> Go to n line number.
H  ==> Go to top of screen.
L  ==> Go to bottom of screen.
w  ==> Move one word forward.
b  ==> Move one word backward.
0  ==> Go to start of line.
$  ==> Go to end of line.

Common Options for Copying, Deleting, and Pasting Text

Option ==> Action
yy  ==> Yank (copy) the current line.
nyy ==> Yank (copy) n number of lines.
p   ==> Put yanked line(s) below the cursor.
P   ==> Put yanked line(s) above the cursor.
x   ==> Delete the character that the cursor is on.
X   ==> Delete the character to the left of the cursor.
dw  ==> Delete the word the cursor is currently on.
dd  ==> Delete current line of text.
ndd ==> Delete n lines of text
D   ==> Delete to the end of the current line.

Common Options for Changing Text

Option ==> Action
r  ==> Replace the character that the curser is on with the next character you type.
~  ==> Change the case of a character.
cc ==> Delete the current line and insert text.
C  ==> Delete to the end of the line and insert text.
c$ ==> Delete to the end of the line and insert text.
cw ==> Delete to the end of the word and insert text.
R  ==> Type over the characters in the current line.
s  ==> Delete the current character and insert text.
S  ==> Delete the current line and insert text.

Common Options for Text Searching

Option ==> Action
/ ==> Search forward for a string.
? ==> Search backward for a string.
n ==> Repeat the search forward.
N ==> Repeat the search backward.
f ==> Search forward for a character in the current line.
F ==> Search backward for a character in the current line.

:set number ==> Displaying Line Numbers

===================================================================

bg, fg and jobs Linux Commands

Every command you give is a job that is executed. A job can be suspended, placed in the background, moved back to the foreground or terminated.

While running a job you can        Shortcut
---------------------------            ----------
suspend a job                    ctrl+z

terminate a job                    ctrl+c

Function                            Command
--------                            ------------
Move a suspended job to the foreground        fg

Continue a suspended job in the background    bg

List all jobs                            jobs

Kill a job (%N where N is the job number)    kill %N && fg

Start a job directly in the background            command &

When you execute a unix shell-script or command that takes a long time, you can run it as a background job.

1. Executing a background job

$ find . -name "*.aud" -mtime +120 -exec rm {} \; &

2. Sending the current foreground job to the background using CTRL+Z and bg command
    step 1.Press 'CTRL+Z' which will suspend the current foreground job.
    step 2.Execute 'bg to' make that command to execute in background.

Press ‘CTRL+Z’
$ bg

3. View all the background jobs using jobs command.

$jobs

jobs    : lists the jobs that you are running in the background and in the foreground

jobs -p : list only the PID of process group leader

jobs -l : list only jobs that have change status since last notified by their status

jobs -r : resrict output to running jobs

jobs – s : restrict output to stopped jobs

4. Taking a job from the background to the foreground using fg command

$ fg

When executed without arguments, it will take the most recent background job to the below commands:

We have two Methods:

1. throw SCP:

$SCP -P <file Name> oracle@hostname:<destpath>/.

OR

Throw SFTP:

======================================================================================
SFTP

>sftp <user>@<hostname>
Connecting to <hostname>...
<user>'s Password:
sftp>pwd                   (remote working directory)
sftp>!pwd                  (local working directory)
sftp>cd /target/path/   (remote path)
sftp>pwd                   (remote working directory)
sftp>!ls -l                   (local working directory)
sftp>put <filename(s)>
Uploading <filename> to /target/path/<filename>
sftp>ls -l                    (remote location files)
sftp>bye


=============================================================================================
Linux Basic Commands at OS Level:
---------------------------------


!stty erase ^?

ORACLE_SID=`ps -ef | grep asm_smon | grep -v 'grep' | grep -v 'sed' | awk '{printf $8}' | awk 'BEGIN{FS="_"} {printf $3}'`

date

env

uptime

who -b

last | grep -i boot

ps -ef | grep pmon

ps -ef | grep tns

ps -ef | grep d.bin

df -h or df -g

uname

/etc/oratab or /etc/var/oracle/oratab

df -kh or df -kh . or df -kh /mountpoint/

du -sh * or du -sh .

du -sg *

ls -ltrh <filename> | sort -n

ls -ld

tellme system

lsof /mountpoint/

find /home -name oraInventory -print

find . -name "*.gz" -depth -mtime +60 -exec rm {} \;

nslookup

tnsping

top

bg, fg, jobs

===========================

It find the particular file locations using below commands
-----------------------------------------------------------------


To find a file/directory
------------------------
find /home -name oraInventory -print

find /home|grep oraInventory

To delete files older than 60 days
----------------------------------
find . -name "*.gz" -depth -mtime +60 -exec rm {} \; 

Take the backups using the below commands(Oracle Home backups & Listner backups)

=================================================================================

TAR(Realtime commands):


tar -cvf newname.tar directory_name (to tar)
tar -xvf filename.tar (to untar)

========================================================

 COMPRESS & Delete FILES at 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

Below COMPRESS command::
-----------------------
nohup compress *.arc &

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

SOURCE : Internet

References:

http://eisabainyo.net/weblog/useful-linux-commands/


=================================================================
 REBOOT Server:
===============
If its Dataguard setup or normal db, following steps mandatory just take backup of following three steps and store it in separate notepad. once server reboot activity 

completed cross check once which was taken before server reboot.
===============================================================

ps -ef|grep pmon  

ps -ef|grep pmon|wc -l

ps -ef|grep inh (OR) ps -ef|grep tns

ps -ef|grep inh|wc -l

ps -ef |grep d.bin

hostname

date

uname -a

cat /etc/oratab  /  cat /var/opt/oracle/oratab

uptime 

who -b

df -h  / df -gt
-------------------------------------------------------------------------------------------
Reboot Server  time database side need to  check the below commands: 

(Before server reboot and after server boot, if its is DG database)
-------------------------------------------------------------------

SQL> select name,db_unique_name,database_role,controlfile_type,CREATED from v$database;

SQL >select sequence#,first_time,next_time,completion_time,applied from v$archived_log where applied <> 'YES' and DEST_ID !=0 and status!='D'and completion_time <

(sysdate-1/48) Order By 1;

no rows selected----->in sync

SQL >select process, status ,sequence# from v$managed_standby;

MRP0---->process should reflect

===============================
Realtime Data Guard Db Startup Procedure
===============================

Sqlplus “/ as sysdba”

startup nomount;

alter database mount standby database;

recover managed standby database disconnect from session; ----------->To put it in MRM MODE

exit;

=================================
Realtime Data Guard Db  Shutdown Procedure
=================================

Login as oracle

source the environment

sqlplus “/ as sysdba”

alter database recover managed standby database cancel; ------> to cancel MRM mode

shutdown immediate;
==================================================


Saturday 24 October 2015

Tablespaces Creation steps

Tablespaces Creation Steps:

Locally managed tablespaces track all extent information in the tablespace itself by using bitmaps, resulting in the following benefits:

Concurrency and speed of space operations is improved, because space allocations and deallocations modify locally managed resources (bitmaps stored in header files).
Performance is improved, because recursive operations that are sometimes required during dictionary-managed space allocation are eliminated
To create a locally managed tablespace give the following command

SQL> CREATE TABLESPACE ravi DATAFILE '/u02/oracle/ravi/ravi01.dbf' SIZE 100M
    EXTENT MANAGEMENT LOCAL AUTOALLOCATE;
             

AUTOALLOCATE causes the tablespace to be system managed with a minimum extent size of 64K.

The alternative to AUTOALLOCATE is UNIFORM. which specifies that the tablespace is managed with extents of uniform size. You can specify that size in the SIZE clause

of UNIFORM. If you omit SIZE, then the default size is 1M. The following example creates a Locally managed tablespace with uniform extent size of 256K

SQL> CREATE TABLESPACE ravi DATAFILE '/u02/oracle/ravi/ravi01.dbf' SIZE 100M EXTENT MANAGEMENT LOCAL UNIFORM SIZE 256K;

 Create Dictionary Managed Tablespace

SQL> CREATE TABLESPACE ravi_lmt DATAFILE '/u02/oracle/ravi/ravi01.dbf' SIZE 50M EXTENT MANAGEMENT DICTIONARY;

Bigfile Tablespaces (Introduced in Oracle Ver. 10g)
A bigfile tablespace is a tablespace with a single, but very large (up to 4G blocks) datafile. Traditional smallfile tablespaces, in contrast, can contain multiple

datafiles, but the files cannot be as large. Bigfile tablespaces can reduce the number of datafiles needed for a database.

 create a bigfile tablespace given the below inputs.

SQL> CREATE BIGFILE TABLESPACE ravi_bigtbs
    DATAFILE '/u02/oracle/ravi/bigtbs01.dbf' SIZE 30G;

Process 1:

Re- Size the tablespace in below inputs.

To increasing the size of an existing datafile in below given inputs.

SQL> alter  database ravi datafile ‘/u01/oracle/data/ravi01.dbf’ resize 100M;


Process 2:

To resize of a tablespace by adding a new datafile to a tablespace. Please find the below inputs for resie the tablespace.

SQL> alter tablespace add datafile  ‘/u02/oracle/ravi/ravitbs02.dbf’ size 100M;


Process 3:


Oracle will automatravilly increase the size of a datafile whenever space is required. You can specify by how much size the file should increase and Maximum size to

which it should extending.

Existing datafile auto extendable in below given inputs.

SQL> alter database datafile ‘/u01/oracle/ravi/ravitbs01.dbf’ auto extend ON next 5M maxsize 500M;

Extendable while creating a new tablespace in below given inputs.

SQL> create tablespace ravi datafile ‘/u01/oracle/ravi/ravitbs01.dbf’ size 50M auto extend ON next 5M maxsize 500M;

 Decrease the size of a tablespace:

Decrese the size of tablespace by decreasing the datafile associated with it. Decrease a datafile only up to size of empty space in it.

SQL> alter database datafile ‘/u01/oracle/ravi/ravitbs01.dbf’  resize 30M;


Making tablespaces Offline or Online:

Online tablespace offline so that it is temporarily unavailable for general use. The rest of the database remains open and available for users to
access data. Conversely, you can bring an offline tablespace online to make the schema objects within the tablespace available to database users.

Alter the availability of a tablespace, use the ALTER TABLESPACE statement. You must have the ALTER TABLESPACE or MANAGE TABLESPACE system privilege.

 Make a Tablespace Offline in below given inputs.

SQL>alter tablespace ravi offline;

Make a bring it back online in below given inputs.

SQL>alter tablespace ravi online;

Make individual datafile offline type the following command

SQL>alter database datafile ‘/u01/oracle/ravi/ravi_tbs01.dbf’ offline;

Again to bring it back online give the following command

SQL> alter database datafile ‘/u01/oracle/ravi/ravi_tbs01.dbf’ online;

Note: You can’t take individual datafiles offline it the database is running in NOARCHIVELOG mode.  If the datafile has become corrupt or missing when the database is

running in NOARCHIVELOG mode then you can only drop it by giving the following command

SQL>alter database datafile ‘/u01/oracle/ravi/ravi_tbs01.dbf’ offline for drop;

Making a Tablespace Read only.
Making a tablespace read-only prevents write operations on the datafiles in the tablespace. The primary purpose of read-only tablespaces is to eliminate the need to

perform backup and recovery of large, static portions of a database. Read-only tablespaces also provide a way to protecting historravil data so that users cannot modify

it. Making a tablespace read-only prevents updates on all tables in the tablespace, regardless of a user's update privilege level.

To make a tablespace read only

SQL>alter tablespace ravi read only

Again to make it read write

SQL>alter tablespace ravi read write;

Renaming Tablespaces
Using the RENAME TO clause of the ALTER TABLESPACE, you can rename a permanent or temporary tablespace. For example, the following statement renames the users

tablespace:

ALTER TABLESPACE users RENAME TO usersts;


The following affect the operation of this statement:

The COMPATIBLE parameter must be set to 10.0 or higher.
If the tablespace being renamed is the SYSTEM tablespace or the SYSAUX tablespace, then it will not be renamed and an error is raised.
If any datafile in the tablespace is offline, or if the tablespace is offline, then the tablespace is not renamed and an error is raised.
Dropping Tablespaces
You can drop a tablespace and its contents (the segments contained in the tablespace) from the database if the tablespace and its contents are no longer required. You

must have the DROP TABLESPACE system privilege to drop a tablespace.

Caution: Once a tablespace has been dropped, the data in the tablespace is not recoverable. Therefore, make sure that all data contained in a tablespace to be dropped

will not be required in the future. Also, immediately before and after dropping a tablespace from a database, back up the database completely

To drop a tablespace give the following command.

SQL> drop tablespace ravi;

This will drop the tablespace only if it is empty. If it is not empty and if you want to drop it anyhow then add the following keyword

SQL>drop tablespace ravi including contents;

This will drop the tablespace even if it is not empty. But the datafiles will not be deleted you have to use operating system command to delete the files.

But If  you include datafiles keyword then, the associated datafiles will also be deleted from the disk.

SQL>drop tablespace ravi including contents and datafiles;

Temporary Tablespace
Temporary tablespace is used for sorting large tables. Every database should have one temporary tablespace. To create temporary tablespace give the following command.

SQL>create temporary tablespace temp tempfile ‘/u01/oracle/data/ravi_temp.dbf’ size 100M
   extent management local  uniform size 5M;

The extent management clause is optional for temporary tablespaces because all temporary tablespaces are created with locally managed extents of a uniform size.  The

AUTOALLOCATE clause is not allowed for temporary tablespaces.

Increasing or Decreasing the size of a Temporary Tablespace
You can use the resize clause to increase or decrease the size of a temporary tablespace. The following statement resizes a temporary file:

SQL>ALTER DATABASE TEMPFILE '/u02/oracle/data/lmtemp02.dbf' RESIZE 18M;

The following statement drops a temporary file and deletes the operating system file:

SQL> ALTER DATABASE TEMPFILE '/u02/oracle/data/lmtemp02.dbf' DROP  INCLUDING DATAFILES;

Tablespace Groups
A tablespace group enables a user to consume temporary space from multiple tablespaces. A tablespace group has the following characteristics:


Using a tablespace group, rather than a single temporary tablespace, can alleviate problems caused where one tablespace is inadequate to hold the results of a sort,

particularly on a table that has many partitions. A tablespace group enables parallel execution servers in a single parallel operation to use multiple temporary

tablespaces.

The view DBA_TABLESPACE_GROUPS lists tablespace groups and their member tablespaces.

Creating a Temporary Tablespace Group
You create a tablespace group implicitly when you include the TABLESPACE GROUP clause in the CREATE TEMPORARY TABLESPACE or ALTER TABLESPACE statement and the

specified tablespace group does not currently exist.

For example, if neither group1 nor group2 exists, then the following statements create those groups, each of which has only the specified tablespace as a member:

CREATE TEMPORARY TABLESPACE ravi_temp2 TEMPFILE '/u02/oracle/ravi/ravi_temp.dbf'
     SIZE 50M TABLESPACE GROUP group1;

ALTER TABLESPACE ravi_temp2 TABLESPACE GROUP group2;


Assigning a Tablespace Group as the Default Temporary Tablespace
Use the ALTER DATABASE ...DEFAULT TEMPORARY TABLESPACE statement to assign a tablespace group as the default temporary tablespace for the database. For example:

ALTER DATABASE sample DEFAULT TEMPORARY TABLESPACE group2;

Oracle DBA Architecture . Interview Questions & Answers

 Architecure of SGA(Shared Global Area) structure of components:


SGA Components:


1. Database buffer cache.
2. Shared pool.
3. Redo Buffer cache

Shared  global area is a group of shared memory area that is dedicated to oracle instance. 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 .

Shared pool buffercache contains three major areas:
Library Cache contains by parsing.

Parsing is two types.

1. Hard Parsing : First time sql statement coming that is called hard parsing and maintain the # code.
2. Soft Parsing: Existing sql statement coming then it is called as a soft parsing.

Library cache (parse SQL statement, cursor information and execution plan),

data dictionary cache (contains,user account information, cache, privilege user information, segments and extent information,data buffer cache for parallel execution message and control structure.


Oracle Database 11G New Feature for Oracle DBA:
==============================================

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)

What is the Difference Between Local Inventory and Global Inventory:
=============================================
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.

Basically two kind of inventories:
=====================================

 Local Inventory (also called as Oracle Home Inventory) and other is  Global Inventory (also called as Central Inventory).

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

Why I have multiple Global Inventory on a machine ?

This is  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.

What to do if my Global Inventory is corrupted ?

Dont 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 (Important real time scenerio)

./runInstaller -silent -attachHome -invPtrLoc $location_to_oraInst.loc
ORACLE_HOME=”Oracle_Home_Location” ORACLE_HOME_NAME=”Oracle_Home_Name”


RAC:
---------
./runInstaller -silent -attachHome -invPtrLoc $location_to_oraInst.loc
ORACLE_HOME=”Oracle_Home_Location” ORACLE_HOME_NAME=”Oracle_Home_Name”
CLUSTER_NODES=”{}”


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 


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.

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.

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.

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?

What is SGA_TARGET and SGA_MAX_SIZE ?

This parameter 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

This parameter 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=3GB, 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.

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.

Parameter 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 
  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
  Uses internal advisory predictions 
  STATISTICS_LEVEL must be set to TYPICAL 
  SGA_TARGET is dynamic 


 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

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. 

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


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.


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;


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.

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.

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.

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

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.


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.

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.

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.

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.

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.

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;

Explain Oracle Architecture?
-------------------------
Oracle Instance:
===============
Oracle instance  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 it 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. done here Everything 

Redo Log Buffer :
=================

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

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 non-shared 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:
================================
If any mandatory background process killed then instance terminated immediately.

CKPT, LGWR, SMON DBWn, PMON.

Optional background processes:
=============================
If any optional background process killed then instance not terminated immediately.

CTWR, RMAL,ASM , MMON,MMAN,ARCn, LMDn, RECO, CJQ0, LMON, Snnn, Dnnn, Pnnn, LCKn, QMNn

DBWn writes when: (Database writer writes the data from database buffer cache to datafiles in below given situvations)
================

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

Log Writer (LGWR) writes:   (Log writer writes the data from redo buffer cache to online redolog files in below given situvations)
============================
• At commit
• When 1/3rd full
• When there is 1 MB of redo
• Every 3 seconds
• Before DBWn writes


System Monitor (SMON) Responsibilities:

SMON will be takecare by Rollforward & Rollbackward

• Instance recovery
– Rolls forward changes in redo logs (Like saved the data)
– Opens database for user access
– Rolls back uncommitted transactions (Like delete)
• 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

Why do you run orainstRoot and ROOT.SH once you finalize at end of 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.