Important Oracle Query & Script
Important Oracle Query & Script
STATUS
Startup time
select name
, detected_usages
from dba_feature_usage_statistics
where detected_usages > 0
/
SESSION
Show all connected users
Select sql_text
from v$sqlarea
where (address, hash_value) in
(select sql_address, sql_hash_value
from v$session
where username like '&username')
/
select s.username
, s.sid
, s.serial#
, p.spid
, last_call_et
, status
from V$SESSION s
, V$PROCESS p
where s.PADDR = p.ADDR
and p.spid='&pid'
/
Or alternatively...
set lines 100 pages 999
select count(hash_value) cursors
, sid
, user_name
from v$open_cursor
group by
sid
, user_name
order by
cursors
/
INIT PARAMETERS
Show latent parameter changes
select name
, value
from v$parameter
where ismodified != 'FALSE'
/
USER
List users
And to unlock...
ROLE
Find a role
select *
from dba_roles
where role like '&role'
/
select grantee
, granted_role
, admin_option
from dba_role_privs
where grantee like upper('&username')
/
select privilege
, admin_option
from role_sys_privs
where role like '&role'
/
Administration - ASM
Display disk-groups
select name
, group_number
, disk_number
, total_mb
, free_mb
from v$asm_disk
order by group_number
/
select *
from v$asm_operation
/
Start CRS
crsctl start crs
Stop CRS
crsctl stop crs
Start/stop nodeapps
Start/stop asm
ocrcheck
Make a note of the interface name (eth1 in the following example), then
run the following:
oifcfg delif -global eth1
oifcfg setif -global eth1/<your new subnet>:cluster_interconnect
Submit a job
For example:
declare
job_id number;
begin
dbms_job.submit(
job_id
, 'andy.daily_data_clense'
, trunc(sysdate+1)+22/24
, 'sysdate+1'
, true);
end;
/
This will run a stored procedure called 'daily_data_clense' each day at 10pm.
Remove a job
begin
dbms_scheduler.create_program(
program_name=>'ANDY.job_test',
program_action=>'/home/oracle/andyb/job_test.sh',
program_type=>'EXECUTABLE',
comments=>'test job',
enabled=>TRUE);
end;
/
begin
dbms_scheduler.create_program(
program_name=>'ANDY.job_test',
program_action=>'andy.job_test',
program_type=>'STORED_PROCEDURE',
comments=>'test program',
enabled=>TRUE);
end;
/
begin
dbms_sheduler.create_job(
job_name=>'andy.andy_job_test',
program_name=>'andy.job_test',
start_date=>
)
show recyclebin
purge recyclebin
Structure - Tablespace
• Tablespace usage
• Show the files that comprise a tablespace
• Tablespaces >80% full
• User quotas on all tablespaces
• List all objects in a tablespace
• Show all tablespaces used by a user
• Create a temporary tablespace
• Alter a databases default temporary tablespace
• Show segments that are approaching max_extents
• List the contents of the temporary tablespace(s)
Tablespace usage
select tablespace_name
, ceil(sum(bytes) / 1024 / 1024) "MB"
from dba_extents
where owner like '&user_id'
group by tablespace_name
order by tablespace_name
/
To change maxextents
alter <segment_type> <segment_name> storage(maxextents 150);
Structure - Objects
• Find an object
• Invalid objects
• Show the size of an object
• All objects owned by a user
• Source code of a procedure
• Get an objects ddl (9i onwards)
• Display compilation errors and warnings
• Find all tables containing the specified column
• List all tables owned by a user sorted by size
Find an object
select text
from dba_source
where owner = 'ANDY'
and name = 'FILE_TEST'
and type = 'PACKAGE BODY'
order by line
/
show errors
show errors view <veiw_name>
show errors procedure <proc_name>
Structure - Indexes
select column_name
from dba_ind_columns
where index_name = '&index'
order by column_position
/
Structure - Files
You should only see online and system (maybe read-only too)
select distinct status from v$datafile
/
select file_name
from dba_data_files
where autoextensible = 'YES'
/
spool rename.sql
spool off
List controlfiles
select name
from v$controlfile
/
• Remove drop
• add logfile members
• List members and sizes
Remove drop
Structure - Undo
• Converting from Rollback to Undo
• Display the rollback segments
• Alter undo retention
• What's in undo
• Is anything rolling back at the moment?
select segment_name
, status
from dba_rollback_segs
/
What's in undo
select tablespace_name
, status
, count(*) as HOW_MANY
from dba_undo_extents
group by tablespace_name
, status
/
Look for the used_ublk value decreasing. If it is, the session connected with it is rolling back.
When it reaches zero, rollback is complete.
set lines 100 pages 999
col username format a15
col command format a20
select ses.username
, substr(ses.program, 1, 19) command
, tra.used_ublk
from v$session ses
, v$transaction tra
where ses.saddr = tra.ses_addr
/
Structure - Constraints
List tables that are using the specified table as a foreign key
or...
create materialized view log on <table>
tablespace <tablespace_name>
/
List all materialized view logs
select log_owner
, log_table
from dba_mview_logs
/
Structure - Partitions
Add a partition
or...
alter table <table_name>
add partition <partition_name> values (<value>)
tablespace <tablespace_name>
/
Split a partition
Drop a partition
Truncate a partition
Performance - General
select sql_text
from v$sqlarea
where users_executing > 0
/
Session statistics
select sn.name
, st.value
from v$sesstat st
, v$statname sn
where st.STATISTIC# = sn.STATISTIC#
and st.VALUE > 0
and st.SID = &SID
order by value desc
/
File io stats
Requires timed_statistics=true
set lines 80 pages 999
col fname heading "File Name" format a60
col sizemb heading "Size(Mb)" format 99,999
col phyrds heading "Reads" format 999,999,999
col readtim heading "Time" format 99.999
col phywrts heading "Writes" format 9,999,999
col writetim heading "Time" format 99.999
select lower(name) fname
, (bytes / 1048576) sizemb
, phyrds
, readtim
, phywrts
, writetim
from v$datafile df
, v$filestat fs
where df.file# = fs.file#
order by 1
/
In session tracing
To switch it on:
exec dbms_system.set_sql_trace_in_session (<sid>, <serial#>, true);
To switch it off:
exec dbms_system.set_sql_trace_in_session (<sid>, <serial#>, false);
To switch it on:
alter session set events '10046 trace name context forever, level 8';
To switch it off:
alter session set events '10046 trace name context off';
Note. The current setting is halfway down and has a read factor of one.
set lines 100 pages 999
col est_mb format 99,999
col estd_physical_reads format 999,999,999,999,999
select size_for_estimate est_mb
, estd_physical_read_factor
, estd_physical_reads
from v$db_cache_advice
where name = 'DEFAULT'
order by size_for_estimate
/
select do.object_name
, row_wait_obj#
, row_wait_file#
, row_wait_block#
, row_wait_row#
, dbms_rowid.rowid_create (1, ROW_WAIT_OBJ#, ROW_WAIT_FILE#,
ROW_WAIT_BLOCK#, ROW_WAIT_ROW#)
from v$session s
, dba_objects do
where sid=&sid
and s.ROW_WAIT_OBJ# = do.OBJECT_ID
/
List locks
select decode(lob.kglobtyp,
0, 'NEXT OBJECT', 1, 'INDEX', 2, 'TABLE', 3, 'CLUSTER',
4, 'VIEW', 5, 'SYNONYM', 6, 'SEQUENCE',
7, 'PROCEDURE', 8, 'FUNCTION', 9, 'PACKAGE',
11, 'PACKAGE BODY', 12, 'TRIGGER',
13, 'TYPE', 14, 'TYPE BODY',
19, 'TABLE PARTITION', 20, 'INDEX PARTITION', 21, 'LOB',
22, 'LIBRARY', 23, 'DIRECTORY', 24, 'QUEUE',
28, 'JAVA SOURCE', 29, 'JAVA CLASS', 30, 'JAVA RESOURCE',
32, 'INDEXTYPE', 33, 'OPERATOR',
34, 'TABLE SUBPARTITION', 35, 'INDEX SUBPARTITION',
40, 'LOB PARTITION', 41, 'LOB SUBPARTITION',
42, 'MATERIALIZED VIEW',
43, 'DIMENSION',
44, 'CONTEXT', 46, 'RULE SET', 47, 'RESOURCE PLAN',
48, 'CONSUMER GROUP',
51, 'SUBSCRIPTION', 52, 'LOCATION',
55, 'XML SCHEMA', 56, 'JAVA DATA',
57, 'SECURITY PROFILE', 59, 'RULE',
62, 'EVALUATION CONTEXT','UNDEFINED'
) object_type
, lob.kglnaobj object_name
, pn.kglpnmod lock_mode_held
, pn.kglpnreq lock_mode_requested
, ses.sid
, ses.serial#
, ses.username
from v$session_wait vsw
, x$kglob lob
, x$kglpn pn
, v$session ses
where vsw.event = 'library cache lock'
and vsw.p1raw = lob.kglhdadr
and lob.kglhdadr = pn.kglpnhdl
and pn.kglpnmod != 0
and pn.kglpnuse = ses.saddr
/
select ses.username
, ddl.session_id
, ses.serial#
, owner || '.' || ddl.name object
, ddl.type
, ddl.mode_held
from dba_ddl_locks ddl
, v$session ses
where owner like '%userid%'
and ddl.session_id = ses.sid
/
Waits by file
Segment Waits
select object_name
, obj#
, statistic_name
, value
from v$segment_statistics
where owner like '&owner'
and statistic_name like '%waits%'
and value > 0
order by statistic_name
, value desc
/
Then run this to identify the file, block and reason code...
select p1 "File #"
, p2 "Block #"
, p3 "Reason Code"
from v$session_wait
where event = 'buffer busy waits'
/
Note. You might need to run this a few times before anything is displayed.
select n.name
, s.value
from v$statname n
, v$sysstat s
where n.statistic# = s.statistic#
order by n.class
, n.name
/
Performance - Statistics
Or...
execute dbms_stats.gather_database_stats( -
estimate_percent => 1, -
method_opt => 'FOR ALL COLUMNS SIZE 1',-
cascade => TRUE);
Gather stats for a single schema...
execute dbms_stats.gather_schema_stats('SCOTT');
Or...
execute dbms_stats.gather_schema_stats( -
ownname => 'SCOTT', -
estimate_percent => 1, -
method_opt => 'FOR ALL COLUMNS SIZE 1',-
cascade => TRUE);
You can let oracle come up with the estimate figure by using dbms_stats.auto_sample_size
or...
execute dbms_stats.gather_schema_stats( -
ownname => 'SYS', -
cascade => TRUE);
Table statistics
exec dbms_stats.gather_table_stats('<owner>', '<table_name>');
Delete stats
exec dbms_stats.delete_database_stats;
exec dbms_stats.delete_schema_stats('SCOTT');
execute dbms_stats.gather_system_stats('Start');
Wait for a while - idealy with the database under a typical workload
execute dbms_stats.gather_system_stats('Stop');
This is useful if you are running an analyze and want to see how much is left to do
select count(last_analyzed) left_to_do
from dba_tables
where owner = '&schema'
and trunc(last_analyzed) < trunc(sysdate)
order by 1
/
@?/rdbms/admin/utlxplan.sql
Autotrace
To switch it on:
column plan_plus_exp format a100
To switch it off:
set autotrace off
Explain plan
or...
explain plan set statement_id = 'bad1' for
select...
select sql_text
from v$sqlarea
where hash_value = '&hash'
/
select executions
, cpu_time
, disk_reads
, buffer_gets
, rows_processed
, buffer_gets / executions
from v$sqlarea
where hash_value = '&hash'
/
Performance - Memory
• SGA breakdown
• PGA usage by username
• Display pool usage
SGA breakdown
select name
, sum(bytes)
from v$sgastat
where pool like 'shared pool'
group by name
/
Performance - Statspack
• Take a snapshot
• Delete one or more snapshots
• Generate a report
• List snapshots
• Install statspack
• Uninstall statspack
• Schedule and hourly snapshot
Take a snapshot
exec statspack.snap;
Or to specify a level...
exec statspack.snap(i_snap_level => 6, i_modify_parameter => 'true');
Level 0 - This level captures general statistics, including rollback segment, row cache, SGA,
system events, background events, session events, system statistics, wait statistics, lock statistics,
and Latch information.
Level 5 - This level includes capturing high resource usage SQL Statements, along with all data
captured by lower levels.
Level 6 - This level includes capturing SQL plan and SQL plan usage information for high
resource usage SQL Statements, along with all data captured by lower levels.
Level 7 - This level captures segment level statistics, including logical and physical reads, row
lock, itl and buffer busy waits, along with all data captured by lower levels.
Level 10 - This level includes capturing Child Latch statistics, along with all data captured by
lower levels.
@?/rdbms/admin/sppurge;
Generate a report
@?/rdbms/admin/spreport.sql
List snapshots
Install statspack
Uninstall statspack
@?/rdbms/admin/spdrop
Schedule and hourly snapshot
@?/rdbms/admin/spauto.sql
Performance - AWR
Produce a report
@?/rdbms/admin/awrrpt.sql
To see the snapshot interval and retention period
exec dbms_workload_repository.create_snapshot
Create a baseline
Remove a baseline
and to disable...
exec dbms_scheduler.disable('GATHER_STATS_JOB')
@?/rdbms/admin/ashrpt.sql
Backup - DataGuard
• Startup commands
• To remove a delay from a standby
• Cancel managed recovery
• Register a missing log file
• If FAL doesn't work and it says the log is already registered
• Check which logs are missing
• Disable/Enable archive log destinations
• Turn on fal tracing on the primary db
• Stop the Data Guard broker
• Show the current instance role
• Logical standby apply stop/start
• See how up to date a physical standby is
• Display info about all log destinations
• Display log destinations options
• List any standby redo logs
Startup commands
startup nomount
alter database mount standby database;
alter database recover managed standby database disconnect;
select database_role
from v$database
/
Stop...
alter database stop logical standby apply;
Start...
alter database start logical standby apply;
select ds.dest_id id
, ad.status
, ds.database_mode db_mode
, ad.archiver type
, ds.recovery_mode
, ds.protection_mode
, ds.standby_logfile_count "SRLs"
, ds.standby_logfile_active active
, ds.archived_seq#
from v$archive_dest_status ds
, v$archive_dest ad
where ds.dest_id = ad.dest_id
and ad.status != 'INACTIVE'
order by
ds.dest_id
/
Backup - Flashback
exp / parfile=full_scr9.par
parfile...
userid=system/******
file=full_scr9.dmp
log=full_scr9.log
flashback_time='2006-09-13 12:00:00'
shutdown immediate
startup mount
alter database flashback on;
alter database open;
What is the earliest time the database can be flashed back to?
shutdown immediate
startup mount exclusive
or...
flashback database to timestamp to_timestamp('22/04/2007 19:30:00','dd/mm/yyyy
hh24:mi:ss');
@?/rdbms/admin/utlrp.sql
Having a sysaux tablespace is a requirement in 10g. So, if you haven't already got one, create one
now.
create tablespace sysaux
datafile '<file_name>' size 512M
extent management local
segment space management auto
/
• 3. Run utlu102i.sql
This utility script checks that the database is ready to be upgraded to 10g. It also identifies any
actions that need to be taken. The script is located in the 10g oracle home, so you will need to
specify the full path to it.
@/u01/app/oracle/product/10.2.0/db_1/rdbms/admin/utlu102i.sql
Review the output and make any necessary alterations. Make a note of how many invalid objects
there are.
shutdown immediate
• 5. Copy the spfile (or pfile) and the password file from the existing home to the 10g one.
cp ${ORACLE_HOME}/dbs/*${ORACLE_SID}* <new_home>/dbs/
• 6. Edit oratab
Alter /etc/oratab (or /var/opt/oracle/oratab) to point to the10g home. Once done, rerun oraenv to
bring the alteration into effect.
startup upgrade
This next bit is the upgrade itself. It takes roughly half an hour to complete. Spool the output to a
file so that you can review it afterward.
@?/rdbms/admin/catupgrd.sql
@?/rdbms/admin/utlrp.sql
Compare the number of invalid objects with the number noted in step 3. It should hopefully be the
same or less.
@?/rdbms/admin/utlu102s.sql
shutdown immediate
vi ${ORACLE_HOME}/dbs/init${ORACLE_SID}.ora
Alter/remove parameters identified in step 9. Set compatible to 10.2.0.0.0
startup
shutdown immediate
startup
That's it!
There are situations where it is useful to capture the SQL that a particular user is running in the
database. Usually you would simply enable session tracing for that user, but there are two potential
problems with that approach.
The first is that many web based applications maintain a pool of persistent database connections
which are shared amongst multiple users. The second is that some applications connect, run some
SQL and disconnect very quickly, making it tricky to enable session tracing at all (you could of
course use a logon trigger to enable session tracing in this case).
A quick and dirty solution to the problem is to capture all SQL statements that are run between two
points in time.
The following procedure will create two tables, each containing a snapshot of the database at a
particular point. The tables will then be queried to produce a list of all SQL run during that period.
If possible, you should do this on a quiet development system - otherwise you risk getting way too
much data back.
This first query will list all query hashes that have been executed:
• select aft.hash_value
• from sql_exec_before bef
• , sql_exec_after aft
• where aft.executions > bef.executions
• and aft.hash_value = bef.hash_value (+)
• /
This one will display the hash and the SQL itself:
• 5. Tidy up
Don't forget to remove the snapshot tables once you've finished:
• drop table sql_exec_before
• /
•
• drop table sql_exec_after
• /