You are on page 1of 71

##################find all the tables which contain emp no as comman

column##########################

select
* from "sys"."user_tab_cols"
where column_name = 'emp_no'

----------------------database startup time---------------------------------


select
substr(instance_number,1,3) ins,/

substr(upper(instance_name),1,10) database,
to_char(startup_time,'dd/mm/yyyy hh24:mi:ss') starttime
from v$instance
/

select sys_context('userenv', 'os_user') from dual;

select sys_context('userenv', 'ip_address') from dual;

the operating system identifier for the client of the current session
select sys_context('userenv', 'terminal') from dual;

name of the host machine from which the client has connected.
select sys_context('userenv', 'host') from dual;

##################################-memory tuning-
#######################################
---------------comments:------------------
user_tab_comments
user_col_comments

**************tblspace fragmentation***********************

select tablespace_name, bytes, blocks


from dba_free_space
where tablespace_name='users';

----------------------------------------------------------------------

select a.tablespace_name, a.allocated, b.freespace,


decode(greatest(a.allocated,500), 500, round(b.freespace-200),
decode(greatest(a.allocated,20480), a.allocated,
round(b.freespace-4096),
round(b.freespace
-(a.allocated*.2)))) warning
from (select tablespace_name ,sum(bytes)/1024/1024 allocated
from dba_data_files
group by tablespace_name) a ,
(select tablespace_name,sum(bytes)/1024/1024 freespace
from dba_free_space
group by tablespace_name) b
where a.tablespace_name = b.tablespace_name

-------------------------------------- --------------------------------------
------------------
-----------------------used space for each oracle user--------------------------
select substr(owner,1,16) owner,
substr(tablespace_name,1,26) tablespace_name,
substr(segment_type,1,10) segment_type,
sum(bytes) bytes,
sum(blocks) blocks
from sys.dba_extents
where owner in ('abc','steve','mohan','usrx','myref','rept')
group by
substr(owner,1,16),
substr(tablespace_name,1,26),
substr(segment_type,1,10)
order by 1,2,3
/

----------------------------------------------------------------------------------
--------------
memory usage
shared pool memory usage notes:

owner - owner of the object


object - name/namespace of the object
sharable memory - amount of sharable memory in the shared pool consumed by the
object

--break on owner on report


compute sum of "memory" on report

select substr(owner,1,12) owner,


substr(name||' - '||type,1,50) object,
sharable_mem "memory "
from v$db_object_cache
where
owner in ('steve','usrx','myref','rept')
and sharable_mem > 10000
and type in ('package','package body','function','procedure')
group by owner,name,type,sharable_mem
order by sharable_mem desc
/

------------------imp----------------------------------------------------
loads
loads into shared pool notes:

owner - owner of the object


object - name/namespace of the object
loads - number of times the object has been loaded. this count also increases when
an object has been invalidated.

select substr(owner,1,10) owner,


substr(name||' - '||type,1,55) object,
loads
from v$db_object_cache
where
owner in ('steve','usrx','myref','rept')
and loads > 3
and type in ('package','package body','function','procedure')
order by loads desc
/

------------------imp----------------------------------------------------
executions
shared pool execution notes:

owner - owner of the object


object - name/namespace of the object
executions - total number of times this object has been executed

select substr(owner,1,10) owner,


substr(name,1,25)||' - '||substr(type,1,25) object,
substr(executions,1,12) executions,
sharable_mem mem_used
from v$db_object_cache
where
owner in ('abc','steve','rept','usrx')
and executions > 100
and type in ('package','package body','function','procedure')
order by executions desc
/

select substr(owner,1,10) owner,


substr(type,1,12) type,
substr(name,1,25) name,
executions,
sharable_mem mem_used
--substr(kept||' ',1,4) "kept?"
from v$db_object_cache
where
owner in ('abc','steve','rept','usrx')
and type in ('trigger','procedure','package body','package')
and executions > 100
order by executions desc;

-------------------sql area
details------------------------------------------------
select
substr(sql_text,1,300) sql_txt,
substr(executions,1,4) exec,
substr(buffer_gets,1,5) bfgets,
substr(disk_reads,1,5) bgreads,
substr(rows_processed,1,5) rowpros,
--substr(sorts,1,5) sort,
--substr(address,1,10) addr,
--substr(first_load_time,1,15) frst_load,
--substr(hash_value,1,5) hashval,
substr(module,1,10) modul
from v$sqlarea
where executions >20
and module like 'pl/sql dev%'
order by executions desc
/

-----------------------------------------------------------------------------
disk intensive sql
sql with most disk read notes:

username - name of the user


disk reads - total number of disk reads for this statement
executions - total number of times this statement has been executed
reads/execs - number of reads per execution
sql text - text of the sql statement requiring the cursor, or the pl/sql anonymous
code

select substr(a.username,1,10) username,


substr(osuser,1,25) osusr,
sid "sid",
substr(disk_reads,1,7) disk_reads,
substr(executions,1,5) executions,
substr(round(disk_reads / decode(executions,0,1,executions)),1,5)
"reads/execs",
--substr(sql_text,1,150) sql_text
from dba_users a, v$, v$sqlarea
where parsing_user_id=user_id
and a.username in ('steve')
--and a.username not in ('sys','system')
and address=sql_address(+)
and disk_reads > 10000
order by disk_reads desc, executions desc
/
--------------------------------------------------------------------------
open cursors by user
open cursors by user notes:

username - name of user


sql text - text of the sql statement requiring the cursor, or the pl/sql anonymous
code

set line 300


set pagesize 80
select substr(nvl(username,'oracle proc')||'('||s.sid||')',1,12) username,
substr(osuser,1,25) osuser,
--substr(machine,1,20) machine,
substr(sql_text,1,250) sql_text
from v$open_cursor oc,
v$session s
where s.saddr = oc.saddr
and osuser not in ('sys','system')
order by substr(osuser,1,25)
/

-------------------------------------- --------------------------------------
running cursors by user
running cursors by user notes:

username - name of user


sql text - text of the sql statement requiring the cursor, or the pl/sql anonymous
code

set line 300


set pagesize 85
select substr(nvl(username,'oracle proc')||'('||s.sid||')',1,12) username,
substr(osuser,1,20) osuser,
--substr(machine,1,20) machine,
sql_text sql_text
from v$open_cursor oc, v$session s
where s.sql_address = oc.address
and s.sql_hash_value = oc.hash_value
order by substr(osuser,1,25)
/

-------------------------------------- --------------------------------------

cursor usage by session


cursor usage by session notes:

username - name of the user


recursive calls - total number of recursive calls
opened cursors - total number of opened cursors
current cursors - number of cursor currently in use

select user_process username,


0 --machine,
user_nm,
prog,
"recursive calls",
"opened cursors",
"current cursors"
from (
select substr(nvl(ss.username,'oracle proc')||'('||se.sid||') ',1,15)
user_process,
--substr(ss.machine,1,25) machine,
substr(ss.osuser,1,25) user_nm,
substr(ss.program,1,20) prog,
sum(decode(name,'recursive calls',value)) "recursive calls",
sum(decode(name,'opened cursors cumulative',value)) "opened cursors",
sum(decode(name,'opened cursors current',value)) "current cursors"
from v$session ss,
v$sesstat se,
v$statname sn
where se.statistic# = sn.statistic#
and (name like '%opened cursors current%'
or name like '%recursive calls%'
or name like '%opened cursors cumulative%')
and se.sid = ss.sid
and ss.username is not null
and ss.username not in ('sys','system')
and ss.status='inactive'
group by nvl(ss.username,'oracle proc')||'('||se.sid||')
',ss.machine,ss.osuser,ss.program
)
orasnap_user_cursors
order by "recursive calls" desc
--order by user_process,"recursive calls"
/

##################################-the sessions-
#######################################

###################finding sessions that have more than 50 cursors open

select sid,count(*)
from v$open_cursor
group by sid
having count(*) > 50
order by count(*) desc;

###################to check the long operations#####################

set space0;
select
substr(sid,1,4)sid,username,opname,substr(totalwork,1,7)totwrk,sofar,message from
v$session_longops
/

select sid,username,opname,totalwork,sofar,time_remaining,message from


v$session_longops
/

#######################--sessions--##############################
-----------user sessions----------------
select username, sid, serial#, process, status
from v$session
where username is not null
and osuser in('k?kannaiyan')
/

############################################################

column username format a15 word_wrapped


column module format a15 word_wrapped
column action format a15 word_wrapped
column client_info format a30 word_wrapped

select username||'('||sid||','||serial#||')' username,


substr(module,1,20),
substr(action,1,20)
client_info
from v$session
where module||action||client_info is not null
/
--------------joining v$session and v$sqlarea to obtain current session sql
--------

col username format a10


col machine format a10
col terminal format a10
col program format a20
select username, audsid, machine, terminal, program, sql_address
from v$session
where audsid=(select userenv('sessionid') from dual);

######################tracking the progress of long-running


query##########################
select * from
(select username,opname,sid,serial#,context,sofar,totalwork,
round(sofar/totalwork*100,2) "% complete"
from v$session_longops)
where "% complete" != 100

######################user loged (idle) in from more than one


hour##############################

set line 150


set pagesize 100
select
substr(sid,1,3) sid,
substr(serial#,1,5) slno,
substr(username,1,10) schema_nm,
substr(osuser,1,22) user_nm,
substr(machine,1,22) machine_nm,
substr(program,1,17) prog,
to_char(logon_time,'dd/mm/yyyy hh24:mi:ss am') logon,
substr(trunc(last_call_et/3600,2)||' hrs ',1,10) idle_time
--substr(last_call_et,1,10) last_call
from v$session
where
last_call_et>3600
and username is not null
and status='inactive'
and status <> 'killed'
and program like 'plsql%'
--and program like 'dllhost.exe%'
--and program like 'aspnet_wp.exe%'
order by last_call_et desc;

##################################################################################
########

--------------pertcular user-------------------

select 'alter system kill session ''' || sid || ',' || serial# || ''';'
from v$session
where
username is not null
and osuser in('p?deshpande')
and status='inactive'
and program like 'plsql%'

/
####################################-killing the sessions-
#################################

select 'alter system kill session ''' || sid || ',' || serial# || ''';'
from v$session
where
username is not null
username in ('pradeep')
and status <> 'killed'
and program like 'plsql%'
order by last_call_et desc
/

##################################################################################
##########

select 'alter system kill session ''' || sid || ',' || serial# || ''';'
from v$session
where
machine like 'pj\snakka%'
and status='inactive'
and status <> 'killed'
order by username
/

##################################################################################
########

select
substr(sid,1,3) sid,
substr(serial#,1,5) slno,
substr(username,1,10) schema_nm,
substr(osuser,1,22) user_nm,
substr(machine,1,22) machine_nm,
substr(program,1,17) prog,
to_char(logon_time,'dd/mm/yyyy hh24:mi:ss am') logon
--substr(trunc(last_call_et/3600,2)||' hrs ',1,10) idle_time
--substr(last_call_et,1,10) last_call
from v$session
where
--last_call_et > 3600
--username is not null
username in ('rept')
and machine like 'pj\%'
and status='inactive'
and status <> 'killed'
--and program like 'plsql%'
--and program like 'dllhost.exe%'
--and program like 'aspnet_wp.exe%'
order by username
/
break on c.table_name on report

break on c.table_name on report

break on c.constraint_name,1,25 on report

break on c.table_name,c.constraint_name,substr(c.column_name,1,25) on report

compute sum of con on report


############################max sessions(score) details for each
user###########################

break on user_nm on report


compute sum of con on report
select
substr(machine,1,30) machine_nm,
substr(osuser,1,30) user_nm,
count(*) con
from v$session
where
username is not null
and status='inactive'
group by substr(machine,1,30),substr(osuser,1,30)
order by con desc
/

############################max sessions(score) details for specified


user###########################

select
substr(machine,1,30) machine_nm,
substr(osuser,1,30) user_nm,
count(*) con
from v$session
where
username is not null
and osuser in('s?tadikonda')
and status='inactive'
group by substr(machine,1,30),substr(osuser,1,30)
order by con desc
/

#######################it will gives you the


username,systemid,rating##############################

select nvl(s.username, 'oracle process')username,


s.sid,
s.fixed_table_sequence
from v$session s
where s.type = 'user'
and rownum <= 20
order by 3 desc;
################### program wise user wise count ###########################

break on program on report skip 1


compute sum of noofusr on report
compute sum of noofusr on program
select
substr(osuser,1,23) user_nm,
substr(machine,1,30) machine_nm,
substr(nvl(program,'no program'),1,17) program,
count(*) noofusr
from v$session
where
username is not null
and status='inactive'
--and program like 'plsql%'
and username not in ('sys','system')
group by osuser,machine,program
order by program,count(*) desc
/

######################## sessions order by program


#############################

set line 250


set pagesize 100
break on program skip 1
select
substr(sid,1,3) sid,
substr(serial#,1,5) slno,
substr(username,1,8) schema_nm,
substr(osuser,1,23) user_nm,
substr(machine,1,23) machine_nm,
substr(program,1,17) program,
substr(to_char(logon_time,'dd/mm/yyyy hh24:mi:ss'),1,20) login_time
--trunc(24*((sysdate-logon_time) - trunc(sysdate-logon_time)))||' hour(s), ' ||
-- mod(trunc(1440*((sysdate-logon_time) - trunc(sysdate-logon_time))), 60)
||' minute(s), ' ||
-- mod(trunc(86400*((sysdate-logon_time) - trunc(sysdate-logon_time))), 60)
||' seconds' login_time
--substr(to_char(sysdate,'dd/mm/yyyy hh24:mi:ss'),1,20) cur_time,
--substr(trunc(((86400*(sysdate-logon_time))/60)/60)-24*(trunc((((86400*(sysdate-
logon_time))/60)/60)/24)),1,3)hrs,
--substr(trunc((86400*(sysdate-logon_time))/60)-60*(trunc(((86400*(sysdate-
logon_time))/60)/60)),1,3)mnt
--sysdate-logon_time id
from v$session
where
username is not null
and status='inactive'
and program like 'plsql%'
--and program like 'dllhost.exe%'
--and status= 'sniped'
and username not in ('sys','system')
--order by osuser,logon_time
order by program,osuser,login_time
/
########################schema wise active and inactive
count###################################
compute sum of "active" on report
compute sum of "inactive" on report
compute sum of "total" on report

select
substr(nvl(username,'[b.g. process]'),1,15) schema_name,
sum(decode(nvl(status,'active'), 'active', 1, 0 )) +
sum(decode(nvl(status,'inactive'), 'inactive', 1, 0 )) "total",
sum(decode(nvl(status,'active'), 'active', 1, 0 )) "active",
sum(decode(nvl(status,'inactive'), 'inactive', 1, 0 )) "inactive"
from v$session
where
username is not null
and username not in ('sys','system')
group by username
order by username
/

#####################total users and sessions active and


inactive#####################

select s.status "status",


s.serial# "serial#",
s.type "type",
s.username "db user",
s.osuser "client user",
s.server "server",
s.machine "machine",
s.module "module",
s.client_info "client info",
s.terminal "terminal",
s.program "program",
p.program "o.s. program",
s.logon_time "connect time",
lockwait "lock wait",
si.physical_reads "physical reads",
si.block_gets "block gets",
si.consistent_gets "consistent gets",
si.block_changes "block changes",
si.consistent_changes "consistent changes",
s.process "process",
p.spid, p.pid, si.sid, s.audsid,
s.sql_address "address", s.sql_hash_value "sql hash", s.action
from
v$session s,
v$process p,
sys.v_$sess_io si
where
s.paddr = p.addr(+)
and si.sid(+)=s.sid
order by 3

------------------------------user sessions
type----------------------------------------------------------
break on report
compute sum of num_user_sess count_a count_i on report

select
lpad(nvl(sess.username, '[b.g. process]'), 15) username
, count(*) num_user_sess
, nvl(act.count, 0) count_a
, nvl(inact.count, 0) count_i
from
v$session sess
, (select count(*) count, nvl(username, '[b.g. process]') username
from v$session where status = 'active' group by username) act
, (select count(*) count, nvl(username, '[b.g. process]') username
from v$session where status = 'inactive'group by username) inact
where
nvl(sess.username, '[b.g. process]') = act.username (+)
and nvl(sess.username, '[b.g. process]') = inact.username (+)
and sess.status in ('active','inactive')
group by sess.username , act.count , inact.count
/

--------------more than one sessions------------------------------

select sid,serial#,
--user#,
substr(username,1,10) usr,
--status,server,
substr(osuser,1,20) osusr,
substr(machine,1,20) macname,
substr(terminal,1,20) trmnl,
substr(program,1,12) prg,
to_char(logon_time,'dd/mm/yyyy hh24:mi:ss') dt
from v$session
where
status ='inactive'
and username in (select username from v$session group by username having
count(username)>1)
and logon_time=(select max(logon_time) from v$session);

###############sql statement of perticular user#######################

select sid, schemaname, osuser,


substr(machine,1,20) machine
from v$session order by schemaname

select sql_text
from v$sqlarea
where (address, hash_value)
in(select sql_address,sql_hash_value from v$session where sid = &sid_number);

#########################################################################
select file_name,phyrds,phywrts,decode(phyrds,0,0,phyblkrd/phyrds) �blocks/read�
decode(phywrts,0,0,phyblkwrt/phywrts) �blocks/write�
from dba_data_files, v$filestat
where dba_data_files.file_id=v$filestat.file#;

select substr(sn.name,1,30) parameter,ss.username ||� (�|| se_sid ||�) �


user_process, se.value
from v$session ss, v$sesstat se, v$statname sn#where se. statistic# =
sn.statistic# and sn.name like �%cpu used by this session%� and se.sid=ss.sid
order by sn.name, se_value desc;

select 'alter ||'object_type'||'owner'||'.'||'object_name'||'move tablespace


steveusrx ;'
from user_objects
wher owner in('usrx')
and object_type in('index');

alter user usrx quota 0 on users;

#################################################################################
--------------username and sql text---------------------------------------------

select osuser, username, sql_text


from v$session a, v$sqltext b
where a.sql_address =b.address
order by address, piece

-------------------sessions order by highest physical


reads-----------------------------
set line 300
set pagesize 80
select
--substr(p.spid,1,4) spid ,
----substr(p.pid,1,3) pid,
substr(si.sid,1,3) sid ,
substr(s.audsid,1,4) usid,
substr(s.serial#,1,5) "serial#",
--substr(s.type,1,5) "type",
substr(s.username,1,7) "db user",
substr(s.osuser,1,22) "client user",
--substr(s.server,1,15) "server",
--substr(s.machine,1,22) "machine",
--substr(s.module,1,20) "module",
--substr(s.client_info,1,15) "client info",
--substr(s.terminal,1,15) "terminal",
substr(s.program,1,18) "program",
--substr(p.program,1,15) "o.s. program",
to_char(s.logon_time,'dd/mm/yyyy hh24:mi:ss') "connect time",
--substr(lockwait,1,4) "l w",
substr(si.physical_reads,1,8) "p r",
substr(si.block_gets,1,4) "b g",
substr(si.consistent_gets,1,8) "c g",
substr(si.block_changes,1,4) "b c"
--si.consistent_changes "consistent changes",
--s.process "process",
--s.sql_address "address",
--s.sql_hash_value "sql hash",
--s.action,
--to_char(sysdate - (s.last_call_et / 86400),'dd/mm/yyyy') "last call"
from v$session s, v$process p, sys.v_$sess_io si
where s.paddr = p.addr(+)
and si.sid(+) = s.sid
and s.status in ('inactive')
and (s.username is not null)
and (nvl (s.osuser, 'x') <> 'system')
and (nvl (s.username, 'x') <> 'system')
and (s.type <> 'background')
and si.physical_reads >=1000
order by si.physical_reads desc
/
-------------------------------------------------------------------------
----------who uses what details----------------------------------------
break on "owner" on report
select
sid "sid",
substr(owner,1,15) "owner",
substr(object,1,25) "object"
from v$access
where
owner in ('usrx')
order by owner
/

-----------------lists all tables with their pk columns that are referred as fk in


other tables----------------

select ucc.table_name, ucc.column_name


from user_constraints uc, user_cons_columns ucc
where uc.constraint_name
in (select r_constraint_name
from user_constraints
where constraint_type='r')
and uc.table_name=ucc.table_name
and uc.constraint_name=ucc.constraint_name

-------following query may be used to check parent and child


--------------------------

select parent_qry.table_name pk_table, parent_qry.column_name pk_column,


child_qry.table_name fk_table, child_qry.column_name fk_column
from
(select uc.constraint_name,ucc.table_name, ucc.column_name
from user_constraints uc, user_cons_columns ucc
where uc.constraint_name
in (select r_constraint_name
from user_constraints
where constraint_type='r')
and uc.table_name=ucc.table_name
and uc.constraint_name=ucc.constraint_name) parent_qry,
(select uc.r_constraint_name,ucc.table_name, ucc.column_name
from user_constraints uc, user_cons_columns ucc
where uc.constraint_name
in (select constraint_name
from user_constraints
where constraint_type='r')
and uc.table_name=ucc.table_name
and uc.constraint_name=ucc.constraint_name) child_qry
where parent_qry.constraint_name=child_qry.r_constraint_name

-------------------row locks details-----------------------------------------


select
s.username,
s.sid,
o.owner,
o.object_name,
a.sql_text,
s.row_wait_file#,
s.row_wait_block#,
s.row_wait_row#
from v$session s, v$sqlarea a, dba_objects o
where o.object_id = s.row_wait_obj#
and s.sql_address = a.address
and s.row_wait_obj# > 0
/
----------------------high cpu usage in this sessions---------------------
select
substr(ss.username||'('||se.sid||')',1,15) user_process,
substr(ss.osuser,1,23) user_nm,
substr(ss.machine,1,23) machine_nm,
substr(ss.program,1,17) program,
value
from v$session ss, v$sesstat se, v$statname sn
where se.statistic# = sn.statistic#
and name like '%cpu used by this session%'
and se.sid = ss.sid
and ss.username is not null
and ss.status in ('inactive')
and ss.username not in ('sys','system')
and value >=10
order by substr(name,1,25), value desc
/

---------------------to analyze the table -------------------------------


select 'analyze table '||table_name||' estimate statistics;' from cat where
table_type='table'
--and table_name like 'ptadv001gt%'
/
analyze table ptadv001gt estimate statistics;

---------------- to analyze all the tables and indexes of a schema


-----------------

select ' exec dbms_stats.gather_table_stats (ownname=>'||chr(39)||owner||


chr(39)||',tabname=>'||chr(39)||table_name||chr(39)||',
degree=>8,estimate_percent=>40,cascade=>true);' from dba_tables where
owner='steve'

--------------------if the table size is greater than 10 mb in size, statistics


are estimated.

select 'analyze table '||owner||'.'||table_name||' '||


decode(sign(10485760 - initial_extent),1,'compute statistics;','estimate
statistics;')
from sys.dba_tables
where owner in ('usrx')
/
------------------analyzed talbes details---------------------
select
substr(owner,1,10) owner,
sum(decode(nvl(num_rows,9999), 9999,0,1)) "tables analyzed",
sum(decode(nvl(num_rows,9999), 9999,1,0)) "tables not analyzed",
count(table_name) total
--sum(decode(nvl(num_rows,9999), 9999,0,1)) + sum(decode(nvl(num_rows,9999),
9999,1,0)) "total tables"
from all_tables
where owner in ('steve')
group by owner
/
------------------or---------------------------------------------------
select substr(owner,1,10) owner,
sum(decode(nvl(num_rows,9999), 9999,0,1)) analyzed,
sum(decode(nvl(num_rows,9999), 9999,1,0)) not_analyzed,
count(table_name) total
from dba_tables
where owner in ('steve')
group by owner;

----------------------------------------------------------------------------------
------
query for recently analyzed tables

select substr(owner,1,10) owner,


substr(table_name,1,25) table_name,
to_char(last_analyzed,'mm/dd/yyyy hh24:mi:ss') lastanalyzed
from dba_tab_columns
where owner in ('steve')
and last_analyzed is not null
and column_id=1
--and (sysdate-last_analyzed) < 2
and to_char(last_analyzed,'mm/dd/yyyy') >= '10/17/2005'
order by (sysdate-last_analyzed);
------------------------------------------------------------------------------
query for tables not analyzed

select
--substr(owner,1,15) owner,
substr(table_name,1,25) table_name,
last_analyzed last_analyzed
from
dba_tables
where
owner in ('rept')
and last_analyzed is null
--and last_analyzed < ('15-oct-05')
--and (sysdate-last_analyzed) < 30
order by table_name
--order by (sysdate-last_analyzed)
/

----------------table created dates details-------------------------------

select substr(object_name,1,25) table_name,


substr(to_char(created,'mm/dd/yyyy hh24:mi:ss'),1,25) created_datetime,
substr(to_char(last_ddl_time,'mm/dd/yyyy hh24:mi:ss'),1,25) modified_datetime ,
status
from dba_objects
where
owner='rept'
and object_type in ('table')
--and object_name like 'cltst%'
and to_char(created,'mm/dd/yyyy')>='10/20/2005'
--and to_char(created,'mm/dd/yyyy') <> to_char(last_ddl_time,'mm/dd/yyyy')
order by created desc
/

----------------------table modified dates details-------------------------

select substr(object_name,1,25) table_name,


substr(to_char(created,'mm/dd/yyyy hh24:mi:ss'),1,25) created_datetime,
substr(to_char(last_ddl_time,'mm/dd/yyyy hh24:mi:ss'),1,25) modified_datetime ,
status
from dba_objects
where
owner='steve'
and object_type in ('table')
--and object_name like 'adfcd001lt'
and to_char(last_ddl_time,'mm/dd/yyyy')='11/28/2005'
order by last_ddl_time desc
/

----------------------find user who modified table-------------------------


select s.sid,substr(d.object_name,1,25) table_name,
substr(to_char(d.created,'mm/dd/yyyy hh24:mi:ss'),1,25) created_datetime,
substr(to_char(d.last_ddl_time,'mm/dd/yyyy hh24:mi:ss'),1,25) modified_datetime ,
d.status
from dba_objects d,v$session s
where
d.owner='steve'
and object_type in ('table')
--and object_name like 'adfcd001lt'
and to_char(d.last_ddl_time,'mm/dd/yyyy') between '02/27/2006' and '02/28/2006'
and d.object_name!='ptpmt002gt'
and d.owner=s.username
order by last_ddl_time desc

------------------------tables with no data--------------------------------


sql> select
2 substr(owner,1,10) owner,
3 substr(table_name,1,35) tab,
4 num_rows,
5 empty_blocks
6 from dba_tables
7 where owner in ('steve_prod')
8 and num_rows <=0
9 order by table_name
10 /
---------------------------------------------
select
substr(owner,1,10) owner,
substr(table_name,1,35) tab,
num_rows,
substr(blocks,1,5) block,
empty_blocks,
substr(avg_space,1,5) avg_space,
--substr(chain_cnt,1,5) chain,
substr(avg_row_len,1,5) avg_row,
last_analyzed
from dba_tables
where owner in ('steve_prod')
and last_analyzed is not null
and num_rows <=0
order by table_name
/

----------------------------to display tabel info with no of rows----------------

select substr(t.owner,1,10) town,


substr(t.table_name,1,25) tname,
substr(decode(t.tablespace_name,null,'partitioned',t.tablespace_name),1,10)
tspace,
substr((t.initial_extent / 1024),1,5) iext,
substr((t.next_extent / 1024),1,5) next,
substr(t.pct_increase,1,5) pcti,
substr(t.num_rows,1,5) nrows,
substr(t.blocks,1,5) blks,
substr(t.chain_cnt,1,5) chr,
substr(decode(t.cache, 'n', 'no','y', 'yes','no'),1,5) cach
from dba_tables t
where t.owner = upper('steve')
and t.num_rows>0
and t.table_name like upper('adrp')||'%'
order by t.table_name;
/
-----------------------comments on
tables---------------------------------------------

set line 350


set pagesize 80
select
substr(table_name,1,15) table_name,
substr(comments,1,300) table_comments
from dba_tab_comments
where owner in ('steve' )
and table_type in ('table')
and table_name like 'adfcd001lt'
and comments is not null
order by 1
/

---------------- this script reports the table that is highly fragmented


-------------------

select
substr(segment_name,1,25) table_name , count(*) extents
from dba_segments
where upper(owner) in upper('steve')
group by segment_name
having count(*) = (select max( count(*) )
from dba_segments
group by segment_name)
/

==================================high water mark of


tables==============================

rem script description: this script determines highwater mark of tables.


rem it is essential to run analyze_schema utility or analyze
table
rem commands before running this script for accurate
statistics.
rem
rem it displays all the tables whose high water mark <> no# of
used
rem blocks.

select
substr(a.owner,1,10) owner,
substr(a.table_name,1,20) table_name,
b.blocks allocblks,
a.blocks usedblks,
(b.blocks-a.empty_blocks-1) highwtr
from dba_tables a, dba_segments b
where a.table_name=b.segment_name
and a.owner=b.owner
and a.owner in('steve')
and a.blocks <> (b.blocks-a.empty_blocks-1)
--and a.table_name like upper('adrp')||'%'
order by 1,2 ;

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

rem script description: this query finds sql statements which access database
rem buffers a lot. such statements are typically heavy on cpu
usage
rem because they are probably looking at a lot of rows of
data.

select
substr(username,1,10),
substr(address,1,10) address,
hash_value,
buffer_gets,
executions,
buffer_gets/executions "gets/exec",
substr(sql_text,1,150) sqltext
from v$sqlarea,dba_users
where
username not in ('sys','system')
and buffer_gets > 50000
and executions > 0
and v$sqlarea.parsing_user_id = dba_users.user_id
order by 4 desc;
------------------------------monitoring rollback progress-------------------
select t.used_ublk, t.used_urec
from v$session s, v$transaction t
where s.taddr=t.addr
and s.sid =:sid;

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

rem script description: this script produces a report which describes the indexed
columns
rem for each index of each table of a specified schema. the
user is
rem prompted from the schema name when the script is run. the
indexes
rem for each table are listed on a separate page.

break on table_name skip page on index_name skip 1;

select
substr(i.index_owner ||'.'|| i.index_name,1,35) index_name,
--substr(i.table_owner,1,10) tab_owner,
substr(i.table_name,1,25) tab_name,
substr(i.column_name,1,25) col_nm,
substr(i.column_position,1,3) pos,
substr(i.column_length,1,5) length
--substr(t.data_type,10) data_type
from all_ind_columns i, all_tab_columns t
where table_owner = upper('steve')
and t.owner = i.table_owner
and t.table_name = i.table_name
and t.column_name = i.column_name
and i.table_name like upper('adr')||'%'
order by i.table_name, i.index_name;

--------------------------primary keys details----------------------------------

=======================================================================
/* script description: this script will identify large anonymous blocks of pl/sql
that should be replaced with
packaged procedures and pinned

set lines 132 pages 1000;

select loads,version_count,executions,sql_text
from v$sqlarea
where command_type=47
and length(sql_text) > 250;

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

rem script description: this script identifies pertinent information for jobs
scheduled through oracle.

select
substr(job,1,10) job,
--substr(log_user,1,10) log_usr,
--substr(priv_user,1,10) prv_usr,
substr(schema_user,1,10) sch_usr,
to_char(last_date, 'dd/mm/yy hh24:mi') last,
to_char(next_date, 'dd/mm/yy hh24:mi:ss') next,
substr(interval,1,20) interval,
substr(broken,1,20) broken,
substr(failures,1,20) failures,
substr(what,1,30) what
from dba_jobs
order by job;

spool off;
===================================================================
----------------this simple script lists all tables that do not have any indexes.
select owner, table_name
from all_tables
where owner in ('steve')
minus
select owner, table_name
from all_indexes;

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

---------------------database size in gb---------------------------


select
trunc(a.data_size+b.temp_size+c.redo_size,2) "total_size in gb"
from ( select sum(bytes)/1024/1024/1024 data_size
from dba_data_files ) a,
( select nvl(sum(bytes),0)/1024/1024/1024 temp_size
from dba_temp_files ) b,
( select sum(bytes)/1024/1024/1024 redo_size
from sys.v_$log ) c
/
----------to know the table space details and free space in mb ---------

compute sum of total on report


compute sum of free on report
compute sum of used on report

break on report

select substr(a.tablespace_name,1,13) tablespace,


round(sum(a.total1)/1024/1024, 1) total,
round(sum(a.total1)/1024/1024, 1)-round(sum(a.sum1)/1024/1024, 1) used,
round(sum(a.sum1)/1024/1024, 1) free,
round(sum(a.sum1)/1024/1024, 1)*100/round(sum(a.total1)/1024/1024, 1) pct_free,
round(sum(a.maxb)/1024/1024, 1) largest,
max(a.cnt) fragment
from
(select tablespace_name, 0 total1, sum(bytes) sum1,
max(bytes) maxb,
count(bytes) cnt
from dba_free_space
group by tablespace_name
union
select tablespace_name, sum(bytes) total1, 0, 0, 0 from dba_data_files
group by tablespace_name) a
group by a.tablespace_name
/
----------------schema size--------------------------
select substr(tablespace_name,1,10) table_space,
sum(bytes)/1024/1024/1024 as total_size_gb
from dba_segments
where owner in ('myref')
group by owner
, rollup(tablespace_name)
/

-----------------to know the table space details and free space in


gb----------------------

compute sum of total on report


compute sum of free on report
compute sum of used on report

break on report

select substr(a.tablespace_name,1,13) tablespace,


round(sum(a.total1)/1024/1024/1024, 1) total,
round(sum(a.total1)/1024/1024/1024, 1)-round(sum(a.sum1)/1024/1024/1024, 1) used,
round(sum(a.sum1)/1024/1024/1024, 1) free,
round(sum(a.sum1)/1024/1024, 1)*100/round(sum(a.total1)/1024/1024, 1) pct_free,
round(sum(a.maxb)/1024/1024, 1) largest,
max(a.cnt) fragment
from
(select tablespace_name, 0 total1, sum(bytes) sum1,
max(bytes) maxb,
count(bytes) cnt
from dba_free_space
group by tablespace_name
union
select tablespace_name, sum(bytes) total1, 0, 0, 0 from dba_data_files
group by tablespace_name) a
group by a.tablespace_name
/
--------------------or-----------------------------------------------
break on report
compute sum of kbytes on report
compute sum of free on report
compute sum of used on report
select
nvl(b.tablespace_name,nvl(a.tablespace_name,'unkown')) name
, kbytes_alloc kbytes
, kbytes_alloc-nvl(kbytes_free,0) used
, nvl(kbytes_free,0) free
, ((kbytes_alloc-nvl(kbytes_free,0))/kbytes_alloc)*100 pct_used
, nvl(largest,0) largest
from ( select sum(bytes)/1024 kbytes_free
, max(bytes)/1024 largest
, tablespace_name
from sys.dba_free_space
group by tablespace_name
) a
, ( select sum(bytes)/1024 kbytes_alloc
, tablespace_name
from sys.dba_data_files
group by tablespace_name
) b
where a.tablespace_name (+) = b.tablespace_name
/
----------------------database growth -------------------------------
select
to_char(creation_time, 'rrrr month') "month"
, sum(bytes)/1024/1024 "growth in meg"
from
sys.v_$datafile
where creation_time > sysdate-365
group by to_char(creation_time, 'rrrr month');

====================================================================
--------------to display all objects count of schema------------------------
select substr(u.name,1,10) "user",
substr(sum(decode(o.type#, 2, 1, 0 )),1,6) tables,
substr(sum(decode(o.type#, 3, 1, 0 )),1,6) clust,
substr(sum(decode(o.type#, 1, 1, 0 )),1,8) indexes,
substr(sum(decode(o.type#, 4, 1, 0 )),1,6) views,
substr(sum(decode(o.type#, 5, 1, 0 )),1,6) syn,
substr(sum(decode(o.type#, 6, 1, 0 )),1,6) seq,
substr(sum(decode(o.type#, 7, 1, 0 )),1,6) proc,
substr(sum(decode(o.type#, 8, 1, 0 )),1,6) func,
substr(sum(decode(o.type#, 9, 1, 0 )),1,6) pkg,
substr(sum(decode(o.type#, 12, 1, 0 )),1,6) trig
from sys.obj$ o,
sys.user$ u
where owner# = u.user#
and u.name in ('steve')
group by u.name ;

==================================================================================
=======
---------to know the table details like datatype ----------------------
break on tnam skip 1
select substr(tc.table_name,1,30) tnam,
substr(tc.column_id,1,3) cid,
substr(tc.column_name,1,20) tcol,
substr(tc.data_type,1,10) typ,
substr(tc.data_length,1,5) len,
substr(tc.data_precision,1,5) prc,
substr(decode(tc.nullable,'n','no','y','yes','no'),1,5) nul,
--substr(tc.num_distinct,1,5) dis,
--substr(tc.low_value,1,20) lv,
--substr(tc.high_value,1,20) hv,
-- substr(tc.density,1,20) dens,
-- tc.num_nulls nnul,
to_char(tc.last_analyzed,'mm/dd/yy hh24:mi:ss') analyzed_date
from dba_tab_columns tc
where tc.owner = upper('steve')
and tc.table_name like upper('adrpt')||'%'
order by 1 ;
==================================================================================
=========
-----------------tables with out primary key------------------------
select owner, table_name
from dba_tables a
where table_name not in
(select table_name
from dba_constraints
where owner=a.owner
and constraint_type='p')
and owner in ('steve')
order by owner;

---------data files information----------------------------------------

select
substr(tb.name,1,10) tsname,
substr(v.name,1,40) dfname,
substr(decode(f.status$, 1, 'invalid', 2, 'available', 'undefined'),1,12) status,
f.blocks
from file$ f, v$datafile v, v$tablespace tb
where f.blocks > 0
and f.file#=v.file#
and f.ts# = tb.ts#
order by 1,2 ;
==================================================================================
==============

-------to dispaly the jobs-------------------------

select substr(job,1,4) "job",


substr(log_user,1,5) "user",
substr(schema_user,1,5) "schema",
substr(to_char(last_date,'dd.mm.yyyy hh24:mi'),1,16) "last date",
substr(to_char(next_date,'dd.mm.yyyy hh24:mi'),1,16) "next date",
substr(broken,1,2) "b",
substr(failures,1,6) "failed",
substr(what,1,20) "command"
from dba_jobs;

----------data files inforamtion(imp)--------------------------------------------


break on table_space on report skip 1
compute sum of total on table_space
compute sum of free on table_space
compute sum of used on table_space
compute sum of used on report
compute sum of total on report
compute sum of free on report
select substr(a.tablespace_name,1,15) table_space,
substr(a.file_name,1,45) data_file,
a.avail total,
nvl(a.avail,0)-nvl(b.free,0) used,
nvl(b.free,0) free
-- nvl(round(((free/avail)*100),2),0) a5
from (select tablespace_name,
substr(file_name,1,45) file_name,
file_id,
round(sum(bytes/(1024*1024)),3) avail
from sys.dba_data_files
group by tablespace_name,
substr(file_name,1,45),
file_id) a,
(select tablespace_name,
file_id,
round(sum(bytes/(1024*1024)),3) free
from sys.dba_free_space
group by tablespace_name, file_id) b
where a.file_id = b.file_id (+)
order by 1, 2
/
----------------------------------------------------------------------------------
-----
select
substr(df.tablespace_name,1,12) tblsp_name,
substr(df.file_name,1,40) data_file,
substr(df. status,1,10) sta,
(df.bytes/1024000) tot,
(fs.s/df.bytes*100) fre,
substr(decode (ae.y,1,'yes','no'),1,3) a
from dba_data_files df,
(select file_id,sum(bytes) s
from dba_free_space
group by file_id) fs,
(select file#, 1 y
from sys.filext$
group by file#) ae
where df.file_id = fs.file_id
and ae.file#(+) = df.file_id
order by df.tablespace_name, df.file_id;

------------objecsts and table space details-------------------------------

select substr(owner,1,10) owner,


substr(tablespace_name,1,10) tablespace_name,
substr(segment_type,1,15) segment_type,
sum(bytes) bytes,
sum(blocks) blocks
from sys.dba_extents
where owner in ('abc','steve','mohan','usrx','myref')
group by
substr(owner,1,10),
substr(tablespace_name,1,10),
substr(segment_type,1,15)
order by 1,2,3;

----------------------tables and indexes in system table


space-------------------------------
select substr(owner,1,10) owner,
substr(segment_name,1,20) segment_name,
substr(segment_type,1,15) segment_type,
substr(tablespace_name,1,10) table_space
from dba_segments
where owner in ('rept')
and tablespace_name in ('users')
and segment_type in('table')
order by 2
/
------------------------------------------------------------------------------
--------------to find out which object is corrupted-------------
select segment_type, segment_name
from dba_extents
where file_id = 1
and block_id < 3840
and block_id + blocks >= 3840;
---------or--------------------
select segment_type, segment_name
from dba_extents
where file_id = 1
and 3840 between block_id and block_id + blocks -1;

----------------parameter file details--------------------------------------


set pagesize 9000
set head off
set term off

spool initparameters.ora

select
decode(isdefault, 'true', '# ')||decode(isdefault, 'true', rpad(name,43),
rpad(name,45))||' = '|| value
"parameter and value"
from v$parameter
--where upper(name) like '%shared%'
order by name;
spool off
==================================================================================
===============
------------------errors while creating proc,pkg and trig------------------------
select
substr(type,1,25) typ,
substr(owner,1,10) own,
substr(name,1,30) nm,
substr(sequence,1,3) seq,
substr(line,1,3) len,
substr(position,1,3) pos,
substr(text,1,150) || chr(10) || chr(10) text
from
dba_errors
where owner in ('steve')
order by 1, 2, 3
/
==================================================================================
===============
------------------------------tables,columns,datatyes and created
date--------------------------
set line 200
set pagesize 100

break on table_name skip 1


select substr(tc.table_name,1,30) table_name,
substr(tc.column_id,1,3) cid,
substr(tc.column_name,1,20) column_name,
substr(tc.data_type,1,10) data_type,
substr(tc.data_length,1,5) len,
substr(tc.data_precision,1,5) prc,
substr(decode(tc.nullable,'n','no','y','yes','no'),1,5) nul,
--substr(tc.num_distinct,1,5) dis,
--substr(tc.low_value,1,20) lv,
--substr(tc.high_value,1,20) hv,
-- substr(tc.density,1,20) dens,
-- tc.num_nulls nnul,
to_char(do.created,'mm/dd/yyyy hh24:mi:ss') created_date
--to_char(last_ddl_time,'mm/dd/yyyy hh24:mi:ss') modified_date,
--to_char(tc.last_analyzed,'mm/dd/yy hh24:mi:ss') analyzed_date
from dba_tab_columns tc,dba_objects do
where tc.owner = upper('steve')
and tc.table_name like upper('adfcd')||'%'
and tc.owner = do.owner
and do.object_type in ('table')
and tc.table_name=do.object_name
order by 1,2 ;

select count(*) from dba_tab_columns


where
owner in ('abc')
and table_name in ('adusr001mt');
----------------------------long running sql statements----------------------
alter session set sort_area_size=1048576;

col rows_processed form 9,999,990 head rows


col buffer_gets form 999,999,990
col executions form 999,999,990
col disk_reads form 99,999,990

set pages 60
set lines 132
set newpage 0

break on rows_processed on loads on executions on buffer_gets on disk_reads


ttitle 'long running sql statements'

select s.rows_processed, s.loads, s.executions, s.buffer_gets,


s.disk_reads, t.sql_text
from v$sql/*area*/ s,
v$sqltext t
where s.address = t.address
and ((buffer_gets > 10000000) or
(disk_reads > 1000000) or
(executions > 1000000))
order by ((s.disk_reads * 100) + s.buffer_gets) desc, t.address, t.piece
/

select c.executions,trunc(a.last_call_et/60) min,b.sql_text


from v$session a
,v$sqltext b
,v$sqlarea c
where
--a.sid=167
a.sql_address = b.address
and a.sql_address = c.address
order by b.piece;

-------tables with no rows----------------


select owner,table_name
from dba_tables
where num_rows = 0
and owner in ('abc')order by 1,2;
-------columns with no value-----------------
break on table_name skip 1
select
--substr(owner,1,10) owner,
substr(table_name,1,25) table_name,
substr(column_name,1,20) column_name
from dba_tab_columns
where num_distinct = 0
and owner in ('abc')
order by table_name
/
------------------temporary segments----------------------
select tablespace_name, segment_name, segment_type, sum(bytes), count(extent_id)
from dba_extents
where segment_type = 'temporary'
group by tablespace_name, segment_name, segment_type
/
set pages 999;

column pga_size format 999,999,999

select
a.value,b.value,2048576+a.value+b.value pga_size
from
v$parameter a,
v$parameter b
where
a.name = 'sort_area_size'
and
b.name = 'hash_area_size'
/
--------------temp segments---------------------
break on tablespace_name skip 1 on file_id skip 1

select tablespace_name, file_id, segment_name,segment_type, block_id, blocks


from dba_extents
where tablespace_name = 'temp'
order by file_id, block_id
/
break on tablespace on segfile#

select b.tablespace,b.segfile#,b.segblk#,b.blocks
from v$sort_usage b
/
select
a.tablespace,a.segfile#,a.segblk#,a.blocks,b.sid,b.serial#,b.username,b.osuser,b.s
tatus
from v$sort_usage a,v$session b
where a.session_addr = b.saddr
order by a.tablespace,a.segfile#,a.segblk#
/
select a.tablespace, b.sid, b.serial#, a.blocks,c.sql_text
from v$sort_usage a,v$session b,v$sqltext c
where a.session_addr = b.saddr
and b.sql_address = c.address
order by a.tablespace,b.sid,b.serial#,c.address, c.piece
/

select * from (select


username,opname,sid,serial#,context,sofar,totalwork
,round(sofar/totalwork*100,2) "% complete"
from v$session_longops)
where "% complete" != 100
/
select a.executions,
a.disk_reads,
a.disk_reads/a.executions dre,
a.

_gets,
a.buffer_gets/a.executions bge,
b.username,
a.first_load_time,
a.sql_text
from v$sql a, all_users b
where a.executions > 0
and a.parsing_user_id = b.user_id
and username not in ('sys','system')
order by 1 desc
/
select t.used_ublk, t.used_urec
from v$session s, v$transaction t
where s.taddr=t.addr
--and s.sid =:sid;

------------------to dispaly sequence and current value---------------------


------------------imp first analyze the tables before running this
script----------------
select
substr(b.table_name,1,30) tab,
--c.num_rows norows,
substr(a.sequence_name,1,30) seq,
substr(b.column_name,1,25) col,
substr(a.last_number,1,5) cur_val
from user_sequences a,
user_ind_columns b
--,user_tables c
where substr(a.sequence_name ,1,length(a.sequence_name)-4)=b.table_name
and b.index_name like '%pk%'
--and c.table_name = b.table_name
-- and a.sequence_name like 'cltst003dt%'
--and b.table_name like 'adalm001lt%'
order by b.table_name
/
----------------tables with out sequences
details----------------------------------

select distinct * from (


select
substr(b.table_name,1,30) tab
--substr(b.column_name,1,25) col
from user_ind_columns b,user_objects c
where
b.table_name = c.object_name
and object_type in ('table')
and substr(c.object_name,1,3) not in ('smp','vdk','vbz')
and b.table_name not in
(select substr(a.sequence_name,1,length(a.sequence_name)-4) from user_sequences a
where substr(a.sequence_name,1,length(a.sequence_name)-4)=b.table_name and
b.index_name is not null)
--and b.table_name like 'ad%'
order by b.table_name)
/
--------------temporary tables details-----------------------------------
select owner,table_name,last_analyzed
from dba_tables where owner in ('steve') and temporary ='y'

-----------------------------------------------------------------------------
------------total memory of all running sessions--------------------
select sum(se.value)||' bytes' "total memory for all sessions"
from v$sesstat se, v$statname n
where n.statistic# = se.statistic#
and n.name = 'session pga memory'
/
-------------session total waits and time waited----------------------
select substr(a.sid,1,5) "sid",
substr(a.process,1,7) "process",
substr(a.username,1,10) "user",
substr(a.osuser,1,23) user_nm,
substr(a.machine,1,23) machine_nm,
substr(a.program,1,17) program,
total_waits,
time_waited
from v$session_event v, v$session a
where v.event='db file scattered read'
and v.total_waits > 0
and a.sid = v.sid
and a.username not in ('sys','system')
order by v.total_waits desc
/

-------------un used columns in the tables---------------------------------


create or replace view dba_unused_col_tabs (
owner
,table_name
,count
) as
select u.name, o.name, count(*)
from sys.user$ u, sys.obj$ o, sys.col$ c
where c.obj# = o.obj#
and bitand(c.property,32768) = 32768 -- is unused column
and bitand(c.property, 1) != 1 -- not adt attribute col
and bitand(c.property, 1024) != 1024 -- not ntab's setid col
and u.user# = o.owner#
and u.user# in ('abc')
group by u.name, o.name
/

select u.name, o.name,


decode(c.type#, 1, decode(c.charsetform, 2, 'nvarchar2', 'varchar2'),
2, decode(c.scale, null, decode(c.precision#, null,
'number', 'float'),'number'),
8, 'long',
9, decode(c.charsetform, 2, 'nchar varying', 'varchar'),
12, 'date', 23, 'raw', 24, 'long raw',
69, 'rowid',
96, decode(c.charsetform, 2, 'nchar', 'char'),
105, 'mlslabel',
106, 'mlslabel',
111, 'unknown',
112, decode(c.charsetform, 2, 'nclob', 'clob'),
113, 'blob', 114, 'bfile', 115, 'cfile',
121, 'unknown',
122, 'unknown',
123, 'unknown',
178, 'time(' ||c.scale|| ')',
179, 'time(' ||c.scale|| ')' || ' with time zone',
180, 'timestamp(' ||c.scale|| ')',
181, 'timestamp(' ||c.scale|| ')' || ' with time zone',
231, 'timestamp(' ||c.scale|| ')' || ' with local time
zone',
182, 'interval year(' ||c.precision#||') to month',
183, 'interval day(' ||c.precision#||') to second(' ||
c.scale || ')',
208, 'urowid','undefined'),
c.length, c.precision#, c.scale
from sys.user$ u, sys.obj$ o, sys.col$ c
where c.obj# = o.obj#
and bitand(c.property,32768) = 32768 -- is unused column
and bitand(c.property, 1) != 1 -- not adt attribute col
and bitand(c.property, 1024) != 1024 -- not ntab's setid col
and u.user# = o.owner#
/
--------report on all objects that do not have statistics collected on
them----------------------------------- select
owner owner
, 'table' object_type
, table_name object_name
, null partition_name
from
sys.dba_tables
where
last_analyzed is null
and owner in ('steve')
and partitioned = 'no'
union
select
owner owner
, 'index' object_type
, index_name object_name
, null partition_name
from
sys.dba_indexes
where
last_analyzed is null
and owner in ('steve')
and partitioned = 'no'
union
select
table_owner owner
, 'table partition' object_type
, table_name object_name
, partition_name partition_name
from
sys.dba_tab_partitions
where
last_analyzed is null
and table_owner in ('steve')
union
select
index_owner owner
, 'index partition' object_type
, index_name object_name
, partition_name partition_name
from
sys.dba_ind_partitions
where
last_analyzed is null
and index_owner in ('steve')
order by 1 , 2 , 3
/

----------find the tables more than 100 rows-------------------

create or replace function rowcount(tname varchar2) return number is


x number;
stmt varchar2(200);
begin
stmt := 'select count(*) from '||tname;
execute immediate stmt into x;
return x;
exception when no_data_found then
return 0;
end;
/

select table_name, rowcount(table_name) from cat where rowcount(table_name) >=


100;
/

--------the session id,event name,time waited on the database.


useful in identifying the resource intensive queries.
-----------------------------

select
substr(se.sid,1,3) sid,
substr(s.username,1,15) user,
substr(se.event,1,20) event,
substr(se.time_waited,1,20) tim
from v$session s, v$session_event se
where s.username is not null
and s.username not in ('sys','system')
and se.sid=s.sid
and s.status='active'
and se.event not like '%sql*net%'
/

----------------------------system schema---------------------------------

select owner,substr(segment_name,1,25) segname,


substr(segment_type,1,12) segtype,
blocks,
extents
from dba_segments
where segment_name='sycdm001lt';

-----------------------------steve schema----------------------------------

select
substr(table_name,1,25) tablename,
num_rows,blocks,empty_blocks
from user_tables
where table_name='adrptc003dt';

select count (distinct


dbms_rowid.rowid_block_number(rowid)||
dbms_rowid.rowid_relative_fno(rowid)) "used"
from adrpt003dt;

---------------------------analyze
table-------------------------------------------------

truncate table adrcp001gt reuse storage

truncate table adrpt003dt;

analyze table adrpt003dt estimate statistics;

select 'analyze table '||owner||'.'||segment_name||' estimate statistics;'


from dba_segments
where segment_type in('table')
and owner in('steve');

-----------------------------------------------------------------------

select
substr(owner,1,10) owner,
substr(table_name,1,35) tab,
num_rows,
substr(blocks,1,5) block,
empty_blocks,
substr(avg_space,1,5) avg_space,
substr(chain_cnt,1,5) chain,
substr(avg_row_len,1,5) avg_row,
last_analyzed
from dba_tables
where owner in ('steve')
and last_analyzed is not null
and table_name like 'adrpt%'
and num_rows <=0
order by table_name
/
-------------------table sisze in mbs------------------------------------------

select
substr(segment_name,1,25) segment_name,
sum(bytes)/1048576 megs
from user_extents
where
segment_type ='table'
--and segment_name like 'adrc%'
group by segment_name
/

long deletes (committing every x number of records)

set time on
set echo on
declare
cnt number(7) := 0;
tot number(7) := 0;
cursor c1 is select rowid from <owner>.<table_name>
where <your criteria>;
begin
for rec in c1 loop
delete from <owner>.<table_name>
where rowid = rec.rowid;
tot := tot + 1;
cnt := cnt + 1;
if (cnt >= 1000) then
commit;
cnt := 0;
end if;
end loop;
commit;
dbms_output.put_line('<your table> records deleted: '||tot);
end;
/

#
*******************tables without primary key constraint ***************

select substr(owner,1,10) owner,


substr(table_name,1,35) table_name
from (select owner, table_name
from dba_tables
where owner in ('steve')
minus
select owner, table_name
from dba_constraints
where owner in ('steve')
and constraint_type = 'p')

----------trace file details----------------------------------


select s.sid,
s.serial#,
pa.value || '/' || lower(sys_context('userenv','instance_name')) ||
'_ora_' || p.spid || '.trc' as trace_file
from v$session s,
v$process p,
v$parameter pa
where pa.name = 'user_dump_dest'
and s.paddr = p.addr
and s.audsid = sys_context('userenv', 'sessionid');
-----------grants details-----------------------------
select grantee, privilege, admin_option
from sys.dba_sys_privs
where (privilege like '% any %'
or privilege in ('become user', 'unlimited tablespace')
or admin_option = 'yes')
and grantee not in ('sys', 'system', 'outln', 'aq_administrator_role',
'dba', 'exp_full_database', 'imp_full_database',
'oem_monitor', 'ctxsys', 'dbsnmp', 'ifssys',
'ifssys$cm', 'mdsys', 'ordplugins', 'ordsys',
'timeseries_dba')
/
----------deadly roles to assigned to users-------------------------------
select grantee, granted_role, admin_option
from sys.dba_role_privs
where granted_role in ('dba', 'aq_administrator_role',
'exp_full_database', 'imp_full_database',
'oem_monitor')
and grantee not in ('sys', 'system', 'outln', 'aq_administrator_role',
'dba', 'exp_full_database', 'imp_full_database',
'oem_monitor', 'ctxsys', 'dbsnmp', 'ifssys',
'ifssys$cm', 'mdsys', 'ordplugins', 'ordsys',
'timeseries_dba')
/

****************************************************************************
database performance tuning scripts
****************************************************************************
measure the buffer cache hit ratio
increase db_block_buffer if cache hit ratio < 90%
--------------------------------------------------------------------------------

select 1-(phy.value / (cur.value + con.value)) "cache hit ratio",


round((1-(phy.value / (cur.value + con.value)))*100,2) "% ratio"
from v$sysstat cur, v$sysstat con, v$sysstat phy
where cur.name = 'db block gets' and
con.name = 'consistent gets' and
phy.name = 'physical reads'
/

select (d.value+c.value-p.value)/(d.value+c.value)*100 "hit ratio"


from v$sysstat d,v$sysstat c,v$sysstat p
where d.name='db block gets' and
c.name='consistent gets' and
p.name ='physical reads'
/

col name format a20 heading "buffer pool name

select name,free_buffer_wait,write_complete_wait,
buffer_busy_wait,db_block_gets,
consistent_gets,physical_reads,
physical_writes
from v$buffer_pool_statistics;

----------------sessions with bad buffer cache hit ratio in %----------------


select substr(a.sid,1,5) "sid",
substr(a.username,1,10) "user",
substr(a.osuser,1,23) user_nm,
--substr(a.machine,1,23) machine_nm,
substr(a.program,1,17) program,
b.consistent_gets "consgets",
b.block_gets "blockgets",
b.physical_reads "physreads",
100 * round((b.consistent_gets + b.block_gets - b.physical_reads) /
(b.consistent_gets + b.block_gets),3) hitratio
from v$session a, v$sess_io b
where a.sid = b.sid
and (b.consistent_gets + b.block_gets) > 0
and a.username is not null
and a.username not in ('sys','system')
order by hitratio asc
/
-------------response time per transaction----------------------------
select ((wait + val) / trxn_cnt) as trxn_speed
from (select sum(total_waits) as wait from v$system_event) ,
(select value as val from v$sysstat where name='cpu used by this session'),
(select sum(value) as trxn_cnt from v$sysstat where name in ('user
rollbacks','user commits'))
/

------------sql text executing morethan 25 times(sql hard parsing )---------------

select substr(sql_text,1,50), count(*) from v$sql


group by substr(sql_text,1,50) having count(*) > 25
/

rem**---------------------latch contention----------------**

col name format a40 heading "latch name"

select name, gets, misses,


round((gets-misses)/decode(gets,0,1,gets),3) hit_ratio,
sleeps,
round(sleeps/decode(misses,0,1,misses),3) "sleeps/misses"
from v$latch
where gets != 0
order by name;

select
name,immediate_gets,immediate_misses,(immediate_gets)/(immediate_gets+immediate_mi
sses) hit_ratio
from v$latch where immediate_gets != 0;

rem**---------------shared pool statistics-------------------------------**

col namespace format a22

select namespace,gets,gethits,round(gethitratio,2)
gethitratio,pins,pinhits,round(pinhitratio,2)
pinhitratio,reloads,invalidations from v$librarycache;

-----------------------------------------------------------------------
display database sga statistics
-----------------------------------------------------------------------

declare
libcac number(10,2);
rowcac number(10,2);
bufcac number(10,2);
redlog number(10,2);
spsize number;
blkbuf number;
logbuf number;
begin
select value into redlog from v$sysstat
where name = 'redo log space requests';
select 100*(sum(pins)-sum(reloads))/sum(pins) into libcac from v$librarycache;
select 100*(sum(gets)-sum(getmisses))/sum(gets) into rowcac from v$rowcache;
select 100*(cur.value + con.value - phys.value)/(cur.value + con.value) into
bufcac
from v$sysstat cur,v$sysstat con,v$sysstat phys,v$statname ncu,v$statname
nco,v$statname nph
where cur.statistic# = ncu.statistic#
and ncu.name = 'db block gets'
and con.statistic# = nco.statistic#
and nco.name = 'consistent gets'
and phys.statistic# = nph.statistic#
and nph.name = 'physical reads';
select value into spsize from v$parameter where name = 'shared_pool_size';
select value into blkbuf from v$parameter where name = 'db_block_buffers';
select value into logbuf from v$parameter where name = 'log_buffer';
dbms_output.put_line('> sga cache statistics');
dbms_output.put_line('> ********************');
dbms_output.put_line('> sql cache hit rate = '||libcac);
dbms_output.put_line('> dict cache hit rate = '||rowcac);
dbms_output.put_line('> buffer cache hit rate = '||bufcac);
dbms_output.put_line('> redo log space requests = '||redlog);
dbms_output.put_line('> ');
dbms_output.put_line('> init.ora setting');
dbms_output.put_line('> ****************');
dbms_output.put_line('> shared pool size = '||spsize||' bytes');
dbms_output.put_line('> db block buffer = '||blkbuf||' blocks');
dbms_output.put_line('> log buffer = '||logbuf||' bytes');
dbms_output.put_line('> ');
if
libcac < 99 then dbms_output.put_line('*** hint: library cache too low!
increase the shared pool size.');
end if;
if
rowcac < 85 then dbms_output.put_line('*** hint: row cache too low!
increase the shared pool size.');
end if;
if
bufcac < 90 then dbms_output.put_line('*** hint: buffer cache too low!
increase the db block buffer value.');
end if;
if
redlog > 100 then dbms_output.put_line('*** hint: log buffer value is rather
low!');
end if;
end;
/

---------------list all supported init.ora parameters-----------------------------

select a.ksppinm name, b.ksppstvl value, b.ksppstdf isdefault,


decode(a.ksppity, 1, 'boolean', 2, 'string', 3, 'number', 4, 'file',
a.ksppity) type,
a.ksppdesc description
from sys.x$ksppi a, sys.x$ksppcv b
where a.indx = b.indx
and a.ksppinm not like '\_%' escape '\'
order by name
/

--------------list all un-supported init.ora parameters--------------------------

select a.ksppinm name, b.ksppstvl value, b.ksppstdf isdefault,


decode(a.ksppity, 1, 'boolean', 2, 'string', 3, 'number', 4, 'file',
a.ksppity) type,
a.ksppdesc description
from sys.x$ksppi a, sys.x$ksppcv b
where a.indx = b.indx
and a.ksppinm like '\_%' escape '\'
order by name
/

---------------active (in progress) transactionsrollback seg------------------

col name format a8


col username format a8
col osuser format a8
col start_time format a17
col status format a12
tti 'active transactions'

select username, terminal, osuser,


t.start_time, r.name, t.used_ublk "rollb blks",
decode(t.space, 'yes', 'space tx',
decode(t.recursive, 'yes', 'recursive tx',
decode(t.noundo, 'yes', 'no undo tx', t.status)
)) status
from sys.v_$transaction t, sys.v_$rollname r, sys.v_$session s
where t.xidusn = r.usn
and t.ses_addr = s.saddr
/
-----------------------------------------------------------------------

rem purpose: display rollback segment statistics


rem -----------------------------------------------------------------------

column "rollback segment" format a16


column "size (kb)" format 9,999,999
column "gets" format 999,999,990
column "waits" format 9,999,990
column "% waits" format 90.00
column "# shrinks" format 999,990
column "# extends" format 999,990

prompt
prompt rollback segment statistics...

select rn.name "rollback segment", rs.rssize/1024 "size (kb)", rs.gets "gets",


rs.waits "waits", (rs.waits/rs.gets)*100 "% waits",
rs.shrinks "# shrinks", rs.extends "# extends"
from sys.v_$rollname rn, sys.v_$rollstat rs
where rn.usn = rs.usn
/

show sga

show parameters area_size

set pages 999;

column pga_size format 999,999,999

select
2048576+a.value+b.value pga_size
from v$parameter a,v$parameter b
where a.name = 'sort_area_size'
and b.name = 'hash_area_size';

column pga_size format 999,999,999

accept hwm number prompt 'enter the high-water mark of connected users: '

select
150*(2048576+a.value+b.value) pga_size
from v$parameter a, v$parameter b
where a.name = 'sort_area_size'
and b.name = 'hash_area_size';

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

rem database health monitoring script.


rem
rem segments max extents & current extent comparison
rem
set line 180
set pagesize 10000
set feedback off
prompt
col time format a50 heading "system time"
select to_char(sysdate,'dd-mon-yyyy:hh24:mi:ss') time from dual;
prompt
prompt
prompt
rem**-------------objects reaching max extents-----------**

col segment_name format a40 heading "object name"


col max_extents format 9999999999 heading "max extents"
col curr_extents format 99999999999 heading "curent extents"
select a.segment_name,a.max_extents,b.curr_extents from dba_segments a,(select
segment_name,max(extent_id) curr_extents from dba_extents group by segment_name) b
where a.segment_name = b.segment_name
and (a.max_extents - b.curr_extents) <= 10;

rem**--------------user session information-----------------**

col sid format 9999 heading "sid"


col serial# format 9999999 heading "serial no"
col logon_time format 9999999 heading "login time"
col username format a12
col osuser format a24
col program format a38
select
s.sid,s.serial#,p.spid,s.username,s.osuser,s.program,to_char(s.logon_time,'dd-mon-
yy:hh24:mi:ss') "log on time",round((s.last_call_et/(60*60*24)),2)"wait in days"
from v$session s,v$process p where s.paddr = p.addr and s.username is not null
order by 8 desc;

rem**----------------------file information-------------------------**

col file_name format a55 heading "file name"


col sizeinmb format 99999999 heading "total size (mb)"
col maxsize format 99999999 heading "maximum size (mb)"

compute sum of sizeinmb on report


select
substr(file_name,1,60) fil_name,
bytes/(1024*1024) sizeinmb,
autoextensible,
maxbytes/(1024*1024) maxsize
from dba_data_files
union all
select
substr(file_name,1,60) fil_name,
bytes/(1024*1024) sizeinmb,
autoextensible,
maxbytes/(1024*1024) maxsize
from dba_temp_files;

rem**-----------------tablespace information--------------------------*

col tablespace_name format a25 heading "tablespace name"


col logging format a10
col status format a12
col extent_management format a30 heading "local/dict"
select tablespace_name,status,contents,decode(logging,logging,'yes','no')
logging,extent_management from dba_tablespaces;
select total.name "tablespace name",
free_space, (total_space-free_space) used_space, total_space
from
(select tablespace_name, sum(bytes/1024/1024) free_space
from sys.dba_free_space
group by tablespace_name
) free,
(select b.name, sum(bytes/1024/1024) total_space
from sys.v_$datafile a, sys.v_$tablespace b
where a.ts# = b.ts#
group by b.name
) total
where free.tablespace_name = total.name;

rem**-----------tablespace fragmentation status---------------------**

col tablespace_name format a25 heading "tablespace name"

select
substr(tablespace_name,1,12) name,
total_extents "total extents",
extents_coalesced,
decode(percent_extents_coalesced,100,'no','yes') "frag"
from
dba_free_space_coalesced;

rem**---------------top 20 events and system


statistics-------------------------------**

col event format a40 heading "event name"


col stat format a40 heading "stat name"
select * from ( select name "stat",value from v$sysstat order by value desc )
where rownum <= 20 ;
select * from ( select event,total_waits from v$system_event order by total_waits
desc ) where rownum <=20;

rem**---------------buffer cache statistics-------------------------------**

select (1-(a.value/(b.value+c.value)))*100 "buffer cache hit ratio"


from v$sysstat a,v$sysstat b,v$sysstat c
where a.name= 'physical reads'
and b.name = 'consistent gets'
and c.name = 'db block gets';

**********************************************************************************
******************

rem**---------------file i/o statistics-------------------------------**


col file# format 99 heading "file no"

select file#,phyrds "physical reads",


phywrts "physical writes",
readtim "read time",
writetim "write time",
avgiotim "avg time" from v$filestat;

select f.file#,d.file_name,f.phyrds "physical reads",


f.phywrts "physical writes",
f.readtim "read time",
f.writetim "write time",
f.avgiotim "avg time"
from v$filestat f,dba_data_files d
where d.file_id=f.file#
/

--------------------------------------getting sql statement


--------------------------------------
select sql_text
from v$sql
where address in ( select address
from v$open_cursor
where sid = (select sid
from v$mystat
where rownum=1) )
and upper(sql_text) like '%

***---------------idle
connections-----------------------------------------------------------**

select s.sid||','||s.serial# session,


s.username,
s.last_call_et seconds_since_active,
s.status,
s.sql_address,
s.program
from v$session s
where s.sid = nvl(to_number('&sid'),s.sid);

##################################indices#########################################
#####

rem script description: this script generates an index listing for a particular
owner

break on table_name skip 2 on index_name skip 1;

select
substr(table_name,1,25) table_nm,
substr(index_name,1,30) index_name,
substr(column_position,1,3) pos,
substr(column_name,1,20) column_name
from all_ind_columns a
where a.index_owner = upper('rept')
--and table_name like upper('adpr')||'%'
order by 1,2,3;

----------------------------------------------------------------------------------
--------------------

tables without indexes notes:

select substr(owner,1,12) owner,


substr(table_name,1,25) table_name
from
(
select owner,
table_name
from dba_tables
minus
select table_owner,
table_name
from dba_indexes
)
orasnap_noindex
where
owner in ('rept')
--and table_name not like 'smp'||'%' and table_name not like 'v'||'%'
order by owner,table_name
/
****************************invalid indices***************************************

when tables are moved from one tblsp to other indices gets unvalid so rebuild them
again

select 'alter table steve.'||table_name||' move tablespace users nologging ;'from


user_tables where tablespace_name like 'steveusrx';

select 'alter index '||index_name||' rebuild tablespace indexes ;' from


user_indexes;

##############to find invalid objects in user schema##############

select object_type,count(*) from user_objects where status = 'invalid'


group by object_type;

$$$$$$$$$$$$$ invalid objects $$$$$$$$$$$$$$$$$$$$$$

select substr(owner, 1, 20) owner,


substr(object_name, 1, 40) object_name,
substr(object_type, 1, 20) type
from dba_objects
where status='invalid'
/
**********************tables without indexes****************************

select substr(owner,1,10) owner,


substr(table_name,1,35) table_name
from (select owner, table_name
from dba_tables
where owner in ('steve')
minus
select table_owner, table_name
from dba_indexes
where owner in ('steve'))
order by owner,table_name;

analyze index <index_name> validate structure;

- this populates index_stats.

select index_name,lf_rows,del_lf_rows from index_stats;

- if the deleted leaf rows is 5% of the actual rows(lf_rows) then


oracle suggests to rebuild the indexes.

to
index:

alter index <index_name> rebuild online (if 9i)

*****************gen script for move indices****************

select 'alter index '||owner||'.'||segment_name ||' rebuild online ;'


from dba_segments
where owner in ('steve')
and segment_type in('index')

--and tablespace_name in('users')


/

select 'alter index '||owner||'.'||segment_name||' move tablespace steveusrx ;'


from dba_segments
where owner in('usrx')
and segment_type in('index')
and tablespace_name in('users')
/

###################script to move tables#######################

select 'alter table '||owner||'.'||segment_name ||' move tablespace steveusrx ;'


from dba_segments
where owner in('usrx')
and segment_type in('table')
and tablespace_name in('users')

/
################finding the sessions holding the lock##########################

find the (id1, id2, type) for sessions waiting for a lock (lmode=0).

find the session holding the lock (request=0) for that id1, id2, type.

select lpad(' ',decode(request,0,0,1))||sid sess, id1,id2,lmode


,request, type
from v$lock
where id1 in (select id1 from v$lock where lmode = 0)
order by id1,request

*******************=============================****************************======
===============

select hash_value, buffer_gets, disk_reads


from v$sqlarea
where disk_reads > 1000000
order by buffer_gets desc;

**********************************************************************************
*****************

####################### finding the waits for the database


writer############################

select s.sid, bgp.name


from v$session s, v$bgprocess bgp
where bgp.name like '%dbw%'
and bgp.paddr = s.paddr;

select event, total_waits waits, total_timeouts timeouts,


time_waited total_time, average_wait avg
from v$session_event
where sid = 3
order by time_waited desc;

select sid, sql_hash_value


from v$session
where sid in (1237,1256,1176,938,1634);

================================ profile
creation==================================================

alter profile profile_name limit private_sga 50 k

sessions_per_user
cpu_per_session
cpu_per_call
connect_time
idle_time
logical_reads_per_session
logical_reads_per_call
composite_limit
private_sga

unlimited | default | integer

alter profile myprofile limit private_sga 50 k

v$sql_area
v$sql_text

$$$$$$$$$$$$$$$$$$$$$amount of used space, the free space and


the total allocated space for all tablespaces in a database. $$$$$$$$$$$$$$$$$$

select tablespace_name
, sum(bytes)/1024/1024 mbytes
from dba_free_space
group by tablespace_name
/

select ts.tablespace_name
,round(fs.mbytes,2) "free (mbytes)"
from dba_tablespaces ts
,( select tablespace_name
, sum(bytes)/1024/1024 mbytes
from dba_free_space
group by tablespace_name) fs
where ts.tablespace_name = fs.tablespace_name

################display last updation########################

select owner, object_name, created, last_ddl_time


from dba_objects
where object_name = 'syscroo1mt';

################display last n records########################

select * from
(select rownum a, eno,ename,sal from scott.emp)
where a > ( select (max(rownum)-5) from scott.emp);

you can run "$oracle_home/rdbms/admin/utlbstat.sql" to start gathering


statistics. when you are ready to see the file reads/writes, run
"$oracle_home/rdbms/admin/utlestat.sql". you will also find dozens of useful
pieces of information about your database.

in fact oracle uses this for much of its internal packages. just look at
$oracle_home/rdbms/admin for files with examples of creating wrapped
packages.

select * from v$sgastat;

set escape #

now # is the escape character. now i can select the % literally:

sql> select '#%' from dual;

to find all records with the % symbol, it is important to know the ascii
codes. chr(37) is the % symbol. to find all records with %:

select * from table_name


where instr(column_name,chr(37)) > 0;

same for the underscore, which is chr(95). to see tables with underscore:

select * from table_name


where instr(column_name,chr(95) > 0;

audit audit_option [on schema.object_name] [by username]


[by { session | access }]
[whenever { successful | not successful }]

audit drop table on scott.emp


by session
whenever successful

select * from sys.aud$

insert into xxx select * from xxx@remote_database;

create table xxx as select * from xxx@remote_database


alter tablespace temp default storage (initial 1m next 10m);

#######################create table & sequence ###############################

create table cltttl01mt


(tttl_tmp_id number,
mgr_id number,
tttl_tmp_name varchar2(200),
tttl_tmp_desc varchar2(1000),
tttl_pd_med char(1),
tttl_pd_all char(1),
tttl_pd_pr char(1),
tttl_created_date date,
tttl_created_user_id varchar2(60),
tttl_delete_flg char(1),
tttl_delete_dt date,
tttl_delete_user varchar2(60),
constraint cltttl01mt_pk primary key(tttl_tmp_id),
constraint cltttl01mt_fk foreign key(mgr_id) references admgr001mt(mgr_id))
/
create sequence cltttl01mt_seq
minvalue 1
maxvalue 99999999999999999999
start with 1
increment by 1
nocache
/

alter table table_name


add constraint constraint_name
unique (column_name)

###########################data loading ########################################

you can first export the excel files to access and then from access to oracle.

to access:
create a blank database in access
file-get external data-import-files of type(select *.xls)

then you can select the option suites to your needs.

after all this you will have your data in well organised access table.

to oracle:
create an odbc connection for your database
right click on your table in access-export-save as type(odbc database) and follow
the onscreen instructions.

that's it.

#################finding the undo


retention#############################################

undo ret=undo_size/(db blk size*undo blk per sec)

select sum(a.bytes) "undo_size"


from v$datafile a,
v$tablespace b,
dba_tablespaces c
where c.contents = 'undo'
and c.status = 'online'
and b.name = c.tablespace_name
and a.ts# = b.ts#;

undo blocks per second

select max(undoblks/((end_time-begin_time)*3600*24))
"undo_block_per_sec"
from v$undostat;

db block size

select to_number(value) "db_block_size [kbyte]"


from v$parameter
where name = 'db_block_size';

#################################################################

select d.undo_size/(1024*1024) "actual undo size [mbyte]",


substr(e.value,1,25) "undo retention [sec]",
round((d.undo_size / (to_number(f.value) *
g.undo_block_per_sec))) "optimal undo retention [sec]"
from (
select sum(a.bytes) undo_size
from v$datafile a,
v$tablespace b,
dba_tablespaces c
where c.contents = 'undo'
and c.status = 'online'
and b.name = c.tablespace_name
and a.ts# = b.ts#
) d,
v$parameter e,
v$parameter f,
(
select max(undoblks/((end_time-begin_time)*3600*24))
undo_block_per_sec
from v$undostat
) g
where e.name = 'undo_retention'
and f.name = 'db_block_size'
/

####################################################################

flush shared pool when it reaches 60-70% of it's capacity


---=======================================================---

create or replace view sys.sql_summary as select


username,
sharable_mem,
persistent_mem,
runtime_mem
from sys.v_$sqlarea a, dba_users b
where a.parsing_user_id = b.user_id;

create or replace procedure flush_it as

cursor get_share is
select sum(sharable_mem)
from sys.sql_summary;

cursor get_var is
select value
from v$sga
where name like 'var%';

cursor get_time is
select sysdate
from dual;

todays_date date;
mem_ratio number;
share_mem number;
variable_mem number;
cur integer;
sql_com varchar2(60);
row_proc number;

begin

open get_share;
open get_var;

fetch get_share into share_mem;


dbms_output.put_line('share_mem: '||to_char(share_mem));

fetch get_var into variable_mem;


dbms_output.put_line('variable_mem: '||to_char(variable_mem));

mem_ratio:=share_mem/variable_mem;
dbms_output.put_line('mem_ratio: '||to_char(mem_ratio));

if (mem_ratio>0.3) then
dbms_output.put_line ('flushing shared pool ...');
cur:=dbms_sql.open_cursor;
sql_com:='alter system flush shared_pool';
dbms_sql.parse(cur,sql_com,dbms_sql.v7);
row_proc:=dbms_sql.execute(cur);
dbms_sql.close_cursor(cur);
end if;
end;
/

-- this procedure was then loaded into the job queue and scheduled to run
-- every hour using the following commands:
declare
job number;
begin
dbms_job.submit(job,'flush_it;',sysdate,'sysdate+1/24');
end;
/

alter database archivelog


alter database archivelog manual
alter database noarchivelog
alter database backup controlfile to trace;
alter database backup controlfile to trace as '/some/arbitrary/path';
alter database backup controlfile to trace as '/some/arbitrary/path' reuse;
alter database backup controlfile to '/some/arbitrary/path';
alter database backup controlfile to '/some/arbitrary/path' reuse;
whenever the database is altered, the control file should be backed up.

alter database backup controlfile to ['filename' | trace]


this command comes in two versions. one backs up the control file in a binary
format while the other backs it up in a human readable form. it is required if the
database is running in archive log mode and a structural change was made to the
database.

======================================
tablespace/datafile listing
=====================================
set pagesize 100
set line 150
column "location" format a35;
column "tablespace name" format a15;
column "size(m)" format 999,990;

break on "tablespace name" skip 1 nodup;


compute sum of "size(m)" on "tablespace name";

select substr(tablespace_name,1,10) "tablespace name",


substr(file_name,1,40) "location",
bytes/1048576 "size(m)"
from sys.dba_data_files
order by tablespace_name
/

======================================
redo log listing
=====================================

select a.group#,substr(b.member,1,35) "file",


(a.bytes/1024/1024)||' mb' "size"
from v$log a,v$logfile b
where a.group#=b.group#
/

column "group" format 999;


column "file location" format a50;
column "bytes (m)" format 99,990;
break on "group" skip 1 nodup;

select a.group# "group",


substr(b.member,1,35) "file location",
(a.bytes/1024) "bytes (k)"
from v$log a,
v$logfile b
where a.group# = b.group#
order by 1,2
/

======================================
control file listing
=====================================
column name format a80 heading "control file name"
column status format a10 heading "status"

select name,status
from v$controlfile

select username,default_tablespace from dba_tablespaces

#################################schema size owner size#########################


select owner,
sum(bytes)/1024/1024 as total_size_mb
from dba_segments
group by owner;
/

################chained rows#####################################

select owner, table_name, num_rows, chain_cnt, (chain_cnt*100/num_rows)


pct, empty_blocks, blocks
from dba_tables where chain_cnt > 0 and owner not in ('sys','system')

myref use myrefspcs tablespace for tables and use indx_myref tablespace for
indexes.
create tablespace users1 datafile 'd:\oracle\ora92\oradata' size 1000m
auto extentd on

----------------------------advised by bill
lee------------------------------------------------

##################################usrx ###############################
create tablespace users1
logging
datafile 'd:\oracle\oradata\pcjmso\user1.dbf'
size 1000m
autoextend on
extent management local;

alter tablespace <............>


add {tempfile|datafile} 'filespec' [autoextend off] size int {k|m}

add {tempfile|datafile} 'filespec' size int {k|m}


[ autoextend on [next int k | m]
[maxsize {unlimited|int k|int m}] ]

rename datafile 'filename' to 'filename'


{tempfile|datafile} online
{tempfile|datafile} offline
minimum extent int {k|m}
coalesce
default storage storage_clause
online
offline {normal | temporary | immediate}
{begin | end} backup
read {only | write}
permanent | temporary
logging | nologging
[no] force logging

alter database datafile '/db/adpdb/foo.dbf' resize 1024m

alter database datafile '/u01/db/df/ts_data01.dbf' autoextend on maxsize 20m

--revoke unlimited tablespace from usrx--

alter user usrx grant quota 0 on steveusrx;

alter user usrx default tablespace users;

alter user usrx quota unlimited on users;

create tablespace users


logging
datafile 'd:\oracle\oradata\pcjmso\users01.dbf' size 2000 m
auto extend on
extent management local;

alter tablespace users


add datafile 'd:\orac;e\oradata\pcjmso\users02.dbf' size 1000 m;

create tablespace users1


logging
datafile 'd:\oracle\oradata\pcjmso\users101.dbf' size 2000 m
auto entend on
extent management local;

alter tablepspace add datafile 'd:\oracle\oradta\pcjmso\users102.dbf' size 1000 m;

alter user usrx quota unlimited on users1


grant quota unlimited on tablespace myrefspcs to myref

----------------------------------------------------------------------------------
---

grant select on scott.emp to public;


create public synoym emp on scott.emp;

select * from all_objects where status = 'invalid'

lob_storage_clause

select name,value,isdefault
from v$parameter order by name
/

sql statement

select sid, schemaname, osuser, substr(machine, 1, 20) machine


from v$session
order by schemaname

finding the total real size of data in a table, not just the init/next extent

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
select table_name, blocks, empty_blocks
from user_tables where table_name = �table_name�;

now, you can select a user from list. when you run the sql below,
the sql statement that the user account is running will beshown.

select sql_text
from v$sqlarea
where (address, hash_value) in
(select sql_address, sql_hash_value
from v$session
where sid = &1);

#################################invalid
objects#################################################

exec dbms_utility.compile_schema( 'steve' )

$oracle_home/rdbms/admin/utlrp.sql

which will compile all invalid objects thru svrmgrl.


set heading off;
set feedback off;
set echo off;
set lines 999;
spool run_invalid.sql
select'alter ' || object_type || ' ' || owner || '.' || object_name || '
compile;'
from dba_objects
where status = 'invalid'
and object_type in ('package','function','procedure') ;
spool off;
set heading on;
set feedback on;
set echo on;

select owner,name,type,referenced_owner,referenced_name,referenced_type from


all_dependencies where referenced_name='emp';

set heading off


spool recompile.sql
select 'alter '||decode(object_type,'package body','package',object_type)||' '||
owner||'.'||object_name||' compile;'
from dba_objects where status= 'invalid';
spool off

select name, value, isdefault


from v$parameter
order by name;

select �set sqlprompt ���|| d.name ||�@� ||


substr(s.machine,1,decode (instr(s.machine,�.�), 0, length(s.machine),
instr(s.machine,�.�) - 1)) || �-sql> ���
from v$session s, v$database d
where s.sid=1;

d:\oracle\ora90\network\admin

-----------------------changing the datatype of column (which contains data)


---------------------

let's say you want to decrease ename from varchar2(10) to varchar2(7)


oracle allows you to increase the size of a column but does not allow you to
decrease the size of a column.
here's a way to decrease the size of a column which contains data.
sql> desc emp
name null? type
------------------------------- -------- ----
empno not null number(4)
ename varchar2(10)
job varchar2(9)
mgr number(4)
hiredate date
sal number(7,2)
comm number(7,2)
deptno number(2)

drop table fix_it;

create table fix_it as select rowid rowid_xx,sys_code_id


create table fix_it as select rowid rowid_xx,sys_code_id from syttqc01mt;

create index fix_it on fix_it (rowid_xx);

--alter table syttqc01mt modify (sys_code_id null);

update syttqc01mt set sys_code_id = null;

alter table syttqc01mt modify (sys_code_id number);

update syttqc01mt set sys_code_id=(


select sys_code_id from fix_it where rowid_xx=syttqc01mt.rowid);

######################finding dup rows##################

select count(*),eno, deptno


from emp
group by eno, deptno
having count(*) > 1;

################deleting duplicate rows######################

delete from emp a


where rowid > (
select min(rowid) from emp b
where a.eno = b.eno and
a.deptno = b.deptno);

delete from deep_sytst001mt1 a


where rowid > (
select min(rowid) from deep_sytst001mt1 b
where a.sys_test_desc = b.sys_test_desc);

################################################################

delete from emp a where


(eno, deptno,2) in
(select eno,deptno,decode(count(*),1,1,2)
from emp b
where a.eno=b.eno and
a.deptno = b.deptno
group by eno,deptno);

################files that grow by default################

the listener.log file


$oracle_home/network/log
the alert_{sid}.log file
$oracle_base/admin/{oracle_sid}/bdump
default audit files
$oracle_home/rdbms/audit
background dump files
$oracle_base/admin/{sid}/bdump
$oracle_base/admin/{sid}/cdump
$oracle_base/admin/{sid}/udump

#############################to login as other user########################

alter user myref identified by values '.................'

alter user <name>

create tablespace usrxind


logging
datafile 'c:\oracle\oradata\wlxhyd\usrxind01.dbf' size 4000 m
auto extend off
extent management local

alter tablespace undotbs1 add datafile 'e:\oracle\oradata\pcjmso\undotbs02.dbf'


size 1000 m

select trigger_name,table_name,trigger_body from all_triggers;

nls_date_format.
a) oracle server maintains the spfile
c) ability to make changes persistent across startup &
shutdown
d) changes can be made in memory or in spfile with
alter system

column description
statistic# the unique identifier for the statistic
name the name of the statistic
figure 3: useful columns in v$statname
column description
statistic# the unique identifier for the statistic
name the name of the statistic
value the value of the statistic for the instance as a whole
figure 4: useful columns in v$sysstat
column description
sid the unique identifier for the session�join to v$session
statistic# the unique identifier for the statistic�join to v$statname
value the value of the statistic for the session
figure 5: useful columns in v$sesstat
number name
12 cpu used by this session
39 physical reads
40 physical writes
119 table scans (long tables)
123 table scan rows gotten
129 parse time cpu
131 parse count
133 bytes sent via sql*net to client
134 bytes received via sql*net from client
135 sql*net roundtrips to/from client
140 sorts (disk)
141 sorts (rows)

revoke unlimited tablespace from usrx;

alter tablespace mymain rename


datafile thedatafilenameinthediskgettingfilled
to newdatafilenametoabiggerdiskorpartition.
for the system tablespace do as follows alter database rename
file thefiletomove
to newfileinanewdiskorpartition.

alter tablespace mymaintablespace


default storage (initial x next x maxextents y)

#############rebuild indexes###########################
alter index <index_name> rebuild;

select 'alter '||object_type||' '||owner||'.'||object_name||' rebuild online ;'


from dba_objects
where owner in('steve')
and object_type in('index')
and rownum<5
/

sql> select 'alter '||object_type||' '||owner||'.'||object_name||' rebuild ;'


2 from dba_objects
3 where owner in('myref')
4 and object_type in('index');

select 'alter index '||owner||'.'||segment_name ||' rebuild online ;'


from dba_segments
where owner in ('steve_prod')
and segment_type in('index')

select 'alter index '||owner||'.'||segment_name||' move tablespace usrxind :'


from dba_segment;

alter index <indexname> rebuild online;

alter index formulary_int_gcn_idx rebuild tablespace usrxindx;

##################################################################################
###
restrictions on the auto clause:

you can specify this clause only for permanent, locally managed tablespace. (make
tbs locally managed using : execute dbms_space_admin.tablespace_migrate_to_local
('users');)
you cannot specify this clause for the system tablespace.
syntax:
create tablespace auto_seg_ts datafile 'file1.dbf' size 1
0m
extent management local
segment space management auto;

########when to rebuild the index###########

lf_blk_len/lf_blk_len+br_blk_len

-------------------------------------------------------------

select userenv('sessionid'), userenv('terminal') from


dual;

it is stored in a table .. nls_instance_parameters , nls_session_parameters ..

nls_date_format

select sys_context('userenv','ip_address') "my ip address" from dual;


select * from emp where rowid=(select min(rowid) from scott.emp)
union
select * from emp where rowid=(select max(rowid) from scott.emp)

trr108: can change my contact no :this is new 09986342803

#############################################query tuning#####################
select username,sid,program,to_char(logon_time,'hh24:mi:ss') logon_time,
to_char(sysdate,'hh24:mi:ss') current_time,
to_char(sysdate-last_call_et/24/60/60,'hh24:mi:ss') start_time,
trunc(last_call_et/60) || ' mins, ' || mod(last_call_et,60) || ' secs' running,
last_call_et,sql_address
from v$session
where status='active'and rawtohex(sql_address) <> '00'and username is not null
and last_call_et>:period
order by last_call_et asc

***********************alter system flush shared pool;********************

a) how much do you want to assign to your buffer cache for maximum performance
b) how big is your shared/java pool (a function of how much sql/plsql/java you
run in your database, no magical number for all to use)
c) do you run in shared server (than the large pool is used and will be large --
that is part of the sga) or in dedicated server -- then you need to leave os
memory for dynamic allocations
d) what else is going on in the machine.

sga = total ram � os usage � application usage � pga.

##################################################################################
####

break on 1;
compute sum label 'sga total' of value on 1
col name format a30
col1 format a10
select 1, name, to_number(value/1024/1024) value
from v$parameter
where upper(name) like 'db%cache_size'
or upper(name) in ('shared_pool_size',
'large_pool_size',
'java_pool_size',
'log_buffer')
union
select 1, '+ 1mb', 1 from dual
order by 2;

###################################waits##################################33

select class wait_event,count num_waits,(select sum(value) from


v$sysstat where name in ('db block gets','consistent gets')) total_requests,
round (count/(select sum(value) from v$sysstat where name in ('db block
gets','consistent gets'))*100,2)||'%' pct_wait
from v$waitstat where class in ('system undo header', 'system undo
block', 'undo header', 'undo block');

-----------------reports free memory available in the sga----------------------

select name,
sgasize/1024/1024 "allocated (m)",
bytes/1024 "free (k)",
round(bytes/sgasize*100, 2) "% free"
from (select sum(bytes) sgasize from sys.v_$sgastat) s, sys.v_$sgastat f
where f.name = 'free memory'
/

select 100*(sum(pins)-sum(reloads))/sum(pins) from v$librarycache;

select 100*(sum(gets)-sum(getmisses))/sum(gets) from v$rowcache;

----------------------------------------------------------------------------------
--------
shared pool
the shared pool contains memory for the library cache and the dictionary cache.
the library cache stores information for the
different sql code blocks, such as the sql area, triggers, stored procedures and
functions. to determine if your library
cache is sufficiently being utilized, use the following sql code.

select sum(pins) as hits,


sum(reloads) as misses,
round((sum(pins-reloads)/sum(pins))*100, 2)as hit_ratio
from v$librarycache
/

the library cache hit ratio should be at least 99%. if the library cache hit ratio
is less than 99%, then you need to increase the shared_pool initialization
parameter.

the dictionary cache stores information on all database objects. to calculate the
dictionary cache hit ratio, use the following
sql code.

select sum(gets-getmisses)as hits,


sum(getmisses)as misses,
round((sum(gets-getmisses)/sum(gets))*100,2)as hit_ratio
from v$rowcache
/

the dictionary cache hit ratio should be at least 85%. if the dictionary cache hit
ratio is less than 85%, then you need to
increase the shared_pool initialization parameter.

buffer cache
the buffer cache is where oracle stores data blocks in memory. the number of data
blocks assigned to the buffer cache is
defined by the db_block_buffers initialization parameter. the size of the buffer
cache is equal to db_block_size
multiplied by db_block_buffers. the buffer cache hit ratio is a measurement of the
efficiency of the buffer cache. to
calculate the buffer cache hit ratio, use the following sql code and formula.

the buffer cache hit ratio should be at least 90%. if it below 90%, there are a
few things you can do to increase the buffer

select name, value


from v$sysstat
where name='redo buffer allocation retries'
/

----------------------------------------------------------------------------------
--------------------
measure the buffer cache hit ratio
increase db_block_buffer if cache hit ratio < 90%
---------------------------------------------------------------------------------
-------------------

select ((p1.value+p2.value-p3.value)/(p1.value+p2.value))*100 "buffer hit ratio"


from v$sysstat p1,v$sysstat p2,v$sysstat p3
where p1.name='db block gets'
and p2.name='consistent gets'
and p3.name='physical reads'
/

disk i/o balancing


the goal of balancing disk i/o is to evenly distribute i/o across all drives. to
monitor your file i/o, you can use operating
system utilities such as windows performance monitor or unix�s sar utility. you
can also use the following sql code to
identify the number of i/os per datafile.

select to_char(sysdate,�mm-dd-yyyy hh24:mi:ss�) as time_stamp,


a.filename as datafile,
b.phyrds as reads,
b.phyblkrd as blocks_read,
b.phywrts as writes,
b.phyblkwrt as blocks_written,
(b.phyrds + b.phywrts) as total_io
from dba_data_files a, v$filestat b
where a.file_id = b.file#
order by a.filename;

################################pga size#######################

select empty_blocks/nvl((empty_blocks + blocks),1) "hwm %",table_name


from dba_tables
where owner = 'ishadmin'
/

set pages 999;

column pga_size format 999,999,999

accept hwm number prompt 'enter the high-water mark of connected users: '

select
&hwm*(2048576+a.value+b.value) pga_size
from
v$parameter a,
v$parameter b
where
a.name = 'sort_area_size '
and
b.name = 'hash_area_size '
;

column c1 heading 'target(m)'


column c2 heading 'estimated|cache hit %'
column c3 heading 'estimated|over-alloc.'

select
round(pga_target_for_estimate /(1024*1024)) c1,
estd_pga_cache_hit_percentage c2,
estd_overalloc_count c3
from
v$pga_target_advice;

????????????????????????????????????????????????????????/

select *
from v$pgastat
order by lower(name)
/

??????????????????????????????????????????????????????//

select *
from v$pga_target_advice
order by pga_target_for_estimate
/

?????????????????????????????????????????`???????????????

select
max(pga_used_mem) max_pga_used_mem
, max(pga_alloc_mem) max_pga_alloc_mem
, max(pga_max_mem) max_pga_max_mem
from v$process
/
?????????????????????????????????????????????????????????/
select
sum(pga_used_mem) sum_pga_used_mem
, sum(pga_alloc_mem) sum_pga_alloc_mem
, sum(pga_max_mem) sum_pga_max_mem
from v$process
/

????????????????pga tuning???????????????????????????????????????????

select name,value
from
v$pgastat
order by
value desc
/

alter system set pga_aggregate_target=100m scope=spfile;

alter system set pga_aggregate_target = 35m

show parameter pga_aggregate_target

select name,value from v$pgastat;

select
optimal_count "optimal",
round(optimal_count * 100 / total,2) "optimal %",
onepass_count "onepass",
round(onepass_count * 100 / total,2) "onepass %",
multipass_count "multipass",
round(multipass_count * 100 / total,2) "multipass %"
from (
select
decode (sum(total_executions), 0, 1, sum(total_executions)) total,
sum(optimal_executions) optimal_count,
sum(onepass_executions) onepass_count,
sum(multipasses_executions) multipass_count
from v$sql_workarea_histogram
);

select
low_optimal_size/1024 "low (k)",
(high_optimal_size + 1)/1024 "high (k)",
optimal_executions "optimal",
onepass_executions "1-pass",
multipasses_executions ">1 pass"
from v$sql_workarea_histogram
where total_executions <>

select
round(pga_target_for_estimate /(1024*1024)) "target (m)",
estd_pga_cache_hit_percentage "est. cache hit %",
estd_overalloc_count "est. over-alloc"
from v$pga_target_advice
/

select
optimal_count "optimal",
round(optimal_count * 100 / total,2) "optimal %",
onepass_count "onepass",
round(onepass_count * 100 / total,2) "onepass %",
multipass_count "multipass",
round(multipass_count * 100 / total,2) "multipass %"
from (
select
decode (sum(total_executions), 0, 1, sum(total_executions)) total,
sum(optimal_executions) optimal_count,
sum(onepass_executions) onepass_count,
sum(multipasses_executions) multipass_count
from v$sql_workarea_histogram)
/

######################create database link##############################

create database link new.us.oracle.com connect to steve identified by pcj123


using
'description=(address=(protocol=tcp)(host=10.1.2.22)(port=1521))(connect_data=(sid
=jskt)(server=dedicated)))
/

create database link <dblink name> connect to steve identified by <pwd>


using '..host string..'

exp scott/tiger file=d:\f1.dmp,e:\f2.dmp filesize=10m log=scott.log

copy from scott/tiger@bostondb -


> create empcopy -
> using select * from emp

---------------- to convert a tablespace to locally-


managed-------------------------------

sys.dbms_space_admin .tablespace_migrate_to_local('users')

------------ take a tablespace locally-managed back to dictionary


management---------------

sys.dbms_space_admin .tablespace_migrate_from_local('users')
##################duplicate
rows######################################################

delete from personnelwhere rowid in (select p2.rowid from personnel p2,


(select p3.id, p3.name, max(p3.rowid) max_rowid
from personnel p3
group by p3.id, p3.name) p4 where p2.rowid <> p4.max_rowid
and p2.id=p4.id and p2.name=p4.name );

######################who locked
whom#################################################################

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

blocker sid 'isblocking' blockee


sid
------------------------------ ---------- --------------------
------------------------------ ----------
system 17 is blocking perfstat
11

2. look for the object id, row wait file#, row wait block# and row wait row# -
these info will be using in dbms_rowid

select sid,row_wait_file#,row_wait_block#,row_wait_row#
from v$session where sid=11;
--- use blockee sid;

sid row_wait_obj# row_wait_file# row_wait_block# row_wait_row#


---------- ----------------------------- -----------------------------
-------------------------------- -----------------------------
11 26435 3
11923 5

3. look for object name - join dba_objects (object_id) in step 2

select object_type, owner, object_namefrom dba_objectswhere


object_id=26435;object_type owner object_name
----------------------- ------------------------------
-----------------------------------
table perfstat t

4. use dbms_rowid to find out the row.

select * from t where rowid = dbms_rowid.rowid_create(1,26435,3,11923,5);


c1 c2
---------- ------------
6 f

this is the row which is locked by system where perfstat user trying to update

###########################################################################

alter session set sql_trace = true;

select count(*)
from dual;

alter session set sql_trace = false;


the resulting trace file will be located in the user_dump_dest directory. this can
then be interpreted using tkprof at the commmand prompt as follows:

tkprof <trace-file> <output-file> explain=user/password@service


table=sys.plan_table

###################################################################

convert a long raw column into a clob or blob or


bfile.

alter table old_table modify ( c clob );


create table new_table as select c1, c2, to_lob(c3) from old_table;

rename table current_db.tbl_name to other_db.tbl_name;

alter table test rename column col1 to id;

alter table x
alter column c1 varchar(80)

alter table
table_name
modify
(
column_name varchar2(30)
);

export rows redefine table and import.

alter table ntiac_table add

(publication_date_copy date) ;

update ntiac_table
set publication_date_copy=publication_date;

alter table ntiac_table set unused column

publication_date;
alter table ntiac_table drop unused columns;

alter table ntiac_table rename column

publication_date_copy to publication_date;

..........generate 1 to 64 in words......................

select upper(to_char(to_date(rownum,'j'),'jsp')) text


from (select 1 from dual group by cube (1,2,3,4,5,6))

my palla_pcr2003@yahoo.co.uk.................pwd: ramu11

srinivasrao pilli: hi..find here video and photo coverage of johndoerr's


visit........ \\pjindia\backupofdevelopement\copy of johndoerrvisit

http://economictimes.indiatimes.com/articleshow/msid-1384411,curpg-1.cms swami
vivekananda's words.." a country's fate is in the hands of youth"...hatsoff 2 the
guys..'n gudluks 2 them..

delete from personnelwhere rowid in (select p2.rowid from personnel p2,


(select p3.id, p3.name, max(p3.rowid) max_rowid
from personnel p3
group by p3.id, p3.name) p4 where p2.rowid <> p4.max_rowid
and p2.id=p4.id and p2.name=p4.name );

select * from a where a.name in (select * from b where b.id=a.id);


select emp_id from emp where emp_id in ( select emp_id from dep ) ;

select table_name,constraint_name,constraint_type
from user_constraints c
where constraint_type='p'
and c.table_name in(select c1.table_name
from user_constraints c1
where c1.constraint_type='p')
/

################################################### buffer hit ratio of sql


statement###
select substr(a.sid,1,5) "sid",
substr(a.username,1,10) "user",
substr(a.osuser,1,23) user_nm,
--substr(a.machine,1,23) machine_nm,
substr(a.program,1,17) program,
b.consistent_gets "consgets",
b.block_gets "blockgets",
b.physical_reads "physreads",
100 * round((b.consistent_gets + b.block_gets - b.physical_reads) /
(b.consistent_gets + b.block_gets),3) hitratio
from v$session a, v$sess_io b
where a.sid = b.sid
and (b.consistent_gets + b.block_gets) > 0
and a.username is not null
and a.username not in ('sys','system')
order by hitratio asc
/

##########################################################drop
schema##################################

select 'alter table '||table_name||' disable constraint '||constraint_name||';'


from user_constraints
where constraint_type = 'r'
where table_name in('first table','sec table')
/
select 'prompt truncate cluster '||user||'.'||object_name||' in progress...'||
chr(10)||
'truncate '||object_type||' '||object_name||';'
from user_objects
where object_type = 'cluster'
order by 1
/
select 'prompt truncate table '||user||'.'||table_name||' in progress...'||
chr(10)||
'truncate table '||table_name||';'
from user_tables
where cluster_name is null
order by 1
/
select 'prompt drop '||object_type||' '||user||'.'||object_name||' in
progress...'||chr(10)||
'drop '||object_type||' '||object_name||
decode(object_type,'table',' cascade constraint;',';')
from user_objects
where object_type not in ('package body','index','cluster','trigger','lob')
and subobject_name is null
order by 1
/
select 'prompt drop '||object_type||' '||user||'.'||object_name||' in
progress...'||chr(10)||
'drop '||object_type||' '||object_name||';'
from user_objects
where object_type = 'cluster'
order by 1
/

steve @pcjmso> select 'create public synonym '||tname||' for steve.'||tname||';'


from tab where tabtype='table' and tname not like 'satya%' and tname not like
'vdk%' and tname not like 'smp%' and tname not like 'vbz%' and tname not like
'vmq%'and tname not like 'epc%'
steve @pcjmso> select 'grant select on '||tname||' to public;' from tab where
tabtype='table' and tname not like 'satya%' and tname not like 'vdk%' and tname
not like 'smp%' and tname not like 'vbz%' and tname not like 'vmq%'and tname not
like 'epc%'

----------------------------------------------------------------------------------
------------------

create or replace procedure fast_insert


as
vcount number;
vsysdate date;
type books_aat
is table of old_cardio_set%rowtype
index by pls_integer;
books books_aat;
begin

select /*+ rule */


d.*
bulk collect into books
from
cardio_workout a,
cardio_activity b,
cardio_activity_changed c,
old_cardio_set d
where a.workout_nr = b.workout_nr
and b.activity_nr = c.new_activity_nr
and c.change_nr = d.change_nr
and a.person_nr =123456;
forall book_index
in books.first .. books.last
insert into old_cardio_set
values books(book_index);
vcount := sql%rowcount;
end;
/

__________________________________________________________________________________
___________________