Archive for the ‘Oracle’ Category

It’s convinent to post blog via email. After struggling for a while, got the plugin postie to do this functionalities. Which mean more posting from me going forward.

convert this post to pdf.

Set the login info, otherwise you will give session expired error.

./emcli setup -url=https://source_hostname:7799/em  -username=sysman
./emcli export_report -title="Database Size" -owner="SYSMAN" -output_file="db_size.xml"
Report "Database Size", owned by "SYSMAN", has been exported from the repository.
Exported reports may not contain all information from original report.  Repository specific information such as targets, administrator access, and schedules are not exported.  Imported reports should be edited after import to supply all necessary report parameters.

In target

./emcli setup -url=https://target_hostname:7799/em  -username=sysman
./emcli import_report -files="db_size.xml"
File "db_size.xml" has been imported into the repository.
Imported reports should be edited after import to supply all necessary report parameters.
convert this post to pdf.
./emcli setup -url=https://source_hostname:7799/em -username=sysman

If you don’t issue the above command, you will get error like session expired. get the name and target type from below query

 SELECT TEMPLATE_NAME,TARGET_TYPE FROM sysman.MGMT_TEMPLATES ;
./emcli export_template -name="Common_Database_Template" -arget_type="oracle_database" -output_file=Common_Database_Template.out

./emcli export_template -name="Common_Sybase_Template" -target_type="sybase_ase" -output_file=Common_Sybase_Template.out

./emcli export_template -name="Common_Clusterdb_template" -target_type="rac_database" -output_file=Common_Clusterdb_template.out

./emcli export_template -name="Common_ASM_template" -target_type="osm_instance" -output_file=Common_ASM_template.out

./emcli export_template -name="Common_Agent_template" -target_type="oracle_emd" -output_file=Common_Agent_template.out

./emcli export_template -name="Common_listener_Template" -target_type="oracle_listener" -output_file=Common_listener_Template.out

./emcli export_template -name="Common_Host_template" -target_type="host" -output_file=Common_Host_template.out

To import

./emcli setup -url=http://target_hostname:7788/em -username=sysman

Make sure that if the oms is secured use https, if not use http in -url. If you want to import as different user you can change the -username to respective users.

 ./emcli import_template -files="Common_Database_Template.out;Common_Sybase_Template.out;
Common_Clusterdb_template.out;Common_ASM_template.out;
Common_Agent_template.out;Common_listener_Template.out;
Common_Host_template.out"

sybase template will fail if sybase plugin is not installed. If there is already a name with exisiting template, that template will not be added.

convert this post to pdf.

By mistake if you have used wrong port while configuring SLB, the oms will not come up.

./emctl secure oms -sysman_pwd xyz123 -reg_pwd abc123 -host hostname -secure_port 443 -slb_port 443 -slb_console_port 443

You will be getting below error while starting the oms.

./emctl start oms
Oracle Enterprise Manager 11g Release 1 Grid Control 
Copyright (c) 1996, 2010 Oracle Corporation.  All rights reserved.
Starting WebTier…
WebTier Could Not Be Started
Error Occurred: WebTier Could Not Be Started
Please check /u01/app/oracle/Middleware/oms11g/em/EMGC_OMS2/sysman/log/emctl.log for error details

when you check the log, basically the apache will not start. You can see the error in /u01/app/oracle/Middleware/oms11g/WebTierIH1/diagnostics/logs/OHS/ohs1/ohs1.log

The error will look like

[pid: 9633918] [tid: 1] [user: oracle] [VirtualHost: main] (13)Permission denied:  make_sock: could not bind to address [::]:443
[pid: 9633918] [tid: 1] [user: oracle] [VirtualHost: main]  no listening sockets available, shutting down

3918] [tid: 1] [user: oracle] [VirtualHost: main]  Unable to open logs

you will have to change the port back in

/u01/app/oracle/Middleware/oms11g/WebTierIH1/config/OHS/ohs1/httpd_em.conf

note there will be a backup file automatically taken whenever any change to above file. Overwrite the correct copy with incorrect one.

convert this post to pdf.

There is easier way of  pointing agent to new oms in 11g.

Go the $AGENT_HOME/bin and execute just one command,

$ ./emctl switchOMS https://oms_hostname:1159/em/upload
Oracle Enterprise Manager 11g Release 1 Grid Control 11.1.0.1.0
Copyright (c) 1996, 2010 Oracle Corporation.  All rights reserved.
SwitchOMS succeeded.

If you have agent registration passwd enabled, do the below steps,

$./emctl stop agent

$./emctl secure agent ‘pwd’

$./emctl start agent

Before 11g, you will have to follow steps given metalink#413228.1

convert this post to pdf.

In case if you have lost agent registration pwd and want to create new one. Go to setup=> registration pwd and remove the existing one.

then in the OMS server execute below command,

/emctl secure setpwd
Oracle Enterprise Manager 11g Release 1 Grid Control 
Copyright (c) 1996, 2010 Oracle Corporation.  All rights reserved.
Enter Enterprise Manager Root Password :
Enter New Agent Registration Password :
Registration Password added successfully.

root password above is sysman password

convert this post to pdf.

It’s specific to AIX environment. While doing oms installation during the agent configuration stage it failed. Even a fresh installation of agent in oms host will fail with similar error. You will not be able to stop or start the agent.

It’s a aix bug, metalink#1298284.1 talks about it. There is a workaround provided in that note.

Workaround provided by Oracle:

1. export $ORACLE_HOME=<agent home>/sysman/lib
2. cd <agent home>/sysman/lib
3. backup env_emagent.mk
4. Modify env_emagent.mk:
   Search “LIB_JVM_LINK =”
   Remove the “-blazy” option from LIB_JVM_LINK definition
   Save the file
5. /usr/sbin/slibclean

5.1. export OBJECT_MODE=32 ==> Pls note this step is missing in the oracle document

6. make -f ins_emagent.mk agent

convert this post to pdf.

We have 2 node cluster running in 11gR1 crs and asm. We have a requirement to upgrade to 11gR2 grid infrastrcuture. As we know grid infrastructure is one home for crs and asm unlike 11gR1. Also in case of upgrade if the crs and asm of 11gR1 was installed in oracle account, you can install the new grid infrastructure only on oracle account.  Where as for new install you can have grid infrastructure in grid account and your DBs in oracle accounts.

What we tried is a rolling upgrade, since the steps are not clear we didn’t actually test the application after upgrading one node. But guess what outlined here will give you a clue and may help you to do rolling upgrade.

There are totalling 7 zip files for linux, download to a folder and unzip each one of it. At the end of unzip you will have folder like grid,database,client etc.,

grid folder will have installables for grid infrastrucutre,

set the display and run the runInstaller. Some reason our environment we used  -ignoreInternaldriver flag with runInstaller.

skip the software updates,

Select the ‘Upgrade Oracle Grid Infrastructure or Oracle Automatic Storage Management”

Though you select one node, software will be pushed to all the nodes in that cluster. You can choose to run rootupgrade.sh or not later. Since you selected one node asm upgrade has to be done manually.

Next screen will ask for scan ip info and the port. Port give which ever required.

Make sure everything it is oinstall group  or whatever relevant in your environment.

Next

 

Next

 Next you will get the summary tab. If everything fine select Next click ‘Install’.

End of this it will ask to run rootupgrade.sh. You can run one node at a time. At the end of ‘rootupgrade.sh’ it will bring the crs in new home and ASM with older version. Pls node only if you run rootupgrade.sh the asm will come up.

“Configuration assistants have not been executed by the installer, since only a subset of nodes was selected for the upgrade. Run rootupgrade.sh on the rest of the nodes and then proceed to execute the configuration assistants.

“/u01/app/11.2.0/grid/cfgtoollogs/configToolAllCommands” script contains all commands that the configuration assistants will complete. This file may be used to run the configuration assistants outside of OUI. Note that you may have to update this script with passwords (if any) before you can run the script.”

Note you will have run rootupgrade.sh in all the node and comeback and run “/u01/app/11.2.0/grid/cfgtoollogs/configToolAllCommands”. This is because you have selected only one node during the upgrade. configToolAllCommands is a script which call runconfig.sh

Set the environment variable to new grid infrastructure and start the asmca for upgrading the +asm. If you have specified asmca_rolling_upgrade=true, it will upgrade asm in each node in rolling fashion.

This is the stage we are not sure what to do. We ran the rootupgrade.sh in both the node and started asmca with asmca_rolling_upgrade=true. asmca_rolling_upgrade needs to be set as environment variable. When you set this environment variable, it does the asm upgrade in both the node.

I belive after rootupgrade.sh and asmca on one node could have brought the application up on one node.

When you set the environment variable pointing to new grid and run asmca from $ORACLE_HOME/bin/asmca you will see the screen like below.

convert this post to pdf.

You don’t need tns or ldap entry to connect to your db from your desktop. 10g uses service name and 11g uses sid.

C:\Documents and Settings>tnsping hostname:1141/emrep

TNS Ping Utility for 32-bit Windows: Version 11.2.0.1.0 – Production on 24-FEB-2

011 18:42:59

Copyright (c) 1997, 2010, Oracle. All rights reserved.

Used parameter files:

c:\tns\sqlnet.ora

Used EZCONNECT adapter to resolve the alias

Attempting to contact (DESCRIPTION=(CONNECT_DATA=(SERVICE_NAME=emrep))(ADDRESS=(PROTOCOL=TCP)(HOST=xxxxxxxxx)(PORT=1141)))

OK (440 msec)

C:\Documents and Settings\>sqlplus dbsnmp/*******@hostname:1141/emrep

SQL*Plus: Release 11.2.0.1.0 Production on Thu Feb 24 18:44:30 2011

Copyright (c) 1982, 2010, Oracle. All rights reserved.

Connected to:

Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 – 64bit Production

With the Partitioning, Oracle Label Security, OLAP, Data Mining Scoring Engine

and Real Application Testing options

SQL> select host_name from v$instance;

HOST_NAME

—————————————————————-

hostname

SQL> show parameter db_name

NAME TYPE

———————————— ——————————–

VALUE

——————————

db_name string

emrep

to work you need below entry in your sqlnet.ora,

NAMES.DIRECTORY_PATH= (TNSNAMES, EZCONNECT)

convert this post to pdf.

If you want top 200 sql in your report
dbms_workload_repository.modify_snapshot_settings (topnsql=> 200)

If you want a particular sql even if it’s not in your top list.
dbms_workload_repository.add_colored_sql(:sql_id)

trace one or more sql id
alter session set events ‘sql_trace [sql: sql_id1 |sql_id2]‘

I know about the last one.

convert this post to pdf.

Pls see this interesting note,

http://blogs.oracle.com/optimizer/2011/02/how_do_i_deal_with_a_third_party_application_that_has_embedded_hints_that_result_in_a_sub-optimal_ex.html

convert this post to pdf.

If one of your data file is corrupted in Production or in Standby, you can pick that data file from other location and restore.
We don’t have to recreate the standby db or restore the DB. Please find the steps we followed..

SQL> select * from v$database_block_corruption;

FILE#     BLOCK#     BLOCKS CORRUPTION_CHANGE# CORRUPTIO
———- ———- ———- —————— ———
36     289469          1                  0 CORRUPT
75      96029          1                  0 CORRUPT

Primary:

RMAN> backup as copy datafile 36 format ‘/ora_dr_backup/rman/drdb/data36.dbf’;

RMAN>backup as copy datafile 75 format ‘/ora_dr_backup/rman/drdb/data75.dbf’;

ftp Standby

SQL> alter database datafile 36 offline ;   If your standby datafile is corrupted use ‘drop’ option
SQL> alter database datafile 75 offline ;  If your standby datafile is corrupted use ‘drop’ option

RMAN> catalog datafilecopy  ‘/ora_dr_backup/rman/drdb/data36.dbf’;

RMAN> catalog datafilecopy ‘/ora_dr_backup/rman/drdb/data75.dbf’;

RMAN> list copy of datafile 36; ==> Check above mountpoint is listed

RMAN> list copy of datafile 75; ==> Check above mountpoint is listed

RMAN> restore datafile 36;

SQL> alter database datafile 36 online;

RMAN> recover datafile 36;

RMAN> restore datafile 75;

SQL> alter database datafile 75 online;

RMAN> recover datafile 75;

convert this post to pdf.

Got lot of insight on various process in DG environment.

http://forums.oracle.com/forums/thread.jspa?messageID=4090175

convert this post to pdf.

New 11gR2 feature. Seems interesting. Can it be a alternate to active-passive cluster or Dataguard? May not be for DG, as DG protects you in cases like corruption.

http://download.oracle.com/docs/cd/E11882_01/rac.112/e16795/onenode.htm

convert this post to pdf.

Sometime you may want to run the rda.sh has nohup. But it take lot of input. You can create the setup.cfg using

./rda.sh -S

Again you will have to input the password if you are collecting via system.

./rda.sh -A system

enter the system password. In the same session

nohup ./rda.sh &

password what you set is valid only that session. You can run nohup from anothe r session.

you can see in the setup.cfg, newly added content like below.

#B.Multi-run collection indicator
S999END_MRC=0
#T.Password for ‘SYSTEM’
SQL_PASSWORD_SYSTEM=’(<WDR8F%S93(`’

convert this post to pdf.

If you have used repvfy utility in grid control, pls see the sql generated under emdiag/log location. Out of repvfy a sql file generated and content of those sql’s are pretty useful.

Also on other note if you want to diagonise one target, you can use below command.

./repvfy -usr SYSMAN -tns emrep -pwd dump target -name -type oracle_database

convert this post to pdf.

If you have administered Grid Control, you would have known two types of corrective actions.

1. Corrective Action Script
2. Agent Response Script

What it does is you can invoke a remediation script based on an action. Suppose you want to add a datafile if the tablespace usage is nearing 95%, you can write a script and keep in the target server. Configure this script in metrics and policy setting of tablespace usage metrics. So whenever any tablespace usage crossing 95%, the script stored in the target server will be invoked.

The advantage is that it avoid human interference,errors and enhance the effective usage of DBA.

Consider if you have 1000s of targets and each targets you need to add remediation scripts to the metrics, it’s going to take lot of time.
What if i have option to invoke the Agent response script via sqlplus. It’s going to give me better control. I can write a package, which will poll the metrics tables and invoke the scripts based on varying conditions. This is not possible to implement in metrics and policy tab.

Opened a SR with oracle and justification like below is given,
1. We have 1000s of targets for most of which we need to enable response action. Manually updating each target is time consuming. We can’t have template as the scripts getting invoked will have different name based on db name.
2. There are different groups of targets for which invoking response actions script will be based on certain scenarios. If response action can be invoked manually, then we can put our conditions and invoke accordingly.
3. We will have control on one place. Modifying something will be quicker instead of going to each target’s metric & policy and changing.

We have filed enhancement request filed with oracle.

ER IS : Bug 10214800 – INVOKING ” RESPONSE ACTION” VIA SQLPLUS

convert this post to pdf.

If we could simulate the performance issue in sqlplus, consider we can fix the issue most of the time. Incase if you need oracle supports help in a query, you can build the test case like below.

SQL> DECLARE tc clob;
  2  BEGIN
  3  DBMS_SQLDIAG.EXPORT_SQL_TESTCASE(
  4  DIRECTORY=>'DATA_PUMP_DIR',
  5  SQL_ID=>'6bcwxgty705p8',
  6  TESTCASE=>tc);
  7  END;
  8  /

PL/SQL procedure successfully completed.

You need to supply sql_id and directory name. You can zip this and sent it to support. If you give exportdata to true, expdp will include table data.

This is tested in 11gR2.

convert this post to pdf.

impdp will do a direct load import. This is one way to confirm


SQL> select sum(bytes/1024/1024) from dba_segments where segment_name='T';

SUM(BYTES/1024/1024)
--------------------
            176.1875

SQL> truncate table t;

Table truncated.

SQL> alter table t COMPRESS FOR OLTP ;

Table altered.

Note: compress for all operation is deprecated in 11gR2 instead it will be compress for oltp


SQL> host impdp directory=data_pump_dir dumpfile=xyz.dmp tables='test.t' table_e
xists_action=append

Import: Release 11.2.0.1.0 - Production on Thu Oct 14 21:30:33 2010

Copyright (c) 1982, 2009, Oracle and/or its affiliates.  All rights reserved.

Username: / as sysdba

Connected to: Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Produc
tion
With the Partitioning and Real Application Testing options
Master table "SYS"."SYS_IMPORT_TABLE_01" successfully loaded/unloaded
Starting "SYS"."SYS_IMPORT_TABLE_01":  /******** AS SYSDBA directory=data_pump_d
ir dumpfile=xyz.dmp tables='test.t' table_exists_action=append
Processing object type TABLE_EXPORT/TABLE/TABLE
ORA-39152: Table "TEST"."T" exists. Data will be appended to existing table but
all dependent metadata will be skipped due to table_exists_action of append
Processing object type TABLE_EXPORT/TABLE/TABLE_DATA
. . imported "TEST"."T"                                  149.2 MB 1689984 rows
Job "SYS"."SYS_IMPORT_TABLE_01" completed with 1 error(s) at 21:31:03

Let us check the size now.


SQL> select sum(bytes/1024/1024) from dba_segments where segment_name='T';

SUM(BYTES/1024/1024)
--------------------
             72.1875

From 176mb the size is reduced to 72mb. Not let us try the direct load after truncating the table,


SQL> alter table t compress for DIRECT_LOAD OPERATIONS;

Table altered.

SQL> host impdp directory=data_pump_dir dumpfile=xyz.dmp tables='test.t' table_e
xists_action=append status=2 

Import: Release 11.2.0.1.0 - Production on Thu Oct 14 21:32:28 2010

Copyright (c) 1982, 2009, Oracle and/or its affiliates.  All rights reserved.

Username: / as sysdba

Connected to: Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Produc
tion
With the Partitioning and Real Application Testing options
Master table "SYS"."SYS_IMPORT_TABLE_01" successfully loaded/unloaded
Starting "SYS"."SYS_IMPORT_TABLE_01":  /******** AS SYSDBA directory=data_pump_d
ir dumpfile=xyz.dmp tables='test.t' table_exists_action=append
Processing object type TABLE_EXPORT/TABLE/TABLE
ORA-39152: Table "TEST"."T" exists. Data will be appended to existing table but
all dependent metadata will be skipped due to table_exists_action of append
Processing object type TABLE_EXPORT/TABLE/TABLE_DATA
Job "SYS"."SYS_IMPORT_TABLE_01" completed with 1 error(s) at 21:43:55

SQL> select sum(bytes/1024/1024) from dba_segments where segment_name='T';

SUM(BYTES/1024/1024)
--------------------
             72.1875

Now the size has reduced from 176mb


SQL> alter table t nocompress;

Table altered.

SQL> host impdp directory=data_pump_dir dumpfile=xyz.dmp tables='test.t' table_e
xists_action=append status=2 

SQL> select sum(bytes/1024/1024) from dba_segments where segment_name='T';

SUM(BYTES/1024/1024)
--------------------
            176.1875

Without compression it’s 176mb.

convert this post to pdf.

If your DB is applied with patch#8198906, then beware that you may run into corruption when extending the table manually.
This patch is obselete now. You have to uninstall and install 9711859.

If your shop is managing 1000s of DBs then how to find out on which installation this patch is applied.

If these DBs are managed in OEM, then you can use below query

select * from  mgmt_inv_patch_fixed_bug  where bug_number=8198906;
convert this post to pdf.

In one of our application, we have a daily partition on few critical tables. After data load, we gather statitics. Stats gathering should complete in 2 hrs. 2hrs is pretty high due to memory usage on the server. But that’s different issue which we are working parallely.
We had a issue, where the stats gathering job failed. Stats was scheduled to complete 9am.Since the stats failed BO reports started going slow. Business can’t afford to wait 2hrs for stats gathering.
As a quick fix we took previous day stats and applied to today’s partition.

If subpartition exist and if you are trying to copy partition statistics, we will be getting error message like below,

ERROR at line 1:
ORA-06533: Subscript beyond count
ORA-06512: at "SYS.DBMS_STATS", line 17130
ORA-06512: at line 2

If subpartition exist, run the stats gathering first and followed by partition copy stats

exec dbms_stats.copy_table_stats(user, 'TAB1', srcpartname=>'P_20100927_S', dstpartname=>'P_20100928_S');

Followed by partition stats, to which you will get the error. Which you can ignore.

exec dbms_stats.copy_table_stats(user, 'TAB1', srcpartname=>'P_20100927', dstpartname=>'P_20100928');
ERROR at line 1:
ORA-06533: Subscript beyond count
ORA-06512: at "SYS.DBMS_STATS", line 17130
ORA-06512: at line 2

Bug#8866627 might fix it has it has fix for many dbms_stats related bugs.

convert this post to pdf.

Many of our sessions are waiting on ‘cursor: pin S wait on X’ in one our DB. Connecting to DB via Toad,sql developer is hanging.

Most of the sessions from toad,sql developer is waiting on, as the query all_objects during the startup.

SELECT 'X' FROM SYS.ALL_OBJECTS WHERE    OBJECT_NAME = :1 AND OWNER = :2 AND
OBJECT_TYPE = 'TABLE'

Some kind of contention around all_objects.

To find the blocking session,

SELECT sid,last_call_et,p2raw
,to_number(substr(to_char(rawtohex(p2raw)), 1, 8), 'XXXXXXXX') sid "Blocking Sid"
FROM v$session
WHERE event = 'cursor: pin S wait on X'
order by last_call_et;

Get the record having max last_call_et and take the correspond “Blocking Sid”. Killing the “Blocking Sid” has cleared the DB issue. Most likely this case killing sessions will take time, so kill -9 the os process.

Blocking Sid in our case is waiting on sql_id 1j4husc7c0k5u

To get the query,

SQL> select * from table(dbms_xplan.display_awr('1j4husc7c0k5u'));

SQL_ID 1j4husc7c0k5u
--------------------
select i.obj#, i.rowcnt, i.leafcnt, i.distkey, i.lblkkey, i.dblkkey,i.clufac, i.blevel,
i.analyzetime, i.samplesize, decode(i.pctthres$,null,null,mod(trunc(i.pctthres$/256),256)),
i.flags, ist.cachedblk, ist.cachehit, ist.logicalread from ind$ i, ind_stats$ ist where
i.obj# = ist.obj#(+) and i.bo#=:1 order by i.obj#

Plan hash value: 1414749717

---------------------------------------------------------------------------------------------------
| Id  | Operation                     | Name              | Rows  | Bytes | Cost (%CPU)| Time     |
---------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT              |                   |       |       |     4 (100)|          |
|   1 |  SORT ORDER BY                |                   |     4 |   400 |     4  (25)| 00:00:01 |
|   2 |   NESTED LOOPS OUTER          |                   |     4 |   400 |     3   (0)| 00:00:01 |
|   3 |    TABLE ACCESS CLUSTER       | IND$              |     4 |   192 |     2   (0)| 00:00:01 |
|   4 |     INDEX UNIQUE SCAN         | I_OBJ#            |     1 |       |     1   (0)| 00:00:01 |
|   5 |    TABLE ACCESS BY INDEX ROWID| IND_STATS$        |     1 |    52 |     1   (0)| 00:00:01 |
|   6 |     INDEX UNIQUE SCAN         | I_IND_STATS$_OBJ# |     1 |       |     1   (0)| 00:00:01 |
---------------------------------------------------------------------------------------------------

May be auto stats gathering happening on that time creating contention in IND$. This behaviour is documented in note#6011045.8

convert this post to pdf.

Refer to below link for manually creating and evolving the baseline plan.


http://www.oracle-base.com/articles/11g/SqlPlanManagement_11gR1.php

In the example given in the url above, after adding index we need to manually evolve. This helps in accepting the right plan.

But what happens if i drop the index.


SQL> drop index spm_test_tab_idx;

Index dropped.

SQL> EXEC DBMS_STATS.gather_table_stats(USER, 'SPM_TEST_TAB', cascade=>TRUE);

PL/SQL procedure successfully completed.

SQL> SET AUTOTRACE TRACE
SQL> SELECT description
2  FROM   spm_test_tab
3  WHERE  id = 99;

Execution Plan
----------------------------------------------------------
Plan hash value: 1107868462

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

--

| Id  | Operation         | Name         | Rows  | Bytes | Cost (%CPU)| Time
|

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

--

|   0 | SELECT STATEMENT  |              |     1 |    25 |    13   (0)| 00:00:01

|

|*  1 |  TABLE ACCESS FULL| SPM_TEST_TAB |     1 |    25 |    13   (0)| 00:00:01

|

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

--

Predicate Information (identified by operation id):
---------------------------------------------------

1 - filter("ID"=99)

Note
-----
- SQL plan baseline "SQL_PLAN_7qxjk7bch8h5tb65c37c8" used for this statement ==> Old base line is taken automatically

Statistics
----------------------------------------------------------
1  recursive calls
0  db block gets
47  consistent gets
0  physical reads
0  redo size
441  bytes sent via SQL*Net to client
416  bytes received via SQL*Net from client
2  SQL*Net roundtrips to/from client
0  sorts (memory)
0  sorts (disk)
1  rows processed

Let me try to create that index back and see what happens,


SQL> CREATE INDEX spm_test_tab_idx ON spm_test_tab(id);

Index created.

SQL> EXEC DBMS_STATS.gather_table_stats(USER, 'SPM_TEST_TAB', cascade=>TRUE);

PL/SQL procedure successfully completed.

SQL> SELECT description
2  FROM   spm_test_tab
3  WHERE  id = 99;

Execution Plan
----------------------------------------------------------
Plan hash value: 3121206333

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

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

| Id  | Operation                   | Name             | Rows  | Bytes | Cost (%

CPU)| Time     |

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

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

|   0 | SELECT STATEMENT            |                  |     1 |    25 |     2
(0)| 00:00:01 |

|   1 |  TABLE ACCESS BY INDEX ROWID| SPM_TEST_TAB     |     1 |    25 |     2
(0)| 00:00:01 |

|*  2 |   INDEX RANGE SCAN          | SPM_TEST_TAB_IDX |     1 |       |     1
(0)| 00:00:01 |

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

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

Predicate Information (identified by operation id):
---------------------------------------------------

2 - access("ID"=99)

Note
-----
- SQL plan baseline "SQL_PLAN_7qxjk7bch8h5ted3324c0" used for this statement  ==> Goes for the best plan

Statistics
----------------------------------------------------------
1  recursive calls
0  db block gets
4  consistent gets
0  physical reads
0  redo size
448  bytes sent via SQL*Net to client
416  bytes received via SQL*Net from client
2  SQL*Net roundtrips to/from client
0  sorts (memory)
0  sorts (disk)
1  rows processed

Note: I have not evolved 2nd time after putting back the index.

Need to check how the auto Evolving of baseline works.

convert this post to pdf.

 We did see our mview going slow. When we traced the session we found our job is waiting for a while in sumdelta$.

if automic_refresh=false due to direct load operation sumdelta$ don’t purge. There are some bug registered for this.

This is the workaround.


CREATE MATERIALIZED VIEW dummy_mview
TABLESPACE tbs_data
NOLOGGING
refresh complete
start with sysdate
next (sysdate+(1/1440))
WITH ROWID
AS select sysdate,col1 from mview mv10 WHERE 1=2 ;

In the select add “sysdate” so that refresh is assumed as complex and refresh every time.

exec DBMS_MVIEW.REFRESH('DUMMY_MVIEW','C');
select count(*) from sys.sumdelta$ where tableobj# in (select obj# from sys.obj$ where name=upper('DUMMY_MVIEW');

the count of this query should reduce to zero.

convert this post to pdf.

I generally create the profile via oem. The below link explains how to create via command line,

http://www.oracle-base.com/articles/10g/AutomaticSQLTuning10g.php

convert this post to pdf.

We have a DB which connects to other DB via LDAP connection. We had an issue where db link to another db server is slow.

I have limited expertise on LDAP. This is how i solved the issue.

select * from dual@db_link;

it’s slow first time. In the same session if we run it again, it’s fast.

Opened a SR.Got all the trace files but no update.

I enabled tnsping trace using below command

#TNSPING.TRACE_LEVEL = 16
#TNSPING.TRACE_DIRECTORY=/tmp

It didn’t have time info. So enabled the client and server level trace.

#trace_level_server=16
#trace_level_client=16
#trace_directory_server=/tmp
#trace_directory_client=/tmp
#trace_file_client=cli1
#trace_file_server=srv1
#trace_unique_client=true

in the trace

[04-AUG-2010 05:20:19:035] nnflilc:  Opening sync conn to server1.domain.com:123
[04-AUG-2010 05:21:33:947] nnflilc:   ldap_open failed ld:0

almost a minute it waits on server1, then it goes to server 2 and connects

[04-AUG-2010 05:21:33:954] nnflilc:  Opening sync conn to server2.domain.com:123
[04-AUG-2010 05:21:33:979] nnflalc: entry
[04-AUG-2010 05:21:34:009] nnflalc:     bind call returns 0

This gives the clue that server1 oid is having issue. So we changed the ldap.ora look up

DIRECTORY_SERVERS= (server1.domain.com:123:636,server2.domain.com:123:636)

to

DIRECTORY_SERVERS= (server2.domain.com:123:636,server1.domain.com:123:636)

command to start and stop oid.

oidmon start
oidctl server=oidldapd1 instance=1 configset=1 start
oidctl server=oidrepld1 instance=1 flags="-h server1 -p 389" start

stop

oidctl server=oidldapd1 instance=1 configset=1 stop;sleep 10
oidctl server=oidrepld1 instance=1 stop;sleep 10
oidmon stop
convert this post to pdf.

Create a sql based user defined metrics with below script. SQL query output will be 2 colums with metrics value as number.

select tablespace_name,
100-(round(((mb_free+mb_total-mb_curr)/mb_total)*100,0)) adj_pct_free
from
(
select d.tablespace_name,
nvl(sum(f.bytes)/1024/1024, 0) mb_free,
sum(d.bytes)/1024/1024 mb_curr,
case when sum(d.maxbytes)>0 then sum(d.maxbytes)/1024/1024
else  sum(d.bytes)/1024/1024 end mb_total
from dba_data_files d left outer join dba_free_space f
on (f.tablespace_name = d.tablespace_name)
group by d.tablespace_name
) used_free
where tablespace_name not like '%UNDO%';
convert this post to pdf.

In sqlt.zip there is a script called coe_xfr_sql_profile.sql which will help in generating the sql_profile from other_xml of v$sql_plan and output in executable format. This helps in moving the plan across the environment and also before creating profile helps you in editing the hints.

SQL> @/tmp/coe_xfr_sql_profile.sql

Parameter 1:
SQL_ID (required)

Enter value for 1: bcmu3by7zdb03

Parameter 2:
PLAN_HASH_VALUE (required)

Enter value for 2: 2415307779

Values passed:
~~~~~~~~~~~~~
SQL_ID         : "bcmu3by7zdb03"
PLAN_HASH_VALUE: "2415307779"

Disconnected from Oracle Database 10g Enterprise Edition Release 10.2.0.5.0 - 64bit Production
With the Partitioning, Data Mining and Real Application Testing options
convert this post to pdf.

New diagonistic tool is introduced in 11g. Using which we can gather all the information relevant to an issue and upload to oracle or investigate by yourself.

adrci is executable in $ORACLE_HOME/bin location

$ adrci

ADRCI: Release 11.1.0.7.0 - Production on Mon Jul 26 04:08:33 2010

Copyright (c) 1982, 2007, Oracle.  All rights reserved.

ADR base = "/opt/apps/oracle"
adrci>

adrci> show home
ADR Homes:
diag/rdbms/db1
diag/rdbms/db2
diag/rdbms/db3
diag/rdbms/db4
diag/tnslsnr/hostname/listener_bor3rep

adrci> set homepath diag/rdbms/db1

adrci> show problem ==> this will report the problem recently poped up in the db.

*************************************************************************
PROBLEM_ID           PROBLEM_KEY                                                 LAST_INCIDENT        LASTINC_TIME
-------------------- ----------------------------------------------------------- -------------------- ----------------------------------------
3                    ORA 7445 [_memset()+120]                                    32093                2010-07-25 18:01:06.962092 -04:00
4                    ORA 7445 [_doprnt()+44]                                     32077                2010-07-25 18:01:03.642031 -04:00
2                    ORA 4030                                                    32270                2010-07-25 18:01:00.837604 -04:00
1                    ORA 7445 [ioc_pin_shared_executable_object()+952]           28842                2010-06-05 22:39:34.757161 -04:00
4 rows fetched

If you want to diagonise 4030 error, then

adrci> ips pack problem 2 in /tmp
Generated package 3 in file /tmp/ORA4030_20100726041042_COM_1.zip, mode complete

Upload the trace file to oracle or use it for investigation. Has all the information relevant to 4030 error.

convert this post to pdf.

When the primary archive location fills, there is an option of writing to alternate archivelog location. These parameter needs to be set.

log_archive_dest_1='LOCATION=use_db_recovery_file_dest NOREOPEN  ALTERNATE=LOG_ARCHIVE_DEST_2'
log_archive_dest_2='LOCATION=/other_destination_for_archiving'
log_archive_dest_state_1='enable'
log_archive_dest_state_2='alternate'

You could use the following to revert back after failover:

alter system set  log_archive_dest_state_1 = enable;
alter system set log_archive_dest_state_2  = alternate;

But make note of below restriction when setting this.Metalink#369120.1

” The REOPEN attribute takes precedence over the ALTERNATE attribute. The alternate destination is
used only if one of the following is true:
- The NOREOPEN attribute is specified.
- A value of zero (0) is specified for the REOPEN attribute.
- A nonzero REOPEN attribute and a nonzero MAX_FAILURE count have been exceeded. ”

It’s preferable to set NOREOPEN to the default location and enable this option.

convert this post to pdf.
Code Description
10000 Control file debug event, name ‘control_file’
10001 Control file crash event1
10002 Control file crash event2
10003 Control file crash event3
10004 Control file crash event4
10005 Trace latch operations for debugging
10006 Testing – block recovery forced
10007 Log switch debug crash after new log select, thread %s
10008 Log switch debug crash after new log header write, thread %s
10009 Log switch debug crash after old log header write, thread %s
10010 Begin Transaction
10011 End Transaction
10012 Abort Transaction
10013 Instance Recovery
10014 Roll Back to Save Point
10015 Undo Segment Recovery
10016 Undo Segment extend
10017 Undo Segment Wrap
10018 Data Segment Create
10019 Data Segment Recovery
10020 Partial link restored to linked list (KSG)
10021 Latch cleanup for state objects (KSS)
10022 Trace ktsgsp
10023 Create Save Undo Segment
10024 Write to Save Undo
10025 Extend Save Undo Segment
10026 Apply Save Undo
10027 Latch cleanup for enqueue locks (KSQ)
10028 Latch cleanup for enqueue resources (KSQ)
10029 Session logon (KSU)
10030 Session logoff (KSU)
10031 Row source debug event (R*)
10032 Sort end (SOR*)
10035 Parse SQL statement (OPIPRS)
10036 Create remote row source (QKANET)
10037 Allocate remote row source (QKARWS)
10038 Dump row source tree (QBADRV)
10039 Type checking (OPITCA)
10040 Dirty cache list
10041 Dump undo records skipped
10042 Trap error during undo application
10044 Free list undo operations
10045 Free list update operations – ktsrsp, ktsunl
10046 Enable SQL statement timing
10047 Trace switching of sessions
10048 Undo segment shrink
10049 Protect library cache memory heaps
10050 Sniper trace
10051 Trace OPI calls
10052 Don’t clean up obj$
10053 CBO Enable optimizer trace
10054 Trace UNDO handling in MLS
10055 Trace UNDO handing
10056 Dump analyze stats (kdg)
10057 Suppress file names in error messages
10058 Use table scan cost in tab$.spare1
10060 CBO Enable predicate dump
10061 Disable SMON from cleaning temp segment
10062 Disable usage of OS Roles in osds
10063 Disable usage of DBA and OPER privileges in osds
10064 Thread enable debug crash level %s, thread %s
10065 Limit library cache dump information for state object dump
10066 Simulate failure to verify file
10067 Force redo log checksum errors – block number
10068 Force redo log checksum errors – file number
10069 Trusted Oracle test event
10070 Force datafile checksum errors – block number
10071 Force datafile checksum errors – file number
10072 Protect latch recovery memory
10073 Have PMON dump info before latch cleanup
10074 Default trace function mask for kst
10075 CBO Disable outer-join to regular join conversion
10076 CBO Enable cartesian product join costing
10077 CBO Disable view-merging optimization for outer-joins
10078 CBO Disable constant predicate elimination optimization
10080 Dump a block on a segment list which cannot be exchanged
10081 Segment High Water Mark has been advanced
10082 Free list head block is the same as the last block
10083 A brand new block has been requested from space management
10084 Free list becomes empty
10085 Free lists have been merged
10086 CBO Enable error if kko and qka disagree on oby sort
10087 Disable repair of media corrupt data blocks
10088 CBO Disable new NOT IN optimization
10089 CBO Disable index sorting
10090 Invoke other events before crash recovery
10091 CBO Disable constant predicate merging
10092 CBO Disable hash join
10093 CBO Enable force hash joins
10094 Before resizing a data file
10095 Dump debugger commands to trace file
10096 After the cross instance call when resizing a data file
10097 After generating redo when resizing a data file
10098 After the OS has increased the size of a data file
10099 After updating the file header with the new file size
10100 After the OS has decreased the size of a data file
10101 Atomic redo write recovery
10102 Switch off anti-joins
10103 CBO Disable hash join swapping
10104 Dump hash join statistics to trace file
10105 CBO Enable constant pred trans and MPs w WHERE-clause
10106 CBO Disable evaluating correlation pred last for NOT IN
10107 CBO Always use bitmap index
10108 CBO Don’t use bitmap index
10109 CBO Disable move of negated predicates
10110 CBO Try index rowid range scans
10111 Bitmap index creation switch
10112 Bitmap index creation switch
10113 Bitmap index creation switch
10114 Bitmap index creation switch
10115 CBO Bitmap optimization use maximal expression
10116 CBO Bitmap optimization switch
10117 CBO Disable new parallel cost model
10118 CBO Enable hash join costing
10119 QKA Disable GBY sort elimination
10120 CBO Disable index fast full scan
10121 CBO Don’t sort bitmap chains
10122 CBO disable count(col) = count(*) transformation
10123 QKA Disable Bitmap And-EQuals
10145 Test auditing network errors
10146 Enable Oracle TRACE collection
10200 Block cleanout
10201 Consistent read undo application
10202 Consistent read block header
10203 Consistent read buffer status
10204 Signal recursive extend
10205 Row cache debugging
10206 Transaction table consistent read
10207 Consistent read transactions’ status report
10208 Consistent read loop check
10209 Enable simulated error on control file
10210 Check data block integrity
10211 Check index block integrity
10212 Check cluster integrity
10213 Crash after control file write
10214 Simulate write errors on control file
10215 Simulate read errors on control file
10216 Dump control file header
10217 Debug sequence numbers
10218 Dump uba of applied undo
10219 Monitor multi-pass row locking
10220 Show updates to the transaction table
10221 Show changes done with undo
10222 Row cache
10223 Transaction layer – turn on verification codes
10226 Trace CR applications of undo for data operations
10227 Verify (multi-piece) row structure
10228 Trace application of redo by kcocbk
10230 Check redo generation by copying before applying
10231 Skip corrupted blocks on _table_scans_
10232 Dump corrupted blocks symbolically when kcbgotten
10233 Skip corrupted blocks on index operations
10234 Trigger event after calling kcrapc to do redo N times
10235 Check memory manager internal structures
10236 Library cache manager
10237 Simulate ^C (for testing purposes)
10238 Instantiation manager
10239 Multi-instance library cache manager
10240 Dump dba’s of blocks that we wait for
10241 Dump SQL generated for remote execution (OPIX)
10243 Simulated error for test %s of K2GTAB latch cleanup
10244 Make tranids in error msgs print as 0.0.0 (for testing)
10245 Simulate lock conflict error for testing PMON
10246 Print trace of PMON actions to trace file
10247 Turn on scgcmn tracing. (VMS ONLY)
10248 Turn on tracing for dispatchers
10249 Turn on tracing for multi-stated servers
10250 Trace all allocate and free calls to the topmost SGA heap
10251 Check consistency of transaction table and undo block
10252 Simulate write error to data file header
10253 Simulate write error to redo log
10254 Trace cross-instance calls
10256 Turn off multi-threaded server load balancing
10257 Trace multi-threaded server load balancing
10258 Force shared servers to be chosen round-robin
10259 Get error message text from remote using explicit call
10260 Trace calls to SMPRSET (VMS ONLY)
10261 Limit the size of the PGA heap
10262 Don’t check for memory leaks
10263 Don’t free empty PGA heap extents
10264 Collect statistics on context area usage (x$ksmcx)
10265 Keep random system generated output out of error messages
10266 Trace OSD stack usage
10267 Inhibit KSEDMP for testing
10268 Don’t do forward coalesce when deleting extents
10269 Don’t do coalesces of free space in SMON
10270 Debug shared cursors
10271 Distributed transaction after COLLECT
10272 Distributed transaction before PREPARE
10273 Distributed transaction after PREPARE
10274 Distributed transaction before COMMIT
10275 Distributed transaction after COMMIT
10276 Distributed transaction before FORGET
10277 Cursor sharing (or not) related event (used for testing)
10281 Maximum time to wait for process creation
10282 Inhibit signalling of other backgrounds when one dies
10286 Simulate control file open error
10287 Simulate archiver error
10288 Do not check block type in ktrget
10289 Do block dumps to trace file in hex rather than fromatted
10290 Kdnchk – checkvalid event – not for general purpose use.
10291 Die in dtsdrv to test controlfile undo”
10292 Dump uet entries on a 1561 from dtsdrv”
10293 Dump debugging information when doing block recovery”
10294 Enable PERSISTENT DLM operations on non-compliant systems”
10300 Disable undo compatibility check at database open
10301 Enable LCK timeout table consistency check”
10320 Enable data layer (kdtgrs) tracing of space management calls”
10352 Report direct path statistics
10353 Number of slots
10354 Turn on direct read path for parallel query
10355 Turn on direct read path for scans
10356 Turn on hint usage for direct read
10357 Turn on debug information for direct path
10374 Parallel query server interrupt (validate lock value)
10375 Turn on checks for statistics rollups
10376 Turn on table queue statistics
10377 Turn off load balancing
10379 Direct read for rowid range scans (unimplemented)
10380 Kxfp latch cleanup testing event
10381 Kxfp latch cleanup testing event
10382 Parallel query server interrupt (reset)
10383 Auto parallelization testing event
10384 Parallel dataflow scheduler tracing
10385 Parallel table scan range sampling method
10386 Parallel SQL hash and range statistics
10387 Parallel query server interrupt (normal)
10388 Parallel query server interrupt (failure)
10389 Parallel query server interrupt (cleanup)
10390 Trace parallel query slave execution
10391 Trace rowid range partitioning
10392 Parallel query debugging bits
10393 Print parallel query statistics
10394 Allow parallelization of small tables
10395 Adjust sample size for range table queues
10396 Circumvent range table queues for queries
10397 Suppress verbose parallel coordinator error reporting
10398 Enable timeouts in parallel query threads
10399 Use different internal maximum buffer size
10400 Turn on system state dumps for shutdown debugging
10500 Turn on traces for SMON
10510 Turn off SMON check to offline pending offline rollbacksegment
10511 Turn off SMON check to cleanup undo dictionary
10512 Turn off SMON check to shrink rollback segments
10600 Check cursor frame allocation
10602 Cause an access violation (for testing purposes)
10603 Cause an error to occur during truncate (for testing purposes)
10604 Trace parallel create index
10605 Enable parallel create index by default
10606 Trace parallel create index
10607 Trace index rowid partition scan
10608 Trace create bitmap index
10610 Trace create index pseudo optimizer
10666 Do not get database enqueue name
10667 Cause sppst to check for valid process ids
10690 Set shadow process core file dump type (Unix only)
10691 Set background process core file type (Unix only)
10700 Alter access violation exception handler
10701 Dump direct loader index keys
10702 Enable histogram data generation
10703 Simulate process death during enqueue get
10704 Print out information about what enqueues are being obtained
10706 Print out information about instance lock manipulation
10707 Simulate process death for instance registration
10708 Print out Tracing information for skxf multi instance comms
10709 Enable parallel instances in create index by default
10710 Trace bitmap index access
10711 Trace bitmap index merge
10712 Trace bitmap index or
10713 Trace bitmap index and
10714 Trace bitmap index minus
10715 Trace bitmap index conversion to rowids
10800 Disable Smart Disk scan
10801 Enable Smart Disk trace
10802 Reserved for Smart Disk
10803 Write timing statistics on OPS recovery scan
10804 Reserved for ksxb
10805 Reserved for row sort
10900 Extent manager fault insertion event #%s
10924 Import storage parse error ignore event
10925 Trace name context forever
10926 Trace name context forever
10927 trace name context forever
10928 trace name context forever
10999 do not get database enqueue name
convert this post to pdf.

We had  an outage, where pga eating up all the memory crashing the vcs. We temporarily solved the issue by moving to shared server and reducing the pga size.

Came across some of the suggestion to restrict pga,

1. Private_sga in MTS

2. 10261 event

10261, 00000, "Limit the size of the PGA heap"
// *Cause:    the limit is one kilobyte times the level of the event. If the
//            pga grows bigger than this signal an internal error.

to set a session to 100mb

  alter system set events '10261 trace name context forever, level 100000';

useful note is found in

http://dioncho.wordpress.com/2010/06/14/rapid-pga-size-increase/

for setting multiple events in spfile, you can use below command
ALTER SYSTEM SET event='10261 trace name context forever, level 15000000','600 trace name heapdump, level 0x20000001' COMMENT='pga issue' SCOPE=SPFILE;

for resetting use,

2:
ALTER SYSTEM RESET EVENT SCOPE=SPFILE SID='*' ;

Note: Have tried setting 10261 event in shared server db, but process didn't crash once reached the limit.
3. DBMS_SESSION.FREE_UNUSED_USER_MEMORY

convert this post to pdf.

We got an requirement to schedule a script after BD6+1. Means next day to BD6, which can be a holiday. But incase between BD1 to BD6 federal holiday falls, it needs to be moved to next day.

Create schedule for all the holidays,

begin
dbms_scheduler.create_schedule( schedule_name => 'NYD_FRI',
repeat_interval => 'FREQ=YEARLY;BYDATE=1231;BYDAY=FRI',
comments => 'Friday alternative for New Year''s Day');
dbms_scheduler.create_schedule( schedule_name => 'NYD_MON',
repeat_interval => 'FREQ=YEARLY;BYDATE=0102;BYDAY=MON',
comments => 'Monday alternative for New Year''s Day');
dbms_scheduler.create_schedule( schedule_name => 'NewYearsDay',
repeat_interval => 'FREQ=YEARLY;BYDATE=0101;BYDAY=MON,TUE,WED,THU,FRI;'
|| 'INCLUDE=NYD_FRI,NYD_MON', comments => 'New Year''s Day');
dbms_scheduler.create_schedule( schedule_name => 'MartinLutherKing',
repeat_interval => 'FREQ=MONTHLY;BYMONTH=JAN;BYDAY=3MON',
comments => 'Martin Luther King Day');
dbms_scheduler.create_schedule( schedule_name => 'PresidentsDay',
repeat_interval => 'FREQ=MONTHLY;BYMONTH=FEB;BYDAY=3MON',
comments => 'President''s Day');
dbms_scheduler.create_schedule( schedule_name => 'MemorialDay',
repeat_interval => 'FREQ=MONTHLY;BYMONTH=MAY;BYDAY=-1MON',
comments => 'Memorial Day');
dbms_scheduler.create_schedule( schedule_name => 'ID_FRI',
repeat_interval => 'FREQ=YEARLY;BYDATE=0703;BYDAY=FRI',
comments => 'Friday alternative for Independence Day');
dbms_scheduler.create_schedule( schedule_name => 'ID_MON',
repeat_interval => 'FREQ=YEARLY;BYDATE=0705;BYDAY=MON',
comments => 'Monday alternative for Independence Day');
dbms_scheduler.create_schedule( schedule_name => 'IndependenceDay',
repeat_interval => 'FREQ=YEARLY;BYDATE=0704;BYDAY=MON,TUE,WED,THU,FRI;'
|| 'INCLUDE=ID_FRI,ID_MON', comments => 'Independence Day');
dbms_scheduler.create_schedule( schedule_name => 'LaborDay',
repeat_interval => 'FREQ=MONTHLY;BYMONTH=SEP;BYDAY=1MON',
comments => 'Labor Day');
dbms_scheduler.create_schedule( schedule_name => 'ColumbusDay',
repeat_interval => 'FREQ=MONTHLY;BYMONTH=OCT;BYDAY=2MON',
comments => 'Columbus Day');
dbms_scheduler.create_schedule( schedule_name => 'VD_FRI',
repeat_interval => 'FREQ=YEARLY;BYDATE=1110;BYDAY=FRI',
comments => 'Friday alternative for Veterans Day');
dbms_scheduler.create_schedule( schedule_name => 'VD_MON',
repeat_interval => 'FREQ=YEARLY;BYDATE=1112;BYDAY=MON',
comments => 'Monday alternative for Veterans Day');
dbms_scheduler.create_schedule( schedule_name => 'VeteransDay',
repeat_interval => 'FREQ=YEARLY;BYDATE=1111;BYDAY=MON,TUE,WED,THU,FRI;'
|| 'INCLUDE=VD_FRI,VD_MON', comments => 'Veterans Day');
dbms_scheduler.create_schedule( schedule_name => 'Thanksgiving',
repeat_interval => 'FREQ=MONTHLY;BYMONTH=NOV;BYDAY=4THU',
comments => 'Thanksgiving');
dbms_scheduler.create_schedule( schedule_name => 'XMS_FRI',
repeat_interval => 'FREQ=YEARLY;BYDATE=1224;BYDAY=FRI',
comments => 'Friday alternative for Christmas');
dbms_scheduler.create_schedule( schedule_name => 'XMS_MON',
repeat_interval => 'FREQ=YEARLY;BYDATE=1226;BYDAY=MON',
comments => 'Monday alternative for Christmas');
dbms_scheduler.create_schedule( schedule_name => 'Christmas',
repeat_interval => 'FREQ=YEARLY;BYDATE=1225;BYDAY=MON,TUE,WED,THU,FRI;'
|| 'INCLUDE=XMS_FRI,XMS_MON', comments => 'Christmas');
end;
/

– create a schedule which clubs all the schedule created above.

begin
dbms_scheduler.create_schedule( schedule_name => 'FederalHolidays',
repeat_interval => 'NewYearsDay,MartinLutherKing,PresidentsDay,' ||
'MemorialDay,IndependenceDay,LaborDay,ColumbusDay,VeteransDay,' ||
'Thanksgiving,Christmas', comments => 'Federal Holidays');
end;
/

– Job which needs to be scheduled

create or replace procedure stats_run_after_BD6 as
begin

---- some job;
end;
/

— Create a job, note the “EXCLUDE” and “BYSETPOS” option

BEGIN
dbms_scheduler.create_job(
job_name => 'Stats_Run_After_BD6+1'
,job_type => 'PLSQL_BLOCK'
,job_action => 'begin stats_run_after_BD6; end; '
,repeat_interval => 'FREQ=MONTHLY; BYDAY=MON,TUE,WED,THU,FRI; byhour=14;byminute=30;bysecond=0; EXCLUDE=FederalHolidays; BYSETPOS=7'
,enabled => TRUE
,comments => 'Run Stats Gather next day of BD6');
END;
/

What are all the dates this job is going to execute. We can use the below procedure.


create or replace procedure print_dates
is
nr_of_dates  pls_integer :=30;
start_date timestamp with time zone := sysdate;
date_after timestamp with time zone := start_date - interval '1' second;
next_execution_date timestamp with time zone;
correct_execution_date timestamp with time zone;

begin
for i in 1 .. nr_of_dates
loop
dbms_scheduler.evaluate_calendar_string
('FREQ=MONTHLY; BYDAY=MON,TUE,WED,THU,FRI; byhour=14;byminute=30;bysecond=0; EXCLUDE=FederalHolidays; BYSETPOS=6', start_date, date_after, next_execution_date);

correct_execution_date := next_execution_date + interval '1' day;
DBMS_OUTPUT.PUT_LINE(correct_execution_date);

date_after := next_execution_date;
end loop;
end;
/

sometime the BD6+ 1 date will be weekend. If you want to execute in the weekend you can add “interval ’1′ day”,

correct_execution_date := next_execution_date + interval ’1′ day;

else remove that.

convert this post to pdf.

When one of the db got upgraded from 10202 to 10205, we found out one of the query is very slow. Didn’t taken the export of stats before upgrade. This is one way we forced a profile to this query.

declare
pln_sql_id varchar2(20) :='fathgmks3vb1g';
pln_plan_hash_value number := 3396554601;
orig_sql_id varchar2(20) := 'fathgmks3vb1g';
new_prof_name varchar2(20) := 'SQL_PROFILE_1';
ar_profile_hints sys.sqlprof_attr;
cl_sql_text clob;
begin

select extractvalue(value(d), '/hint') as outline_hints
bulk collect into ar_profile_hints
from xmltable('/*/outline_data/hint'
passing (select xmltype(other_xml) as xmlval from dba_hist_sql_plan
where sql_id = pln_sql_id and plan_hash_value = pln_plan_hash_value
and other_xml is not null)) d;

select sql_text into cl_sql_text
from dba_hist_sqltext where sql_id = orig_sql_id;

dbms_sqltune.import_sql_profile(
sql_text => cl_sql_text,
profile => ar_profile_hints,
name => new_prof_name,
force_match => true);

end;
/

The below script can be used to see what’s the access path for a hash_value. This can be seen when you create outln and query ol_hint$

select
substr(extractvalue(value(d), '/hint'), 1, 100) as outline_hints
from
xmltable('/*/outline_data/hint'
passing (
select
xmltype(other_xml) as xmlval
from
v$sql_plan
where
hash_value = 2378699969
and child_number = 0
and other_xml is not null
)
) d;

You need to drop any sql_profile created before forcing a plan.

exec DBMS_SQLTUNE.DROP_SQL_PROFILE(name => 'SYS_SQLPROF_014a4a1e346a8004', ignore => TRUE);
convert this post to pdf.

Steps for export and importing the db stats. This helps when you change the stats gathering approach.

exec dbms_stats.create_stat_table(ownname => ‘SYS’, stattab => ‘db_stat’, tblspace => ‘SYSTEM’)

exec dbms_stats.export_database_stats(stattab => ‘db_stat’,statown => ‘SYS’)

exec dbms_stats.import_database_stats(stattab => ‘db_stat’,statown => ‘SYS’)

convert this post to pdf.

Recently while applying incremental backup in DG running under ASM, got into issue due the rman backup taken with %U.

May be should have used %N%f.dbf this helps in giving both tablespace name and absolute file_id. This information is documented in

http://download.oracle.com/docs/cd/B19306_01/backup.102/b14194/rcmsynta033.htm#sthref531

convert this post to pdf.

Recently upgraded the OMS from 10204 to 10205.
As part of we want to upgrade the agent to 10205 from lower version.
We have around 150 targets. So upgrading each is very difficult. Also fresh install requires to install base version apply 10205 patch, psu patch and other fixes. Doing in each server is difficult.

Instead, we installed 10205 with up to date patch in a sand box. Took tar and moved to servers where we need to patch.

After untaring,
./runInstaller -clone -forceClone ORACLE_HOME=$ORACLE_HOME ORACLE_HOME_NAME=agent10205 -noconfig -silent
this will do the proper clone of the agent applying all the bugs
incase if you get complient like home already exist you can try,

./runInstaller -detachHome ORACLE_HOME=$ORACLE_HOME ORACLE_HOME_NAME=agent10204 -noconfig -silent

once done

go to $AGENT_HOME/sysman/config
vi emd.properties
check and apply correct port to emd_url,repository_url,emdWallet
once done
secure the agent and start the agent

after which run
$ORACLE_HOME/bin/agentca -f

if its RAC run the below command. For Rac DB agent needs to be installed in both the server. Make sure the directory structures are same.
$ORACLE_HOME/bin/agentca -f -n “cluster1,cluster2″

Due to nic setting we might have issue in RAC. That case

“ListenOnAllNICs=false” in emd.properties if it’s cluster environment and getting http error port already used errorcheck note 443524.1

convert this post to pdf.

After a while did the DG creation using rman. Referred note#789370.1

take init.ora of both primary and standby backup

run
{
allocate channel c1 type disk;
allocate channel c2 type disk;
backup database format ‘/oradata/orabackup01/Primary/rman/%U’;
backup archivelog all format ‘/oradata/orabackup01/Primary/rman/%U’;
backup current controlfile for standby format ‘/oradata/orabackup01/Primary/rman/%U’;
}

alter system switch logfile;

scp the files to standby server. Use similar location.

on secondary

$ rman target sys/syspwd@Primary_dg auxiliary /

Recovery Manager: Release 10.2.0.2.0 – Production on Tue May 18 04:12:27 2010

Copyright (c) 1982, 2005, Oracle. All rights reserved.

connected to target database: Primary (DBID=863765789)
connected to auxiliary database: standby (not mounted)

RMAN> duplicate target database for standby dorecover;

Starting Duplicate Db at 18-MAY-2010 04:12:51
using target database control file instead of recovery catalog
allocated channel: ORA_AUX_DISK_1
channel ORA_AUX_DISK_1: sid=156 devtype=DISK
allocated channel: ORA_AUX_DISK_2
channel ORA_AUX_DISK_2: sid=155 devtype=DISK
allocated channel: ORA_AUX_SBT_TAPE_1
channel ORA_AUX_SBT_TAPE_1: sid=154 devtype=SBT_TAPE
channel ORA_AUX_SBT_TAPE_1: Veritas NetBackup for Oracle – Release 6.5 (2008052301)
allocated channel: ORA_AUX_SBT_TAPE_2
channel ORA_AUX_SBT_TAPE_2: sid=153 devtype=SBT_TAPE
channel ORA_AUX_SBT_TAPE_2: Veritas NetBackup for Oracle – Release 6.5 (2008052301)

contents of Memory Script:
{
set until scn 8978424429104;
restore clone standby controlfile;
sql clone ‘alter database mount standby database’;
}
executing Memory Script

executing command: SET until clause

Starting restore at 18-MAY-2010 04:25:19
using channel ORA_AUX_DISK_1
using channel ORA_AUX_DISK_2
using channel ORA_AUX_SBT_TAPE_1
using channel ORA_AUX_SBT_TAPE_2

channel ORA_AUX_DISK_1: starting datafile backupset restore
channel ORA_AUX_DISK_1: restoring control file
channel ORA_AUX_DISK_1: reading from backup piece /oradata/orabackup01/standby/rman/jolduq5h_1_1
channel ORA_AUX_DISK_1: restored backup piece 1
piece handle=/oradata/orabackup01/standby/rman/jolduq5h_1_1 tag=TAG20100518T011321
channel ORA_AUX_DISK_1: restore complete, elapsed time: 00:00:18
output filename=+DISK_GROUP1/standby/controlfile/control01_standby.ctl
Finished restore at 18-MAY-2010 04:25:40

sql statement: alter database mount standby database
released channel: ORA_AUX_DISK_1
released channel: ORA_AUX_DISK_2
released channel: ORA_AUX_SBT_TAPE_1
released channel: ORA_AUX_SBT_TAPE_2

contents of Memory Script:
{
set until scn 8978424429104;
set newname for clone tempfile 1 to new;
switch clone tempfile all;
set newname for clone datafile 1 to new;
set newname for clone datafile 2 to new;
set newname for clone datafile 3 to new;
set newname for clone datafile 4 to new;
set newname for clone datafile 5 to new;
set newname for clone datafile 6 to new;
set newname for clone datafile 7 to new;
set newname for clone datafile 8 to new;
set newname for clone datafile 9 to new;
set newname for clone datafile 10 to new;
set newname for clone datafile 11 to new;
set newname for clone datafile 12 to new;
set newname for clone datafile 13 to new;
restore
check readonly
clone database
;
}
executing Memory Script

executing command: SET until clause

executing command: SET NEWNAME

renamed temporary file 1 to +DISK_GROUP1 in control file

executing command: SET NEWNAME

executing command: SET NEWNAME

executing command: SET NEWNAME

executing command: SET NEWNAME

executing command: SET NEWNAME

executing command: SET NEWNAME

executing command: SET NEWNAME

executing command: SET NEWNAME

executing command: SET NEWNAME

executing command: SET NEWNAME

executing command: SET NEWNAME

executing command: SET NEWNAME

executing command: SET NEWNAME

Starting restore at 18-MAY-2010 04:26:02
allocated channel: ORA_AUX_DISK_1
channel ORA_AUX_DISK_1: sid=153 devtype=DISK
allocated channel: ORA_AUX_DISK_2
channel ORA_AUX_DISK_2: sid=154 devtype=DISK
allocated channel: ORA_AUX_SBT_TAPE_1
channel ORA_AUX_SBT_TAPE_1: sid=155 devtype=SBT_TAPE
channel ORA_AUX_SBT_TAPE_1: Veritas NetBackup for Oracle – Release 6.5 (2008052301)
allocated channel: ORA_AUX_SBT_TAPE_2
channel ORA_AUX_SBT_TAPE_2: sid=156 devtype=SBT_TAPE
channel ORA_AUX_SBT_TAPE_2: Veritas NetBackup for Oracle – Release 6.5 (2008052301)

channel ORA_AUX_DISK_1: starting datafile backupset restore
channel ORA_AUX_DISK_1: specifying datafile(s) to restore from backup set
restoring datafile 00001 to +DISK_GROUP1
restoring datafile 00005 to +DISK_GROUP1
restoring datafile 00007 to +DISK_GROUP1
restoring datafile 00008 to +DISK_GROUP1
restoring datafile 00009 to +DISK_GROUP1
restoring datafile 00010 to +DISK_GROUP1
restoring datafile 00013 to +DISK_GROUP1
channel ORA_AUX_DISK_1: reading from backup piece /oradata/orabackup01/standby/rman/jkldupnn_1_1
channel ORA_AUX_DISK_2: starting datafile backupset restore
channel ORA_AUX_DISK_2: specifying datafile(s) to restore from backup set
restoring datafile 00002 to +DISK_GROUP1
restoring datafile 00003 to +DISK_GROUP1
restoring datafile 00004 to +DISK_GROUP1
restoring datafile 00006 to +DISK_GROUP1
restoring datafile 00011 to +DISK_GROUP1
restoring datafile 00012 to +DISK_GROUP1
channel ORA_AUX_DISK_2: reading from backup piece /oradata/orabackup01/standby/rman/jjldupnm_1_1
channel ORA_AUX_DISK_2: restored backup piece 1
piece handle=/oradata/orabackup01/standby/rman/jjldupnm_1_1 tag=TAG20100518T010558
channel ORA_AUX_DISK_2: restore complete, elapsed time: 00:06:15
channel ORA_AUX_DISK_1: restored backup piece 1
piece handle=/oradata/orabackup01/standby/rman/jkldupnn_1_1 tag=TAG20100518T010558
channel ORA_AUX_DISK_1: restore complete, elapsed time: 00:06:31
Finished restore at 18-MAY-2010 04:32:41

contents of Memory Script:
{
switch clone datafile all;
}
executing Memory Script

datafile 1 switched to datafile copy
input datafile copy recid=41 stamp=719296362 filename=+DISK_GROUP1/standby/datafile/system.413.719295981
datafile 2 switched to datafile copy
input datafile copy recid=42 stamp=719296362 filename=+DISK_GROUP1/standby/datafile/undo1.407.719295981
datafile 3 switched to datafile copy
input datafile copy recid=43 stamp=719296362 filename=+DISK_GROUP1/standby/datafile/sysaux.345.719295971
datafile 4 switched to datafile copy
input datafile copy recid=44 stamp=719296362 filename=+DISK_GROUP1/standby/datafile/users.416.719295983
datafile 5 switched to datafile copy
input datafile copy recid=45 stamp=719296362 filename=+DISK_GROUP1/standby/datafile/ts_aud_data_purge.405.719295981
datafile 6 switched to datafile copy
input datafile copy recid=46 stamp=719296362 filename=+DISK_GROUP1/standby/datafile/tspan_data.351.719295975
datafile 7 switched to datafile copy
input datafile copy recid=47 stamp=719296362 filename=+DISK_GROUP1/standby/datafile/tspan_index.410.719295979
datafile 8 switched to datafile copy
input datafile copy recid=48 stamp=719296362 filename=+DISK_GROUP1/standby/datafile/fuego_data.474.719295975
datafile 9 switched to datafile copy
input datafile copy recid=49 stamp=719296362 filename=+DISK_GROUP1/standby/datafile/fuego_index.368.719295977
datafile 10 switched to datafile copy
input datafile copy recid=50 stamp=719296362 filename=+DISK_GROUP1/standby/datafile/adw_data.342.719295971
datafile 11 switched to datafile copy
input datafile copy recid=51 stamp=719296362 filename=+DISK_GROUP1/standby/datafile/adw_index.409.719295981
datafile 12 switched to datafile copy
input datafile copy recid=52 stamp=719296363 filename=+DISK_GROUP1/standby/datafile/reserve.411.719295979
datafile 13 switched to datafile copy
input datafile copy recid=53 stamp=719296363 filename=+DISK_GROUP1/standby/datafile/streams_tbs.406.719295983

contents of Memory Script:
{
set until scn 8978424429104;
recover
standby
clone database
delete archivelog
;
}
executing Memory Script

executing command: SET until clause

Starting recover at 18-MAY-2010 04:32:45
using channel ORA_AUX_DISK_1
using channel ORA_AUX_DISK_2
using channel ORA_AUX_SBT_TAPE_1
using channel ORA_AUX_SBT_TAPE_2

starting media recovery

Oracle Error:
ORA-01547: warning: RECOVER succeeded but OPEN RESETLOGS would get error below
ORA-01152: file 1 was not restored from a sufficiently old backup
ORA-01110: data file 1: ‘+DISK_GROUP1/standby/datafile/system.413.719295981′

RMAN-00571: ===========================================================
RMAN-00569: =============== ERROR MESSAGE STACK FOLLOWS ===============
RMAN-00571: ===========================================================
RMAN-03002: failure of Duplicate Db command at 05/18/2010 04:33:00
RMAN-03015: error occurred in stored script Memory Script
RMAN-06053: unable to perform media recovery because of missing log
RMAN-06025: no backup of log thread 1 seq 203315 lowscn 8978424428500 found to restore
RMAN-06025: no backup of log thread 1 seq 203314 lowscn 8978424427332 found to restore
RMAN-06025: no backup of log thread 1 seq 203313 lowscn 8978424419381 found to restore
RMAN-06025: no backup of log thread 1 seq 203312 lowscn 8978255748027 found to restore

exit from rman. Ignore the above error time being.

go to primary

alter system set log_archive_dest_state_2 = enable ;

go to standby

alter database recover managed standby database disconnect from session;

This should catch up the standby with the missing arch reported above.

execute the below command in standby, you will get the status.

select sequence#,applied from v$archived_log order by sequence#;

convert this post to pdf.

My OMS is in 10204. It’s very slow, one vital reason is we are running low on OS resource. We are planning to move to much higher configuration.

These are some of the changes which helped is putting the below entry in opmn.xml at $OMS_HOME/opmn/conf










===========













convert this post to pdf.

My OMS installed in very poor configuration. Can’t take any load. I applied a template by mistake for 750 target in a shot. My OMS crashed. It didnt’ came up. I tried bouncing, no luck. But i see some activity in my trace file.
Looks like it’s applying or doing something.
Ok, how long it is going to take before my OMS back up. Since my OMS crashed i can’t see how many pending jobs. Here i used below query to figure out how much pending and how much completed.

SELECT target_type “Target Type”,
target_name “Destination Target”,
template_name “Last Applied Template”,
copy_type “Apply Option”,
execution_status “Status”
FROM
(
SELECT mts.template_name template_name,
mt.target_name target_name,
mt.target_type target_type,
mtc.copy_type copy_type,
DECODE(muodt.execution_status,
1, ‘PENDING’,
5, ‘COMPLETE’,
2, ‘EXECUTING’,
3, ‘ABORTED’,
4, ‘FAILED’) execution_status,
mtc.created_date,
RANK () OVER (PARTITION BY mt.target_name,mt.target_type ORDER BY mtc.created_date
DESC ) rk
FROM mgmt_update_operations_details muodt,
mgmt_update_operations_data muoda,
mgmt_update_template_data_map mutdm,
mgmt_template_copies mtc,
mgmt_targets mt,
mgmt_templates mts
WHERE muodt.operation_guid = muoda.operation_guid
AND muoda.data_set_guid = mutdm.data_set_guid
AND muoda.data_set_type = 4
AND mutdm.template_copy_guid = mtc.template_copy_guid
AND mt.target_guid = muodt.destination_target_guid
AND mtc.template_guid = mts.template_guid
)
WHERE rk <=1
and template_name ='Prod - Database - Template' ==> my template name
ORDER BY 1,3,2 ;

convert this post to pdf.

I am trying to remove agent from OEM. It’s running for quite a while and no result seen. If your case is like this, you can use below command to remove.

exec mgmt_admin.cleanup_agent(‘hostname:1830′);

if you want to delete any target from command line use

exec mgmt_admin.delete_target(‘target_name’,'oracle_database’);

followed by

commit;

convert this post to pdf.

This i have seen in one of the forums. Which is something we are looking for sometime.

Not tried yet, but planning to implement soon once we migrate to much robust oem server.

export ORACLE_HOME=${AGENT_HOME}

Stop the agent:
${ORACLE_HOME}/bin/emctl stop agent

Save the file database.xmlp :
cp -p $ORACLE_HOME/sysman/admin/default_collection/database.xmlp $ORACLE_HOME/sysman/admin/default_collection/database.xmlp.orig

search for pattern <CollectionItem NAME=”tbspAllocation”>  or whatever and change the frequency to your requirement

<CollectionItem NAME=”tbspAllocation”>
<ValidIf>
<CategoryProp NAME=”VersionCategory” CHOICES=”pre8;8i;8iR2;9i;9iR2;10gR1;10gR2;10gR203;11gR1;11gR2″/>
</ValidIf>

<Schedule>
<IntervalSchedule INTERVAL=”7″ TIME_UNIT=”Day”/>
</Schedule>

<MetricColl NAME=”tbspAllocation” />
</CollectionItem>

Change the value of INTERVAL from 7 to 1 then save & quit.

Restart the agent :
$ORACLE_HOME}/bin/emctl start agent

The update will be shown in the Grid Control within 24H.

convert this post to pdf.

Our managment decided to give OEM access to development DBA. We were worried that development DBA might share the password to developer. There are 100s of developer in our environment. If everyone login to the OEM, this would create night mare. Since OEM is administration tool, we would prefer to be used by DBA.
How to protect development DBA sharing their pwd with developer. We tried something similar to sessions_per_user profile. Which didn’t work, as it is only for oracle user and not for OEM user.
Other approach is enable auditing on OEM user and if the login is coming from more than one ip, alert the dba.
By default, ip addr and hostname will not be registered in mgmt$audit_log. To enable it follow the metalink note#457382.1

exec mgmt_audit_admin.set_audit(0, null, 0);
shutdown the oms,opmn,agent
update
$OMS_HOME/Apache/Apache/conf/httpd.conf

make these 2 entries
UseWebCacheIp On
HostnameLookups On

restart the OMS.
After which each login in insert into mgmt_user_sessions table along with hostname and ipaddr. If a userid is used in more than one ipaddr, we can easily track.
select EM_USER,
             EM_USER_TYPE,
             EM_USER_HOST_NAME,
             OMS_HOST_NAME ,
             IP_ADDRESS
   from  MGMT_USER_SESSION
order by LOGIN_TIME desc;

But problem is this table might keep growing.
To do the purge,
Stop oms
exec mgmt_audit_admin.set_audit(0,null,2)
exec mgmt_audit_admin.audit_purge(’11-Jan-10′); — Give sysdate+1 to remove all the data

enable auditing
exec mgmt_audit_admin.set_audit(0, null, 0);
start OMS.

convert this post to pdf.

we have a requirement to alert for backup failures. Connecting to each rman repository or db to get this information is difficult. We have OEM, and this how we have implemented. We created UDM and applied to necessary targets.

Monitor DB fullbackup.

select count(*) from (select rownum no,x.status,x.end_time from (select status,end_time from v$rman_status where end_time is not null and object_type=’DB FULL‘ and end_time > sysdate-1 order by end_time desc) x) y where y.no=1 and y.status = ‘COMPLETED’

Monitor DB incr,

select count(*) from (select rownum no,x.status,x.end_time from (select status,end_time from v$rman_status where end_time is not null and object_type=’DB INCR‘ and end_time > sysdate-1 order by end_time desc) x) y where y.no=1 and y.status = ‘COMPLETED’

Archivelog backup.

select count(*) from (select rownum no,x.status,x.end_time from (select status,end_time from v$rman_status where end_time is not null and object_type=’ARCHIVELOG’ and end_time > sysdate-1 order by end_time desc) x) y where y.no=1 and y.status =’COMPLETED’

Other similar query which i came across is

select (sysdate-min(t))*24 from
(
  select max(b.CHECKPOINT_TIME) t
  from v$backup_datafile b, v$tablespace ts, v$datafile f
  where INCLUDED_IN_DATABASE_BACKUP='YES'
  and f.file#=b.file#
  and f.ts#=ts.ts#
  group by f.file#
)

for arch log monitoring,

select (sysdate-max(NEXT_TIME))*24 from v$BACKUP_REDOLOG

convert this post to pdf.

if you have used OEM, then you should have used sql tuning advisor. Sometime if the plan is very large you will not be able to implement the profile. You will get message like,
“There was a problem creating the SQL Profile setString can only process strings of less than 32766 chararacters”

Instead of implementing via OEM, use the below script to force the profile. But remember the tuning name what you have generated.

begin
dbms_output.put_line(
dbms_sqltune.accept_sql_profile(
task_name => 'sql_tuning_xyz',
name => 'manual_forcing',
replace => true,
force_match => true
)
);
end;
/
convert this post to pdf.

Read couple of interesting topic on proxy login in oracle.

http://www.idevelopment.info/data/Oracle/DBA_tips/Database_Administration/DBA_19.shtml

http://jonathanlewis.wordpress.com/2006/12/18/proxy-users/

convert this post to pdf.

We have an requirement, where we need to purge portion of data from huge table. After much discussion, we have decided go to like
1. create temp table
2. populate only relevant data from main table to temp table
3. drop main table.
4. rename temp table to main table and recreate missing indexes.

there are various approach to do this. But instead we have gone with something like split the big table in to logical split using rowid and with each logical split populate the temp table parallel.

create table scuser.tab1_bk as select * from scuser.tab1 where 1=2;

alter table scuser.tab1_bk nologging;

truncate table scuser.tab1_bk;

Drop table split_rowid purge;

CREATE TABLE split_rowid as select distinct grp,
first_value(relative_fno) over
(partition by grp order by relative_fno, block_id
rows between unbounded preceding and unbounded following) lo_fno,
first_value(block_id ) over
(partition by grp order by relative_fno, block_id
rows between unbounded preceding and unbounded following) lo_block,
last_value(relative_fno) over
(partition by grp order by relative_fno, block_id
rows between unbounded preceding and unbounded following) hi_fno,
last_value(block_id+blocks-1) over
(partition by grp order by relative_fno, block_id
rows between unbounded preceding and unbounded following) hi_block,
sum(blocks) over (partition by grp) sum_blocks
from (
select relative_fno,
block_id,
blocks,
trunc( (sum(blocks) over (order by relative_fno, block_id)-0.01) /
(sum(blocks) over ()/&chunk) ) grp
from dba_extents
where segment_name = ('TAB1')
and owner = '&owner' order by block_id
)
/

Create or replace procedure purge_clock(p_no number,lo_rowid rowid,hi_rowid rowid) as
type array is table of scuser.tab1_bk%rowtype;
l_data array;
cursor c is select /+* first_rows */ * from tab1 a where (exists
(select 1 from probsummarym1
where probsummarym1.numberprgn = a.key_char
and a.type = 'problem')
or a.datetime_last_upd > (sysdate-3)
or type <> 'problem')
and substr(name,0,7) <> 'JPASRPT' and rowid between lo_rowid and hi_rowid;;

lv_cnt number:=0;
lv_cnt1 number:=0;
BEGIN
open c;
loop
fetch c bulk collect into l_data LIMIT 10000;
lv_cnt:=lv_cnt+1;
lv_cnt1 := lv_cnt*10000;
dbms_application_info.set_client_info(p_no||' of Clock:'||lv_cnt1);
forall i in 1 .. l_data.count
Insert into scuser.tab1_bk values l_data(i);
COMMIT;
exit when c%notfound;
END LOOP;
CLOSE c;
commit;
END;
/

alter system set job_queue_processes=20;

set serveroutput on;
Declare
cursor c1 is
select rownum no,
dbms_rowid.rowid_create(1,
(select data_object_id from dba_objects where object_name='tab1' and object_type='TABLE'),lo_fno,lo_block,0) lo_rowid,
dbms_rowid.rowid_create(1,
(select data_object_id from dba_objects where object_name='tab1' and object_type='TABLE'),hi_fno,hi_block,32767) hi_rowid
from split_rowid order by no;

lv_job number;
begin
for i in c1 loop
dbms_job.submit(lv_job,'purge_clock('||i.no||','||chr(39)||i.lo_rowid||chr(39)||','||chr(39)||i.hi_rowid||chr(39)||');');
dbms_output.put_line('Job#'||lv_job);
commit;
end loop;
commit;
end;
/
convert this post to pdf.

If you have hundreds of DB it will be usefull to have all the tns entry in your desktop. So for small task you don’t have to get into server. This will be saving lot of times. There are various way to create tns entry. The approach what i have used is from OEM.
If your shop is monitored by OEM, then you can use below script to generate tns entry and put it in your tns_admin location.
This procedure needs be compiled in sysman schema.

create or replace procedure rpt_tns_generation as
cursor c1 is
select distinct a.target_guid from mgmt_target_properties a,mgmt_targets b
where a.target_guid = b.target_guid
and b.target_type=’oracle_database’;

lv_sid varchar2(30);
lv_host varchar2(100);
lv_port number;
lv_service_name varchar2(100);
begin
for i in c1 loop
select property_value
into lv_sid
from mgmt_target_properties
where property_name=’SID’
and target_guid=i.target_guid;

select property_value
into lv_host
from mgmt_target_properties
where property_name=’MachineName’
and target_guid=i.target_guid;

select property_value
into lv_port
from mgmt_target_properties
where property_name=’Port’
and target_guid=i.target_guid;

dbms_output.put_line(lv_sid||’='||chr(10)||’(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=’||lv_host||’)(PORT=’||lv_port||’)))(CONNECT_DATA=(sid=’||lv_sid||’)))’);

end loop;

exception
when others then
dbms_output.put_line(‘error for ‘||sqlerrm);
end;
/

convert this post to pdf.

If your shop using OEM as monitoring tool, then you should be aware of this. If not try it out. Create a group and put all the DB under that group. If you get into the group you will see the launch dashboard. That will invoke the console. This will be one place where you get all the information. Critical,warning, target down, target unknow information. There is a option to customize also.
In our shop we have given a extra TFT monitor to each DBA and he moves this console to this extra monitor. After implementing this there was tremendous progress in our monitoring ability. We are on top of all the alerts now. If budget permits you can go for a wall mounted LCD

convert this post to pdf.

This tool needs to be installed in OMS server preferreably in OMS_HOME. Create a directory called “emdiag” to store these binaries.
You can follow the note 421053.1 and 421499.1 for this.
Once the installation is done you can get the debug details for all the target monitored using

./repvfy -usr SYSMAN -pwd  -tns emrep test -level 9 -detail

If you want to fix some of the debug issues you need to get the number from detail*.log or verify*.log in $EMDIAG_HOME/log location
These files will ahve info like,

001. Agents without a monitored host target: 1
101. Active Agents with clock-skew problems: 8
105. Agents not uploading any data: 6
106. Agents with improper ping status (5440008): 4
110. Agents not marked as potentially down (6314624): 4

so to fix 001 you need to run

$ ./repvfy -tns emrep verify blackouts -test 1 -fix

Please enter the SYSMAN password: 

-- --------------------------------------------------------------------- --
-- EMDIAG: 2009.0711     Repository: 10.2.0.4.0     06-Aug-2009 09:04:50 --
---------------------------------------------------------------------------
-- -- -- - Running in FIX mode: Data updated for all fixed tests - -- -- --
-- --------------------------------------------------------------------- --
verifyBLACKOUTS

These are some of the other module which can be fixed.

$ repvfy verify availability -test 100 -fix

$ repvfy verify targets -test 709 -fix
$ repvfy verify targets -test 705 -fix
$ repvfy verify targets -test 703 -fix
$ repvfy verify targets -test 702 -fix
$ repvfy verify targets -test 701 -fix
$ repvfy verify targets -test 206 -fix
$ repvfy verify targets -test 130 -fix
$ repvfy verify targets -test 122 -fix
$ repvfy verify targets -test 106 -fix

$ repvfy verify repository -test 706 -fix

$ repvfy verify policies -test 702 -fix
$ repvfy verify policies -test 700 -fix
$ repvfy verify policies -test 103 -fix
$ repvfy verify metrics -test 199 -fix
$ repvfy verify policies -test 101 -fix

$ repvfy verify metrics -test 705 -fix
$ repvfy verify ecm -test 799 -fix
$ repvfy verify metrics -test 703 -fix
$ repvfy verify metrics -test 110 -fix
$ repvfy verify targets -test 189 -fix

$ repvfy verify loaders -test 700 -fix

./repvfy -usr SYSMAN -tns emrep -pwd
 -module TARGETS -level 9 -detail
./repvfy -usr SYSMAN -tns emrep -pwd
 dump target -name  -type oracle_database
convert this post to pdf.

In many shops year on year a capacity planning will be done to find out how much space to be added. If you want to find out what are the mountpoint to which storage as to be added, you can get those information from OEM. Our client shop has more than 1000 targets. No way there to generate report from oem to find out what are the mountpoint reaching threshold.
If you know the sysman pwd, you can use below query to find out potential mountpoint to which you need to add space.

select b.host_name,b.target_name,a.key_value,a.message,a.collection_timestamp from MGMT_CURRENT_SEVERITY a,mgmt_targets b
where a.target_guid= b.target_guid and
(a.message_nlsid like 'host_file%' or a.message_nlsid like 'DiskGroup%' or a.message_nlsid like 'archFull%')
order by b.host_name asc,b.target_name asc,a.key_value asc,a.collection_timestamp desc
convert this post to pdf.

A client mailed us with a query, which crashes with 4031 error. It’s a complex query has Nl and Hash joins. While diagonising i found that the problem lies with the below two line of where condition.

AND  ( (GL_MONTH_ACTV_BAL.BUS_UNIT_ID)=SAP_BUS_UNIT_MO_ASIS.BUS_UNIT_ID and SAP_BUS_UNIT_MO_ASIS.BUS_UNIT_CD_TYPE in (‘XYZ123′ ,’ABC’)  )
 AND  ( (GL_MONTH_ACTV_BAL.GLAS_BUS_UNIT_ASIS_ID)=GLAS_BUSINESS_UNIT.BUS_UNIT_ID   AND GLAS_BUSINESS_UNIT.BUS_UNIT_CD_TYPE IN (‘ABC123′ ,’ABC’)  )

When i change the query to

AND  ( (to_number(GL_MONTH_ACTV_BAL.BUS_UNIT_ID))=SAP_BUS_UNIT_MO_ASIS.BUS_UNIT_ID and SAP_BUS_UNIT_MO_ASIS.BUS_UNIT_CD_TYPE in (‘XYZ123′ ,’ABC’)  )
 AND  ( (to_number(GL_MONTH_ACTV_BAL.GLAS_BUS_UNIT_ASIS_ID))=GLAS_BUSINESS_UNIT.BUS_UNIT_ID   AND GLAS_BUSINESS_UNIT.BUS_UNIT_CD_TYPE IN (‘ABC123′ ,’ABC’)  )

It worked. The funny thing here is the column GL_MONTH_ACTV_BAL.BUS_UNIT_ID is  of number datatype.  We were not able to even get the explain plan user “Set autot trace exp”, as the query crashes with 4031 error.

On error and trial of this query, we found that ‘star_transformation_enabled’ is the culprit. It’s pure luck i found this one. I have to change this value from true to false.

I can’t set this at db level or session level, as it might have impact on other queries. That’s where we used /*+opt_param*/ hint

SELECT /*+ OPT_PARAM(‘star_transformation_enabled’,'false’) */

convert this post to pdf.

From 10g there is a change in No_Invalidate parameter of dbms_stats. Default value of No_Invalidate in 10g is dbms_stats.Auto_Invalidate. Means the cursor will remain valid for 5 hrs after the stats gathering. This is to avoid spike in cpu and othe resources due to hard parsing. 5 hrs time limit is governed by underscore parameter “_optimizer_invalidation_period”

convert this post to pdf.

It’s common missing the arch log file needed for standby recovery, there by standby going out of sync. One way before 10g is rebuilding the standby from scratch.

From 10g, you can create a incremental backup from primary and apply the incremental to standby site.

For Source and Target in ASM, use metalink note

Steps to perform for Rolling forward a standby database using RMAN incremental backup when primary and standby are in ASM filesystem [ID 836986.1]

BACKUP FROM SOURCE:

~~~~~~~~~~~~~~~~~~~

get the SCN from checkpoint_change#@v$datafile_header  of standby database. You can also take the current_scn@v$database. But v$database value comes from controlfile and if the controlfile value is recent than datafile, you may not be successful.

RMAN> BACKUP DEVICE TYPE DISK INCREMENTAL FROM SCN 329412309 DATABASE FORMAT ‘/local/eastus/orabackup00/rman/incr1_%U’;

if you want compressed backup

BACKUP AS COMPRESSED backupset DEVICE TYPE DISK INCREMENTAL FROM SCN 8977054477894  DATABASE FORMAT  ‘/local/eastus/orabackup00/rman/incr1_%U’;

Starting backup at 06-MAY-09

using target database control file instead of recovery catalog

allocated channel: ORA_DISK_1

channel ORA_DISK_1: sid=422 devtype=DISK

channel ORA_DISK_1: starting full datafile backupset

channel ORA_DISK_1: specifying datafile(s) in backupset

input datafile fno=00015 name=/local/eastus/oradata01/eastusp1/eastusp1rdgdbo_data01.dbf

input datafile fno=00002 name=/local/eastus/oradata03/eastusp1/eastusp1undotbs01.dbf

input datafile fno=00010 name=/local/eastus/oradata05/eastusp1/eastusp1audit_data01.dbf

input datafile fno=00014 name=/local/eastus/oradata05/eastusp1/eastusp1_sysaux_01.dbf

input datafile fno=00013 name=/local/eastus/oradata05/eastusp1/eastusp1statspack_data.dbf

input datafile fno=00008 name=/local/eastus/oradata05/eastusp1/eastusp1xdb01.dbf

input datafile fno=00004 name=/local/eastus/oradata05/eastusp1/eastusp1drsys01.dbf

input datafile fno=00009 name=/local/eastus/oradata05/eastusp1/netiq_data01.dbf

input datafile fno=00003 name=/local/eastus/oradata05/eastusp1/eastusp1cwmlite01.dbf

input datafile fno=00005 name=/local/eastus/oradata05/eastusp1/eastusp1odm01.dbf

input datafile fno=00001 name=/local/eastus/oradata00/eastusp1/eastusp1system01.dbf

input datafile fno=00006 name=/local/eastus/oradata00/eastusp1/eastusp1tools01.dbf

input datafile fno=00007 name=/local/eastus/oradata00/eastusp1/eastusp1users01.dbf

input datafile fno=00012 name=/local/eastus/oradata02/eastusp1/eastusp1east4_idx01.dbf

input datafile fno=00017 name=/local/eastus/oradata02/eastusp1/eastusp1rdgdbo_idx01.dbf

input datafile fno=00011 name=/local/eastus/oradata01/eastusp1/eastusp1east4_data01.dbf

input datafile fno=00016 name=/local/eastus/oradata01/eastusp1/eastusp1ASI_Data01.dbf

channel ORA_DISK_1: starting piece 1 at 06-MAY-09

channel ORA_DISK_1: finished piece 1 at 06-MAY-09

piece handle=/local/eastus/orabackup00/rman/incr1_tvkebumh_1_1 tag=TAG20090506T160952 comment=NONE

channel ORA_DISK_1: backup set complete, elapsed time: 00:07:05

Finished backup at 06-MAY-09

TRANSFER THE INCREMENTAL BACKUP TO TARGET

Catalog the incremental backup. This help rman to indentify the new backup.

RMAN> CATALOG START WITH ‘/local/eastus/orabackup00/rman/incr1_tvkebumh_1_1′;

searching for all files that match the pattern /local/eastus/orabackup00/rman/incr1_tvkebumh_1_1

List of Files Unknown to the Database

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

File Name: /local/eastus/orabackup00/rman/incr1_tvkebumh_1_1

Do you really want to catalog the above files (enter YES or NO)? YES

cataloging files…

cataloging done

List of Cataloged Files

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

File Name: /local/eastus/orabackup00/rman/incr1_tvkebumh_1_1

Recover with redo clause

RMAN> RECOVER DATABASE NOREDO;

Starting recover at 06-MAY-09

using channel ORA_DISK_1

channel ORA_DISK_1: starting incremental datafile backupset restore

channel ORA_DISK_1: specifying datafile(s) to restore from backup set

destination for restore of datafile 00001: /local/eastus/oradata00/eastusp1/eastusp1system01.dbf

destination for restore of datafile 00002: /local/eastus/oradata03/eastusp1/eastusp1undotbs01.dbf

destination for restore of datafile 00003: /local/eastus/oradata05/eastusp1/eastusp1cwmlite01.dbf

destination for restore of datafile 00004: /local/eastus/oradata05/eastusp1/eastusp1drsys01.dbf

destination for restore of datafile 00005: /local/eastus/oradata05/eastusp1/eastusp1odm01.dbf

destination for restore of datafile 00006: /local/eastus/oradata00/eastusp1/eastusp1tools01.dbf

destination for restore of datafile 00007: /local/eastus/oradata00/eastusp1/eastusp1users01.dbf

destination for restore of datafile 00008: /local/eastus/oradata05/eastusp1/eastusp1xdb01.dbf

destination for restore of datafile 00009: /local/eastus/oradata05/eastusp1/netiq_data01.dbf

destination for restore of datafile 00010: /local/eastus/oradata05/eastusp1/eastusp1audit_data01.dbf

destination for restore of datafile 00011: /local/eastus/oradata01/eastusp1/eastusp1east4_data01.dbf

destination for restore of datafile 00012: /local/eastus/oradata02/eastusp1/eastusp1east4_idx01.dbf

destination for restore of datafile 00013: /local/eastus/oradata05/eastusp1/eastusp1statspack_data.dbf

destination for restore of datafile 00014: /local/eastus/oradata05/eastusp1/eastusp1_sysaux_01.dbf

destination for restore of datafile 00015: /local/eastus/oradata01/eastusp1/eastusp1rdgdbo_data01.dbf

destination for restore of datafile 00016: /local/eastus/oradata01/eastusp1/eastusp1ASI_Data01.dbf

destination for restore of datafile 00017: /local/eastus/oradata02/eastusp1/eastusp1rdgdbo_idx01.dbf

channel ORA_DISK_1: reading from backup piece /local/eastus/orabackup00/rman/incr1_tvkebumh_1_1

channel ORA_DISK_1: restored backup piece 1

piece handle=/local/eastus/orabackup00/rman/incr1_tvkebumh_1_1 tag=TAG20090506T160952

channel ORA_DISK_1: restore complete, elapsed time: 00:00:04

Finished recover at 06-MAY-09

RMAN>

You can check the checkpoint_change#@datafile_header, it should have increased and should be equal to the point you started the incremental backup.

Controlfile of standby may not be updated after this excercise. Recreate the standby controlfile from primary again.

convert this post to pdf.

########

– You can copy below script to notepad and change “SOURCE” to your SOURCE DB and “TARGET” to your TARGET DB
########

Execute in both source and target:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


connect SYS/password as SYSDBA

EXEC DBMS_STREAMS_ADM.REMOVE_STREAMS_CONFIGURATION();
drop user strmadmin cascade;

    create user STRMADMIN identified by STRMADMIN123;
    GRANT CONNECT, RESOURCE, AQ_ADMINISTRATOR_ROLE,DBA to STRMADMIN;
    execute DBMS_STREAMS_AUTH.GRANT_ADMIN_PRIVILEGE('STRMADMIN');
    alter system set aq_tm_processes=1;
   
    connect STRMADMIN/STRMADMIN123

    BEGIN
     DBMS_STREAMS_ADM.SET_UP_QUEUE(
      queue_table => 'STREAMS_QUEUE_TABLE',
      queue_name => 'STREAMS_QUEUE',
      queue_user => 'STRMADMIN');
    END;
    /

create db link from source to target and vice versa

Test using

select * from global_name@db_link;

verify it is returning correct value
Steps to be carried out at the Destination Database
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Add apply rules for the Schema at the destination database :

connect STRMADMIN/STRMADMIN123
 BEGIN
  DBMS_STREAMS_ADM.ADD_SCHEMA_RULES(
    schema_name => 'SCOTT',
    streams_type => 'APPLY ',
    streams_name => 'STRMADMIN_APPLY',
    queue_name => 'STRMADMIN.STREAMS_QUEUE',
    include_dml => true,
     include_ddl => true,
    source_database => 'SOURCE');
 END;
 /
  BEGIN
      DBMS_APPLY_ADM.ALTER_APPLY(
       apply_name => 'STRMADMIN_APPLY',
       apply_user => 'SCOTT'
              );
 END;
 /

  BEGIN
 DBMS_APPLY_ADM.SET_PARAMETER(
   APPLY_NAME => 'STRMADMIN_APPLY',
   PARAMETER => 'disable_on_error',
   VALUE => 'N');
  END;
/
 

DECLARE
 v_started number;
BEGIN
 SELECT decode(status, 'ENABLED', 1, 0) INTO v_started
 FROM DBA_APPLY WHERE APPLY_NAME = 'STRMADMIN_APPLY';
 if (v_started = 0) then
   DBMS_APPLY_ADM.START_APPLY(apply_name  => 'STRMADMIN_APPLY');
 end if;
END;
/

 
Steps to be carried out at the Source Database SOURCE
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

 Connect to STRMADMIN schema at source and execute below steps

connect STRMADMIN/STRMADMIN123

 BEGIN
  DBMS_STREAMS_ADM.ADD_SCHEMA_RULES(
    schema_name => 'SCOTT',
    streams_type => 'CAPTURE',
    streams_name => 'STREAM_CAPTURE',
    queue_name => 'STRMADMIN.STREAMS_QUEUE',
    include_dml => true,
   include_ddl => true,
   inclusion_rule => true,
    source_database => 'SOURCE');
 END;
 /

     BEGIN
 DBMS_STREAMS_ADM.ADD_SCHEMA_PROPAGATION_RULES(
     schema_name => 'SCOTT',
     streams_name => 'STREAM_PROPAGATE',
     source_queue_name => 'STRMADMIN.STREAMS_QUEUE',
     destination_queue_name => 'STRMADMIN.STREAMS_QUEUE@TARGET',
     include_dml => true,
     include_ddl => true,
     source_database => 'SOURCE');
 END;
 /

Steps to replicate the data to destination:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

First load the dictionary information to redo log file, otherwise you might get “WAITING FOR DICTIONARY REDO” during the capture process.

exec DBMS_CAPTURE_ADM.BUILD();

get the scn of the logfile which contains dictionary information.

select  FIRST_CHANGE#,name from v$archived_log where dictionary_begin='YES';

note the first_change# from above query. Make sure the arch logfile is available in disk from the filename got from name column of above query.

Take the datapump export from source

expdp userid/password dumpfile=<filename> directory=<directory_name>  flashback_scn=<first_change#>

Note the flashback_scn option

import the datapump to target

impdp userid/password dumpfile=<filename> directory=<directory_name> streams_configuration=n

note the streams_configuration=n in impdp

go to source database

exec  DBMS_CAPTURE_ADM.STOP_CAPTURE(capture_name  => 'STREAM_CAPTURE',force=>true);

You can either give force=>true or leave it, based on your requirement.

execute dbms_capture_adm.drop_capture ('STREAM_CAPTURE');

execute DBMS_CAPTURE_ADM.CREATE_CAPTURE(queue_name => 'STRMADMIN.STREAMS_QUEUE', capture_name => 'STREAM_CAPTURE', use_database_link=>TRUE,start_scn=><first_change#>, first_scn=><first_change#>);

note the start_scn and first_scn, this value is taking from v$archived_log.

      begin
       dbms_capture_adm.set_parameter('STREAM_CAPTURE','_SGA_SIZE','2000');
       dbms_capture_adm.set_parameter('STREAM_CAPTURE','_CHECKPOINT_FREQUENCY','1000');
       dbms_capture_adm.set_parameter('STREAM_CAPTURE','TRACE_LEVEL','2');
       dbms_capture_adm.set_parameter('STREAM_CAPTURE','PARALLELISM','20');
       DBMS_CAPTURE_ADM.START_CAPTURE(capture_name  => 'STREAM_CAPTURE');
     end;
/

when you set TRACE_LEVEL parameters, incase if the capture process fails you can trace more information to debug.

Go to destination and execute

exec  DBMS_APPLY_ADM.START_APPLY(apply_name  => 'STRMADMIN_APPLY');

Make changes in primary and see whether it is getting replicated in secondary. You can create heart beat table.

heart beat table can be like

create table scott.streams_heartbeat(source_name varchar2(30),Change_dt Date);

insert into scott.streams_heartbeat('<SOURCE_DB_NAME>',SYSDATE);

COMMIT;

Update heart beat table every minute using dbms_job/scheduler or even crontab.

 

Execute the below statement,

select state from v$streams_capture

you should see “CAPTURING CHANGES”

convert this post to pdf.

Capture process might stop sometime due to space issue in sysaux tablespace. Checkpoint information is stored in logmnr_restart_ckpt$ for quicker restart. From 10.2 onwards oracle has enabled automatic purging using the parameter CHECKPOINT_RETENTION_TIME. By default, checkpoint information is stored for last 60 days.
In some environment 60 days could be very long.This is one reason why sysaux tablespace can grow fast.
You can change the default by setting below parameter,

exec dbms_capture_adm.alter_capture(capture_name =>,CHECKPOINT_RETENTION_TIME=> 7);

Also you can bring the hwm of the table using below command,

alter table system.LOGMNR_RESTART_CKPT$ enable row movement;
alter table system.LOGMNR_RESTART_CKPT$ shrink space ;
alter table system.LOGMNR_RESTART_CKPT$ disable row movement;

You can also shrink the primary key index on this table.

Also you can force manual checkpoint using “_checkpoint_force”=’Y’.

convert this post to pdf.

If you are managing logical standby, it’s going out of sync is common. If number of log applied is very huge, and you find transaction on one table consuming lot of time in applying.

Then skip the transaction on table as below

execute dbms_logstdby.skip('DML','SCHEMA_NAME','TABLE_NAME');

Once the remaining log file applied and standby is in sync with primary, you have instantiate the skipped table again.

One option to do is create a db_link to primary and instantiate using,

EXECUTE DBMS_LOGSTDBY.INSTANTIATE_TABLE(schema_name => <SCHEMA_NAME>, table_name => <TABLE_NAME>, dblink =><DB LINK NAME>);

There might be cases where the table you are trying to instantiate is very huge. That case you can use expdp to instantiate the table as below,

A. Stop SQL apply

ALTER DATABASE STOP LOGICAL STANDBY APPLY;

B. put in a skip rule(to keep others from making changes to the table on the Logical)

EXECUTE DBMS_LOGSTDBY.SKIP('DML','TEST,'AAA');

C1.Drop and recreate the table test.aaa

drop table test.aaa;
create table test.aaa(num1 number, text1 varchar2(50));

C2. then get the datapump data from the Primary

On the Logical:

SELECT APPLIED_SCN, LATEST_SCN, MINING_SCN, RESTART_SCN FROM V$LOGSTDBY_PROGRESS;

expdp system/oracle tables=test.aaa dumpfile=expaaa.dmp flashback_scn=<scn#>

Note: Flashback scn will be restart_scn which you get from v$logstdby_progress.

4. then import the datapump data to the Logical

impdp system/oracle dumpfile=expaaa.dmp tables=test.aaa table_exists_actions=append

5. then unskip the skip rule for the table

EXECUTE DBMS_LOGSTDBY.UNSKIP(’DML’,'TEST’,’AAA’);

analyze table test.aaa compute statistics or use dbms_stats to gather statistics.

6. then start sql apply

SQL> ALTER DATABASE START LOGICAL STANDBY APPLY ;

If you like to use exp/imp for instantiatiion follow Note 271455.1 – Synchronizing tables in a Logical Standby Database

 
convert this post to pdf.

If  you are in 10203 rac db and if you see crsd.bin as top consumer apply the CRS Bundle patch 3 #7117233. Till you apply the patch you can have a crontab scheduled to clean *.log in CRS_HOME/log/<hostname>/client 

convert this post to pdf.

When there is heavy load on production, logical standby will not be able to keep up the pace. This is because it has to mine the redo log convert to sql statement and apply to standby db. If there is huge gap, the apply process get struck.
Incase if you are able to know in advance about huge data load, you can set below parameters.

alter database stop logical standby apply;
execute dbms_logstdby.apply_set('MAX_SERVERS',60);
execute dbms_logstdby.apply_set('MAX_SGA',2000);
execute dbms_logstdby.apply_set('APPLY_SERVERS',52);
execute dbms_logstdby.apply_set('PREPARE_SERVERS',5);
execute dbms_logstdby.apply_set ('PRESERVE_COMMIT_ORDER','FALSE');
execute dbms_logstdby.apply_set('_MAX_LOG_LOOKBACK',1);
execute dbms_logstdby.apply_set('_EAGER_SIZE',1000);
alter database start logical standby apply;
convert this post to pdf.

Capture process in one of our client db was hanging with above message. While investigating we found out that some of the arch files need for capture is missing from os, it’s not in tape also. Only option left is to rebuild the streams. Since client is not worried about all the data being in target db, we proposed the alternate option. By which we drop the existing capture process and create a new capture process.

This is what needs to be done,

select queue_name,rule_set_name,queue_owner,rule_set_owner,negative_rule_set_owner, negative_rule_set_name from dba_capture where capture_name =’STREAM_CAPTURE’;

Note the output of above query.
Stop the capture,
exec DBMS_CAPTURE_ADM.STOP_CAPTURE(capture_name => ‘STREAM_CAPTURE’,force=>true);

Stop the apply in target,
exec DBMS_APPLY_ADM.STOP_APPLY(apply_name => ‘STRMADMIN_APPLY’);

Drop the existing capture in source,
execute dbms_capture_adm.drop_capture (‘STREAM_CAPTURE’);

Recreate the Capture in source,
execute DBMS_CAPTURE_ADM.CREATE_CAPTURE(queue_name => ‘STRMADMIN.STREAMS_QUEUE’, capture_name => ‘STREAM_CAPTURE’, use_database_link=>TRUE,rule_set_name => ‘STRMADMIN.RULESET$_244′,start_scn=>null, first_scn=>null);

Some of the values feed to above query could be feeded to CREATE_CAPTURE procedure. One important thing is note is start_scn and first_scn. If you know the scn from which to start and sure that arch file is there in disk, you can feed the start_scn and first_scn value. Otherwise set it as null.
Null value will take the current scn.

If you are feeding scn and arch file is not there, then capture process will stop with “Waiting for Dictionary Redo” message.

The above approach fixed the problem and streams started to run.

convert this post to pdf.

One of the excercise we do every year in our shop is to request business to add more storage. This year we are following a different approach. We are going to stop monitoring tablespace usage in OEM and concentrate only on used and available space on each mount point. To do that, we are putting all the tablespace in autoextend on, except temp and undo.
Once we have removed tablepsace usage monitoring in OEM, we did the shrink of each datafile to remove extra allocated space. So at any point of time tablespace usage will look 100%, with the exception that autoextend is on. Currently we have done this excercise in dev environment, we got a amazing savings for around 4TB savings.
Advantage:
Effective use of storage. Each tablespace grow only when there is space pressure.
Extra ticket generated for tablespace usage alert can be avoided.
Disadvt:
OS mountpoint should be monitored very closely. If any alert, needs to be acted immediatly. As in some cases we need to purchase extra storage.

Ok, this works only for non undo and temp tablespace. We have put the undo and temp in autoextend off mode. So, we need to monitor these two tablespace. While monitoring these two tablespace, we need to consider expired,unexpired extents. We created two user managed metric alert in OEM for these two tablespace. Below is the script which we have used.

Metric Name Temp Usage
Metric Type NUMBER
SQL Query Output Two Columns
SQL Query select * from (select z.tablespace_name||’ Used %’,z.Perc_used from (select x.tablespace_name,trunc((v_usage_gb/v_total_gb)*100,2) Perc_Used from (select tablespace_name,trunc(sum(bytes/1024/1024/1024),2) v_total_gb from dba_temp_files group by tablespace_name) x, (select tablespace,trunc(sum(blocks*8192/1024/1024/1024),2) v_usage_gb from v$sort_usage group by tablespace) y where x.tablespace_name=y.tablespace order by Perc_used DESC ) z where rownum = 1 union all select ’0′,0 from dual ) x1 where rownum = 1

Metric Name Undo Usage
Metric Type NUMBER
SQL Query Output Two Columns
SQL Query select y.tablespace_name,trunc((y.total_gb/z.grand_total_gb)*100,2) Perc_Used from (select x.tablespace_name, trunc(x.total_bytes/1024/1024/1024,2) Total_Gb from (select tablespace_name, (nvl(sum(bytes),0)) total_bytes from dba_undo_extents where status in (‘ACTIVE’,'UNEXPIRED’) group by tablespace_name order by 2 desc) x where rownum=1) y, (select tablespace_name,sum(bytes/1024/1024/1024) grand_total_gb from dba_data_files group by tablespace_name) z where y.tablespace_name = z.tablespace_name

convert this post to pdf.

This is one feature which i use very often.  Even after killing the session using alter system command, the oracle process still hangs in the os.  In such scenario without getting into oracle account we can kill the os process. Please note you need to sysdba privs.

sqlplus "/as sysdba"
oradebug setospid spid@v$process;
oradebug short_stack;
oradebug event immediate crash;
oradebug short_stack;
This will kill the associated os process. This is undocumented so all the warning holds good.
If you want to kill the current session which you have connected then, alter session set 'immediate crash'; Though not much use in real world scenario. convert this post to pdf.

3113

We upgraded one of the db from 9i to 10g. One of the query which is involving a view was erroring out with 3113 error.

select
View1.ACCT_CST_CTR_BK_CD,
View1.ACCT_CST_CTR_BK_DESC,
WCPADM.CAL.FULL_DT_DESC,
sum(WCPADM.WCP_BAS_FCT.TOT_PROD_EXPEN_AM),
sum(WCPADM.WCP_BAS_FCT.PROD_REV_AM)
FROM
View1,
WCPADM.CAL,
WCPADM.WCP_BAS_FCT
WHERE
( WCPADM.WCP_BAS_FCT.PSTN_ID=View1.PSTN_ID)
AND ( WCPADM.CAL.CAL_ID=WCPADM.WCP_BAS_FCT.EFF_DT_ID )
AND (View1.ACCT_CST_CTR_BK_CD In ( '0014036','0029284','0009570','0025336' )
AND  WCPADM.CAL.FULL_DT_DESC In ( '2007 FULL YEAR','2006 FULL YEAR','SEP 2008 YTD' )
)
GROUP BY
View1.ACCT_CST_CTR_BK_CD,
View1.ACCT_CST_CTR_BK_DESC,
WCPADM.CAL.FULL_DT_DESC
/
select
*
ERROR at line 1:
ORA-03113: end-of-file on communication channel

I promptly raised SR, oracle suggested few patches, then events and then some underscore parameters. Nothing worked.

These query is getting generated from BO, so we have been instructed by business to tune without touching it.

We tried various options, but nothing worked. Then i took the query out and run it in sqlplus by adding (select * from View1 where rownum > 0) in place of view as inline query. This worked.

This clearly showed there is some issue with view merging.

We set the parameter “_comple_view_merging”=false. But even this didn’t help. The by setting “_simple_view_merging”=false. We are able to address this issue.



Visitors Count


convert this post to pdf.

Strange…

“Strange” – This is the subject of the mail, which i got from one of the developer. He has query which returns 2 different result.

SQL>  select count(1) from glrsadm.glrs_acct_own o, glwadm.intl_cntc c where  c.dim_nb = to_number(o.cert_own_id) and rcrd_Sts = 'x' and cert_own_id = 1234; 

  COUNT(1)
----------
         9 

SQL> select count(1) from glrsadm.glrs_acct_own o, glwadm.intl_cntc c where  c.dim_nb =o.cert_own_id
  2   and rcrd_Sts = 'x' and cert_own_id = 1234; 

  COUNT(1)
----------
         0

The only different between these two queries is to_number on o.cert_own_id. Datatype of cert_own_id is number. So he was puzzled why it is returning different result.

Closer look on the autotrace showed the reason behind this behaviour.

set autot trace exp 

select count(1) from glrsadm.glrs_acct_own o, glwadm.intl_cntc c where  c.dim_nb = to_number(o.cert_own_id) and rcrd_Sts = 'A' and cert_own_id = 876279; 

Predicate Information (identified by operation id):
--------------------------------------------------- 

   3 - access("CERT_OWN_ID"=1234 AND "RCRD_STS"='x')
   5 - access("C"."DIM_NB"=TO_NUMBER(TO_CHAR("O"."CERT_OWN_ID"))) 
Note the bolded one, it uses the table glrsadm.glrs_acct_own. 

select count(1) from glrsadm.glrs_acct_own o, glwadm.intl_cntc c where  c.dim_nb =o.cert_own_id  and rcrd_Sts = 'x' and cert_own_id = 1234; 

  4 - access("C"."DIM_NB"=1234)
   6 - access("GLRS_ACCT_OWN_MV"."CERT_OWN_ID"=1234)
       filter("C"."DIM_NB"="GLRS_ACCT_OWN_MV"."CERT_OWN_ID")
Note, this uses the materialized view. This view has old data, that's why it doesn't return the correct data.

This clearly shows that query rewrite is enabled and fetching the wrong result.

SQL> alter session set query_rewrite_enabled=false; 

Session altered. 

SQL>  select count(1) from glrsadm.glrs_acct_own o, glwadm.intl_cntc c where  c.dim_nb = to_number(o.cert_own_id) and rcrd_Sts = 'x' and cert_own_id = 1234; 

  COUNT(1)
----------
         9 

SQL>  select count(1) from glrsadm.glrs_acct_own o, glwadm.intl_cntc c where  c.dim_nb =o.cert_own_id   and rcrd_Sts = 'x' and cert_own_id = 1234; 

  COUNT(1)
----------
         9 

This behaviour can happen when
SQL> show parameter query_rewrite_integrity 

NAME                                 TYPE        VALUE
------------------------------------ ----------- ------------------------------
query_rewrite_integrity              string      STALE_TOLERATED 
and
SQL> show parameter query 

NAME                                 TYPE        VALUE
------------------------------------ ----------- ------------------------------
query_rewrite_enabled                string      TRUE



Visitors Count


convert this post to pdf.

Posted by Borndba on April 4, 2009 at 12:31 am under Oracle, Oracle Administration.
Tags: ,
Comments Off.

Delete statement Hanging

In one of our DB, a delete statement was hanging.

delete from adv_temp.recs_type_966
where 1 = 1
and exists (
  select  *
  from adv_master.RECS_TYPE_966_VIEW r
  where r.plot_fk in (-1,5419,5420)
  and r.plot_fk between 5419 and 5420
  and r.p019 = recs_type_966.p019
  and r.p027 = recs_type_966.p027
  and r.f001 = recs_type_966.f001
);

Subquery got a view. The session which is executing was hanging, interestingly it was hanging on ‘SQL*Net message from client’. To me it looked like a merging issue. So i recommeded to include rownum >0 to the subquery. But it was rejected as this is a vendor code and we don’t have any control on this.
Meanwhile, we tried various options like changing cursor_sharing=exact, increasing pga_aggregate_target etc., But it didn’t work out.

When i insert a rule hint to the subquery, it worked fine.

delete from adv_temp.recs_type_966
where 1 = 1
and exists (
  select /*+rule*/ *
  from adv_master.RECS_TYPE_966_VIEW r
  where r.plot_fk in (-1,5419,5420)
  and r.plot_fk between 5419 and 5420
  and r.p019 = recs_type_966.p019
  and r.p027 = recs_type_966.p027
  and r.f001 = recs_type_966.f001
);

But again this not acceptable, since we can’t change the code.

Luckily we got the alternate solutions. We introduced the underscore parameter “_unnest_subquery”=false. It worked great.

It’s a dynamic parameter and we set it as spfile=both;

The batch program went fine without any issues.



Visitors Count


convert this post to pdf.

Posted by Borndba on April 4, 2009 at 12:31 am under Oracle, Oracle Performance.
Tags: ,
Comments Off.

ORA-00600: [ktsircinfo_num1],

In one of our DB, we drop and create a table during batch program. This program runs every day. Today we got a call from the user that they are encountering error

 ORA-00955: name is already used by an existing object

This error message was very clear. We immedately replied back saying that check the code, as it is trying to recreate the object which is already in the DB.

But actually it turned out to be a more interesting issue.

The table in question has been droped from the DB. When we query the dba_tables/obj$, this objects was not present.

However, when we try to give

    select count(*) from table_name;

We got a surprising


ERROR at line 1:
ORA-00600: internal error code, arguments: [ktsircinfo_num1], [21], [21], [2335770], [], [], [], []

We were initially puzzled why this error is coming from. Then we fixed this issue by flushing the shared pool.



Visitors Count


convert this post to pdf.

Posted by Borndba on April 4, 2009 at 12:30 am under Oracle, Oracle Internal.
Tags: ,
Comments Off.

Dead Lock

I got a mail from one of our onshore DBA to take a relook into a dead lock trace file. He also proposed, that it could be due to itl,unique constraints or fk. He told us that he checked for fk where indexes are missing and found none.

Deadlock graph:
                       ---------Blocker(s)--------  ---------Waiter(s)---------
Resource Name          process session holds waits  process session holds waits
TX-0007001a-001aeb6d        21      23     X             20      51           S
TX-0004000c-001ab9d1        20      51     X             21      23           S
session 23: DID 0001-0015-000000A7      session 51: DID 0001-0014-00000253
session 51: DID 0001-0014-00000253      session 23: DID 0001-0015-000000A7

Rows waited on:
Session 51: obj - rowid = 00008808 - AAAJ08AAKAAAAAAAAA
  (dictionary objn - 34824, file - 10, block - 0, slot - 0)
Session 23: obj - rowid = 00008808 - AAAJ08AALAAAAAAAAA
  (dictionary objn - 34824, file - 11, block - 0, slot - 0)

There is something totally wrong with the tracefile. objn number 34824 lead us to a different table. There is no relation between that table and the current dead lock table. Moreover the statement which is causing this issue is “Insert” statement.

This is what my response to the onshore DBA. It turn out to be that, there are some missing indexes on foreign key. He failed to notice that.

ITL waits:
As you said ITL will not come for insert statement. Unless insert turns to update in index we will not be getting ITL waits on insert. But i don’t think it could be the reason here. There is a chance that if the table has trigger and trigger has autonomous transaction we can see deadlocks. But the table XXX_ACCOUNTS doesn’t have any trigger. INITRANS for table is by default 2. Oracle documentation is wrong in this respect. Simple block dump will show that it will use 2 itl slots.

Unique constraints:
There are few unique constraints on this table. But i don’t think it is to do with unique space violation. If a deadlock caused due to unique violation then in the deadlock trace file we will be seeing some like below

Rows waited on:
Session 7: no row
Session 8: no row

UnIndexed Foreign Key:
My analysis pointing towards this. My scripts shows that following columns which has fk constraint is not indexed.

STAT TABLE_NAME                     COLUMNS              COLUMNS
---- ------------------------------ -------------------- --------------------
**** XXX_ACCOUNTS                SRC_SYS_CODE
**** XXX_ACCOUNTS                ACC_TYPE_CODE
**** XXX_ACCOUNTS                CCY_CODE
**** XXX_ACCOUNTS                INST_CLASS
**** XXX_ACCOUNTS                LINE_OF_BUSINESS

I am attaching the scripts which i have used. If we index these columns probably this error might goaway.

Note:
The dead lock trace file is misleading us . For instance from the below content the block 0 is waiting on file 10 or file 11. This is absurd. No file will have block number 0. Hence the Dictionary object number what they are referring is not true. So table FDL_XYZ_LOG waiting on this insert is incorrect. Behaviour such as this might came in ASSM tablespace if we use deferrable constraints. Though the tablespace is ASSM, we are not using any deferrable constraints. Definite candidate for the bug.



Visitors Count

class="statcounter">
href=”http://www.statcounter.com/blogger/”
target=”_blank”> src="http://c.statcounter.com/4628332/0/06d2759c/0/"
alt="blogspot visitor" >


convert this post to pdf.

Posted by Borndba on April 4, 2009 at 12:29 am under Oracle, Oracle Administration.
Tags: ,
Comments Off.

ORA-00600 [qmtInit1]

A schedule export backup on one of our dev DB has failed due to below ora 600


ORA-00600: internal error code, arguments: [qmtInit1], [], [], [], [], [], [], []

As per metalink note:351650.1, they defined this as a bug and workaround is to restart the server.

I tried flushing the shared pool. It didn’t help.

There were some invalid objects, tried compiling but still didn’t help.

From the associated trace file of ora-600, this error was coming on the statement

Current SQL statement for this session:
SELECT URL, LOCAL, STRIPPED_VAL      FROM SYS.KU$_XMLSCHEMA_VIEW      WHERE OWNE
R_NAME = :OWNER

Though this object is valid, i tried recompiling it.

This worked. Our full export started working with out any issues.

This error comes while exporting cluster definitions. I was seeing some wait events like xdb initialization in the event@v$session.



Visitors Count


convert this post to pdf.

Posted by Borndba on April 4, 2009 at 12:28 am under Oracle, Oracle Internal.
Tags: ,
Comments Off.

Excel Sheet report from OEM

   We have an requirement where we have to send a monthly report on space usage and other details to management. Our shops has more than 600 DB. It's very difficult to get into each DB and generate these report. Luckily for us we use 10g OEM grid. So we have developed a script which uses owa_sylk (refer asktom) to generate the excel sheet. I am giving some of the code which we use.

Size of all the DB:
          This script gives hostname,db wise details. The size will be equilent to sum(bytes) from dba_extents.

declare
    output utl_file.file_type;
    lv_target Varchar2(30) := 'ALL';
    lv_file_name varchar2(30) ;
begin

    lv_file_name := lv_target||'_DB_Size.slk';

    output := utl_file.fopen( 'UTL_FILE_DIR', lv_file_name, 'w', 32000 );
    owa_sylk.show(
        p_file => output,
        p_query => 'select target_name DB_NAME,host_name Host,sum(trunc(tablespace_used_size/1024/1024/1024,2))size_GB'||
 '  from MGMT$DB_TABLESPACES group by host_name,target_name order by target_name ',
        p_sum_column =>
                 owa_sylk.owaSylkArray( 'N', 'N', 'Y'),
        p_show_grid => 'NO' ,
        p_user_heading => 'Size of ALL the DB as on '||sysdate);
    utl_file.fclose( output );
end;

Space usage of Arch location:
   This script generate space usage. This script may not work for all the environment, the pre-condition to it is, arch mountpoint should have "arch" keyword.
You need to create a table called RPT_ARCH_SIZES.

declare
    output utl_file.file_type;
    lv_host Varchar2(30) ;
    lv_file_name varchar2(30) ;
begin

    delete rpt_arch_sizes;

    Insert into rpt_arch_sizes select target_name,
     decode(instr(substr(mountpoint,instr(mountpoint,'/',-1)+1),'arch'),0,Upper(substr(mountpoint,instr(mountpoint,'/',-1)+1)),substr((substr(mountpoint,instr(mountpoint,'/',2)+1)),1,Instr(substr(mountpoint,instr(mountpoint,'/',2)+1),'/',1)-1)) database_name,
              mountpoint,
       trunc((sizeb/1024/1024/1024),2) Total_Size_GB ,
       trunc((usedb/1024/1024/1024),2)  Used_Space_GB,
       trunc((freeb/1024/1024/1024),2) Available_GB,
                            trunc((trunc((usedb/1024/1024/1024),2)/trunc                        ((sizeb/1024/1024/1024),2))*100,2) perc_Used
    from MGMT$STORAGE_REPORT_LOCALFS b
    where mountpoint like '%arch%';

    commit;

    lv_file_name := 'All_Storage_arch.slk';

    output := utl_file.fopen( 'UTL_FILE_DIR', lv_file_name, 'w', 32000 );

    owa_sylk.show(
        p_file => output,
      p_query => 'select target_name,upper(database_name) db_name,mountpoint,Total_Size_GB ,Used_Space_GB, Available_GB,perc_free Perc_used  '||
 ' from RPT_ARCH_SIZES order by perc_free desc ',

 p_show_grid => 'NO' ,

 p_user_heading => ' ARCHIEVELOG STORAGE REPORT OF ALL THE HOST as on '||sysdate);

 utl_file.fclose( output );

end;

Backup information of all the DB:
     The below script will give backup information. But in our environment, for some db the status and other columns are null. Need to look into that.

declare
    output utl_file.file_type;
    lv_target Varchar2(30) := 'All';
    lv_file_name varchar2(30) ;
begin

    lv_file_name := lv_target||'_Backup.slk';

    output := utl_file.fopen( 'UTL_FILE_DIR', lv_file_name, 'w', 32000 );
    owa_sylk.show(
        p_file => output,
        p_query => 'select host,Database_name,status,end_time,output_device_type '||
 ' from MGMT$HA_BACKUP order by end_time desc',
   p_show_grid => 'NO' ,
        p_user_heading => 'BACKUP REPORT Of all DB as on '||sysdate);

    utl_file.fclose( output );
end;

DB Features:
     This gives the list of DB features.
declare
    output utl_file.file_type;
    lv_target Varchar2(30) := 'oemrep';
    lv_file_name varchar2(30) ;
begin

    lv_file_name := lv_target||'_db_feature_info.slk';

    output := utl_file.fopen( 'UTL_FILE_DIR', lv_file_name, 'w', 32000 );
    owa_sylk.show(
        p_file => output,
        p_query => 'select Name,Currently_used,Description  '||
   '  from  MGMT$DB_FEATUREUSAGE  '||
   'where database_name=:HOSTNAME ',
          p_parm_names =>
               owa_sylk.owaSylkArray( 'HOSTNAME'),
       p_parm_values =>
                 owa_sylk.owaSylkArray( lv_target ),
        p_show_grid => 'NO' ,
        p_user_heading => 'DB feature info of '||lv_target||' as on '||sysdate);
    utl_file.fclose( output );
end;

Host Storage:
     This script will give host storage.

declare
    output utl_file.file_type;
    lv_host Varchar2(30) := 'cas2s040';
    lv_file_name varchar2(30) ;
begin

    lv_file_name := lv_host||'_Storage.slk';

    output := utl_file.fopen( 'UTL_FILE_DIR', lv_file_name, 'w', 32000 );
    owa_sylk.show(
        p_file => output,
        p_query => 'select mountpoint,trunc((sizeb/1024/1024),2) Total_Size_MB ,trunc((usedb/1024/1024),2)  Used_Space_MB,   trunc((sizeb/1024/1024),2) Available_MB '||
 ' from MGMT$STORAGE_REPORT_LOCALFS '||
 'where target_name=:HOSTNAME',
          p_parm_names =>
               owa_sylk.owaSylkArray( 'HOSTNAME'),
       p_parm_values =>
                 owa_sylk.owaSylkArray( lv_host ),
        p_sum_column =>
                 owa_sylk.owaSylkArray( 'N', 'Y', 'Y', 'Y'),
        p_show_grid => 'NO' ,
        p_user_heading => 'STORAGE REPORT Of '||lv_host||' as on '||sysdate);

    utl_file.fclose( output );
end;

Redo log size:
       This scripts gives the redo log file size for the inputted DB. Replace "oemrep" with your db name.

declare
    output utl_file.file_type;
    lv_target Varchar2(30) := 'oemrep';
    lv_file_name varchar2(30) ;
begin

    lv_file_name := lv_target||'_db_redo_info.slk';

    output := utl_file.fopen( 'UTL_FILE_DIR', lv_file_name, 'w', 32000 );
    owa_sylk.show(
        p_file => output,
        p_query => 'select group_num,members,thread_num,file_name,trunc(logsize/1024/1024,2) Redo_Size_MB,status '||
   '  from  MGMT$DB_REDOLOGS  '||
   'where target_name=:HOSTNAME ',
          p_parm_names =>
               owa_sylk.owaSylkArray( 'HOSTNAME'),
       p_parm_values =>
                 owa_sylk.owaSylkArray( lv_target ),
        p_show_grid => 'NO' ,
        p_user_heading => 'DB redolog info of '||lv_target||' as on '||sysdate);
    utl_file.fclose( output );
end;

DB features:
      DB features used in database. Change "oemrep" with your db name.

declare
    output utl_file.file_type;
    lv_target Varchar2(30) := 'oemrep';
    lv_file_name varchar2(30) ;
begin

    lv_file_name := lv_target||'_db_feature_info.slk';

    output := utl_file.fopen( 'UTL_FILE_DIR', lv_file_name, 'w', 32000 );
    owa_sylk.show(
        p_file => output,
        p_query => 'select Name,Currently_used,Description  '||
   '  from  MGMT$DB_FEATUREUSAGE  '||
   'where database_name=:HOSTNAME ',
          p_parm_names =>
               owa_sylk.owaSylkArray( 'HOSTNAME'),
       p_parm_values =>
                 owa_sylk.owaSylkArray( lv_target ),
        p_show_grid => 'NO' ,
        p_user_heading => 'DB feature info of '||lv_target||' as on '||sysdate);
    utl_file.fclose( output );
end;

Error Message:
     Error message encountered by the DB in last 3 months. Replace "oemrep" with your db name.

declare
    output utl_file.file_type;
    lv_target Varchar2(30) := 'oemrep';
    lv_file_name varchar2(30) ;
begin

    lv_file_name := lv_target||'_Err_hist.slk';

    output := utl_file.fopen( 'UTL_FILE_DIR', lv_file_name, 'w', 32000 );
    owa_sylk.show(
        p_file => output,
        p_query => 'select collection_timestamp,Metric_name,Error_message '||
 ' from MGMT$METRIC_ERROR_HISTORY '||
 'where target_name=:DATABASE_NAME order by 1',
          p_parm_names =>
               owa_sylk.owaSylkArray( 'DATABASE_NAME'),
       p_parm_values =>
                 owa_sylk.owaSylkArray( lv_target ),
   p_show_grid => 'NO' ,
        p_user_heading => 'Error REPORT Of '||lv_target||' for last 3 months');

    utl_file.fclose( output );
end;

DB init parameters:
       This script will give init.ora parameters for DB. Change "oemrep" with your dbname.

declare
    output utl_file.file_type;
    lv_target Varchar2(30) := 'oemrep';
    lv_file_name varchar2(30) ;
begin

    lv_file_name := lv_target||'_db_param.slk';

    output := utl_file.fopen( 'UTL_FILE_DIR', lv_file_name, 'w', 32000 );
    owa_sylk.show(
        p_file => output,
        p_query => 'select Name,Value,isdefault  '||
   '  from  MGMT$DB_INIT_PARAMS '||
   'where target_name=:HOSTNAME ',
          p_parm_names =>
               owa_sylk.owaSylkArray( 'HOSTNAME'),
       p_parm_values =>
                 owa_sylk.owaSylkArray( lv_target ),
        p_show_grid => 'NO' ,
        p_user_heading => 'DB parameter info of '||lv_target||' as on '||sysdate);
    utl_file.fclose( output );
end;



Visitors Count

convert this post to pdf.

Posted by Borndba on April 4, 2009 at 12:27 am under Oracle, Oracle Grid Control.
Tags: ,
Comments Off.

Ref Cursor Vs Plsql table

When you want to return a table in a function, Ref cursor is preferred compared to Plsql table.
If you return a ref cursor, result will be send to the end user in chunk instead of sending full result set. So to the end user, it will appear to be faster.
Additionally, if I was to return an array -- I would have to fetch all of the rows, allocate
storage in plsql for them, copy the data there and then send that data back over the network in one
big chunk where the client would have to allocate storage to hold the whole thing in memory.  With
a ref cursor -- i send back a pointer (don't have the overhead of allocating the storage in plsql
and copying all of the data into it).  I send rows in chunks -- not all at once (10 rows at a time
by default -- you control the size).  I don't have to allocate memory to hold the entire thing in
the client -- just a slice of it.

A ref cursor is infintely more scalable then sending a data structure back and forth for these
reasons.



Visitors Count


convert this post to pdf.

Posted by Borndba on April 4, 2009 at 12:26 am under Oracle, Oracle Administration.
Tags: ,
Comments Off.

TDE

Transparent Data Encryption, this a new feature introduced in 10gR2 in encrypting the sensitive column. I read something interesting on it's impact on performance and storage. Thought let me document it.

Overhead of encrypting or decrypting will be 5%. If a encrypted column is indexed, in the index the value is stored as cipher text. On storage front, the impact is huge, for every encrypted column there is additional overhead of 20bytes due to integrity check. TDE will pad encrypted value to 16 bytes also. Incase if the non-encrypted column requires 10 bytes, when you encrypt it will additionally take 6 bytes. If salt is specified when defining the column, it will additionally consume 16 bytes. 

So altogether if a column is encrypted it will require 33 and 48bytes of additional storage per rows.

So, to get encryption enabled, need to sacrifies a lot of performance and storage front.



Visitors Count





Visitors Count


convert this post to pdf.

Posted by Borndba on April 4, 2009 at 12:26 am under Oracle, Oracle Internal.
Tags: ,
Comments Off.

_Spin_Count

Earlier to 9iR2, if you change the _spin_count it will affect the spinning of all the latches. This affects the CPU resource in particular. From 9iR2, you can assign a latch to classes, and each class can have different _spin_count. Let us assume that library cache latch is having high SLEEPS and if you like to tune only this latch you can assign library cache latch to a class. There are totally 8 classes. The X$KSLLCLASS (Kernel service lock latch class) view contains information about these classes.

sys@10.2.0.2.0> select indx,spin,yield,waittime from x$ksllclass;

      INDX       SPIN      YIELD   WAITTIME
---------- ---------- ---------- ----------
         0      16000          0          1
         1      16000          0          1
         2      16000          0          1
         3      16000          0          1
         4      16000          0          1
         5      16000          0          1
         6      16000          0          1
         7      16000          0          1

8 rows selected.

From above output, note INDX=1 and the corresponding spin. We will be assigning this class to library cache and change the spin count to 20000 from 16000.

sys@10.2.0.2.0> select latch#,name from v$latchname where name='library cache';

    LATCH# NAME
---------- --------------------------------------------------
       214 library cache

Latch number of "library cache" is 214.

sys@10.2.0.2.0> alter system set "_latch_class_1"=20000 scope=spfile;

System altered.

Assigning class_1 with 20000.

sys@10.2.0.2.0> alter system set "_latch_classes"="214:1" scope=spfile;

System altered.

Assigning the latch to class 1.

sys@10.2.0.2.0>

sys@10.2.0.2.0> shutdown abort
ORACLE instance shut down.
sys@10.2.0.2.0> startup
ORACLE instance started.

Total System Global Area   71303168 bytes
Fixed Size                  1287836 bytes
Variable Size              62916964 bytes
Database Buffers            4194304 bytes
Redo Buffers                2904064 bytes
Database mounted.
Database opened.

Bouncing the instance to make the changes effective.

sys@10.2.0.2.0> select indx,spin,yield,waittime from x$ksllclass;

      INDX       SPIN      YIELD   WAITTIME
---------- ---------- ---------- ----------
         0      16000          0          1
         1      20000          0          1
         2      16000          0          1
         3      16000          0          1
         4      16000          0          1
         5      16000          0          1
         6      16000          0          1
         7      16000          0          1

8 rows selected.

Please note the INDX=1, now the spin count=20000

sys@10.2.0.2.0> select a.kslldnam, b.kslltnum, b.class_ksllt
  2  from   x$kslld a, x$ksllt b
  3  where  a.kslldadr = b.addr
  4  and    b.class_ksllt > 0;

KSLLDNAM                                             KSLLTNUM CLASS_KSLLT
-------------------------------------------------- ---------- -----------
process allocation                                          3           2
library cache                                             214           1

The above query gives the output of to which class number the latch is assigned.



Visitors Count


convert this post to pdf.

Posted by Borndba on April 4, 2009 at 12:25 am under Oracle, Oracle Internal.
Tags: ,
Comments Off.

Freelists Management

Freelists is list of blocks which can be used by segment on shortage of space. When delete occurs and freespace within the block goes below pctused, this block will be put in freelist. The block which is added last will be released first. Like B3 is added to freelist, then after a while B1 gets added then the chain looks like.

FL: B3
FL: B1 ==> B3.
On shortage of space B1 will be released before B3.

Type of Freelists:
Txfl  ==>  Transaction Freelist
Prfl  ==>  Process Freelist
Sgfl  ==>   Segment Freelist
Msfl  ==>  Master Freelist
Infl  ==> Instance Freelist

Txfl:
Each segment will have in minimum 16 Txfl, it grows as needed. During a transaction if space is required then oracle will first look into the txfl. At the same time if it wants to release the space it will give it to txfl.
Prfl:
Freelist allocated to a process. A process will not scan prfl allocated to other process.
Sgfl:
Synonym for Prfl.
Msfl:
It is introduced in later part of V6. It is preallocated Prfl which all processes can access known as Master Freeist.
Infl:
No idea on this.

Please note the algorithm when a transaction faces space issue,
• Search the space in it’s own Txfl. If it exist it will use otherwise
• Search the space in Prfl, it it doesn’t find then
• Search the space in Msfl. If it finds one it will copy the chunk to Prfl and use it otherwise
• Search the commited Txfl. If it finds one it will copy the chunk to Msfl from there it will be copied to Prfl. If if doesn’t find one
• Checks whether it can bump the high water mark level. It will bump 5 blocks at a time or defined by _bump_high_water_mark parameter. The added values will be passed to Prfl and used. If not
• Goes to fet$ and allocate a segment. Even if there is no space
• Errors out with unable to extent tablespace error.

Also note index block will be put to freelist only if the block is completely empty.
Event 10044 is used for tracing Freelist Undo operation and event 10045 for tracing freelist update operation -ktsrsp,ktsunl



Visitors Count


convert this post to pdf.

Posted by Borndba on April 4, 2009 at 12:24 am under Oracle, Oracle Internal.
Tags: ,
Comments Off.

Type of Events

Type of Event:
There are 4 types of events.
1. Immediate Dump Events
2. Error Stack Event
3. Change Behavior Event
4. Process Event

Immediate Dump Events:
This event generate trace file immediately in the udump area. These parameters cannot be issued in Parameter file. Some of the event involved are Trace_Buffer_On/Off,Hanganalyze,Latches,Processstate,SystemState,Instantiationstate,Refresh_Os_Stats,Crossic,ContextArea,Headdump,shared_server_state,Drop_Segments library_cache,full_dumps, granulelist, dump_all_comp_granule_addrs, buffers.
Error Stack Events:
If you need to capture the processes throwing out ORA error, you can use this event. This is very useful in diagnosing 4031, 942, 4020, 1555 etc., errors.
Change Behavior Event:
You need to be very careful before setting this event. This event can change the behaviors of oracle kernel and may render your db unsupported if used without approval of oracle support. There are n-number of events fails under this category. These events _generally_ doesn’t have levels associated with it. To name few are 10512 (disabling rollback shrinking by smon), 10170 changes the costing algorithm etc.,
Process Trace Events:
This is less/no harm events. This event is helpful in diagnosing behaviors of the process. Some of the events are 10046, 10053, 10032, 10033 etc.,

If you set an event, event information is stored in the PGA. Since it is stored in the PGA which is private to a session, you can’t find out event set in the other sessions. In case if you want to find out the events set in the current session, you can use below block.

set serveroutput on
declare
  event_level number;
 begin
  for i in 10000..10999 loop
     sys.dbms_system.read_ev(i,event_level);
     if (event_level > 0) then
        dbms_output.put_line('Event '||to_char(i)||' set at level '||
                             to_char(event_level));
     end if;
  end loop;
 end;
/



Visitors Count


convert this post to pdf.

Posted by Borndba on April 4, 2009 at 12:21 am under Oracle, Oracle Internal.
Tags: ,
Comments Off.

ASSM

Pctused,freelist and freelist groups has become obsolete with introduction of ASSM.
The Pctfree is still valid because it is not a space management tool. It still used to tackle row migration.
There are 6 different freeness statuses when a tablespace is declared with ASSM.
0 = unformatted, 1 = logically full, 2 = 0-25% free, 3 = 25-50% free, 4 = 50%-75% free, 5= 75-100% free.
Theoretically a block is considered 90% full (FS=2), if the free space is 0-25%. However if the pctfree is declared more than 10% and freeness falls below pctfree, that block is considered full. This is irrespective of how much the block is full. You can track the behaviors in Event 10612 and Event 10613.



Visitors Count

class="statcounter">
href=”http://www.statcounter.com/blogger/”
target=”_blank”> src="http://c.statcounter.com/4628332/0/06d2759c/0/"
alt="blogspot visitor" >


convert this post to pdf.

Posted by Borndba on April 4, 2009 at 12:20 am under Oracle, Oracle Administration.
Tags: ,
Comments Off.

spliting export files using unix command

Recently we had a scenario, where we need to migrate a oracle 7 db to oracle 9i. We have decided to go ahead with exp/imp method. Size of the Oracle 7 is 8-10gb. Space available in this box is 2.5gb. So we can’t take a complete export, as the size of the dump file may go beyond. Even the compress export using mknod is crossing 2.5 gb. Also there is no filesize/volsize option in oracle7 export utility.
We have did something like this.

 cd /tmp/data
 rm exp.dmp
 mknod exp.dmp p       # mkfifo on certain Unix flavours
 split -b1024m < /tmp/data/exp.dmp &
 exp scott/tiger file=/tmp/data/exp.dmp

Export will create a file of 1024m each, which we have to transfer to oracle9i box and do the import like,

 cd /tmp/data
 rm exp.dmp
 mknod exp.dmp p
 cat xaa xab xac xad > /tmp/data/exp.dmp &
 imp scott/tiger file=/tmp/data/exp.dmp commit=y tables=tableX

From 8, we can use filesize to generate multiple files of specific size. But here we may have to give in advance the number of file names. But you can use the below trick.
“file=xyz%u.dmp”



Visitors Count


convert this post to pdf.

Posted by Borndba on April 4, 2009 at 12:18 am under Oracle, Oracle Backup Recovery.
Tags: ,
Comments Off.

Only “ORDER BY” to sort

If you want to retreive rows in some order use “ORDER BY”. Though “GROUP BY”, forcing index might seem to return in sorted order, but it is not often.
“GROUP BY” doesn’t do character sorting, it actually does Binary Sort. There are many factors like partitioning, table organisation, optimizer_mode, DOP, indexes etc., affects the order by rows retrieved.
I remember seeing a note in metalink, where in future, index may not be stored in sorted order. This may not seems to be likely. However, the rows retrieved using index scan may not be in sorted order. Atleast with current Index full scan and Range scan it is not true.

satheeshb@10.2.0.2.0> drop table t;

Table dropped.

satheeshb@10.2.0.2.0> create table t ( pk1 int,pk2 int, nk1 int not null,
nk2 int not null, primary key (pk1,pk2));

Table created.

satheeshb@10.2.0.2.0> create index tx on t(pk1,nk1,pk2,nk2);

Index created.

satheeshb@10.2.0.2.0> insert into t values (1,1,2,2);

1 row created.

satheeshb@10.2.0.2.0> insert into t values (2,1,1,1);

1 row created.

satheeshb@10.2.0.2.0> analyze table t compute statistics
  2  ;

Table analyzed.

satheeshb@10.2.0.2.0>  set autotrace on explain
satheeshb@10.2.0.2.0> select nk1, nk2, pk1, pk2, count(*) a_count
  2  from t
  3  group by nk1,nk2,pk1,pk2;

       NK1        NK2        PK1        PK2    A_COUNT
---------- ---------- ---------- ---------- ----------
         2          2          1          1          1
         1          1          2          1          1

Execution Plan
----------------------------------------------------------
Plan hash value: 2968033836

-----------------------------------------------------------------------------
| Id  | Operation            | Name | Rows  | Bytes | Cost (%CPU)| Time     |
-----------------------------------------------------------------------------
|   0 | SELECT STATEMENT     |      |     2 |    16 |     1   (0)| 00:00:01 |
|   1 |  SORT GROUP BY NOSORT|      |     2 |    16 |     1   (0)| 00:00:01 |
|   2 |   INDEX FULL SCAN    | TX   |     2 |    16 |     1   (0)| 00:00:01 |
-----------------------------------------------------------------------------


So if you want the rows to be retrieve, the only way is actually to use “ORDER BY”. You have to bear the cost of sorting anyway.



Visitors Count


convert this post to pdf.

Posted by Borndba on April 4, 2009 at 12:17 am under Oracle, Oracle Performance.
Tags: ,
Comments Off.

RFS/MRP applying to Standby db

If you are using Standby redo log files, RFS is the process which receives the change information from primary and apply to standby redolog files.

Size of standby redo log should be same that of primary redolog. RFS gets information only from LGWR of primary. Standby redolog files works only when the transmitter is defined as LGWR.

MRP is the process which will apply the changes from standby redolog files to standby database.

If your not using standby redo log files, RFS is the process which will create the archivelog files and MRP will apply to standby.

Addendum 20th oct:
There is one question for which still i am trying find answer is what is the purpose of LGWR in physical standby. Since RFS will be receiving the files and MRP will be applying file. Need to know

convert this post to pdf.

Posted by Borndba on April 4, 2009 at 12:16 am under Oracle, Oracle Dataguard/RAC.
Tags: ,
Comments Off.

Excluding few tables while exporting

Excluding few tables while exporting or importing can be done by changing definition of export related dictionary tables. In 10g, expdp/impdp has got the feature to do so. Changing the dictionary definition is not supported by oracle.

There will be a view called exu10tab in catexp.sql. This sql file will be available in $ORACLE_HOME/rdbms/admin folder. Search for the view name “exu10tab”. The definition of view will be like below,

CREATE OR REPLACE VIEW exu10tab AS
SELECT *
FROM sys.exu10tabs t$
WHERE t$.secondaryobj = 0 ;

If you want to exclude Table “T” from the export add a where condition like below,

CREATE OR REPLACE VIEW exu10tab AS
SELECT *
FROM sys.exu10tabs t$
WHERE t$.secondaryobj = 0
and NAME NOT IN (‘T’);

Once export is completed, revert make to older setting.

If you have in pre 10g version, you have similar table like exu9tab or exu8tab.



Visitors Count





Visitors Count


convert this post to pdf.

Posted by Borndba on April 4, 2009 at 12:15 am under Oracle, Oracle Internal.
Tags: ,
Comments Off.

Deletefile Procedure in Dbms_Restore_Backup.

There is an unsupported procedure “Deletefile” in Dbms_Restore_Backup. This procedure can delete the OS files. Make sure you grant this package to right users. This will be one more security violation if used improperly.

c:scripts>dir d:oracleproduct10.2.0adminaryaaudump1.trc
 Volume in drive D has no label.
 Volume Serial Number is 8C01-73AF

 Directory of d:oracleproduct10.2.0adminaryaaudump

10/13/2006  10:29 AM            11,574 1.trc
               1 File(s)         11,574 bytes
               0 Dir(s)   4,653,568,000 bytes free

Then from sqlplus

sys@10.2.0.2.0> Begin
  2  dbms_backup_restore.deletefile('D:oracleproduct10.2.0
adminARYAAudump1.trc');
  3  end;
  4  /

PL/SQL procedure successfully completed.

C:Documents and SettingsAryaa>dir D:oracleproduct10.2.0adminARYAAudump1.trc
 Volume in drive D has no label.
 Volume Serial Number is 8C01-73AF

 Directory of D:oracleproduct10.2.0adminARYAAudump

File Not Found



Visitors Count


convert this post to pdf.

Posted by Borndba on April 4, 2009 at 12:15 am under Oracle, Oracle Backup Recovery.
Tags: ,
Comments Off.

Dbms_Stats.Set_Param

There is an unsupported way to trace gathering statistics using dbms_stats.

Usage will be,

satheeshb@10.2.0.2.0> exec dbms_stats.set_param('trace','3166');

PL/SQL procedure successfully completed.

satheeshb@10.2.0.2.0> exec dbms_stats.gather_table_stats(user,'T3',
CASCADE=>TRUE);

PL/SQL procedure successfully completed.

This will generate a trace file in udump area. This trace file will clearly shows what happens behind the scene during dbms_stats.

Various levels of set_param,

1 = use dbms_output.put_line instead of writing into trace file
2 = enable dbms_stat trace only at session level
4 = trace table stats
8 = trace index stats
16 = trace column stats
32 = trace auto stats
64 = trace scaling
128 = dump backtrace on error
256 = dubious stats detection
512 = auto stats job
1024 = parallel execution tracing
2048 = print query before execution
4096 = partition prune tracing
8192 = trace stat differences

Therefore, TRACE 3166 = 2048 + 1024 + 64 + 16 + 8 + 4 + 2.



Visitors Count


convert this post to pdf.

Posted by Borndba on April 4, 2009 at 12:14 am under Oracle, Oracle Performance.
Tags: ,
Comments Off.

Archivelog Nologging

There is a shuttle difference when Nologging is used with Archivelog database. Nologging should be given in Table level NOT in Query level. This is to tell oracle that you are serious in setting the Nologging option.

Database is in Archivelog Mode. Table "T" in Logging mode. 

satheeshb@10.2.0.2.0> insert /*+append*/ into t select * from t3;

4772728 rows created.

Statistics
----------------------------------------------------------
       3726  recursive calls
      10150  db block gets
       8933  consistent gets
       7729  physical reads
   64240476  redo size
        658  bytes sent via SQL*Net to client
        573  bytes received via SQL*Net from client
          4  SQL*Net roundtrips to/from client
         11  sorts (memory)
          0  sorts (disk)
    4772728  rows processed

Note: That quite a lot of redo generated.


satheeshb@10.2.0.2.0> commit;

Commit complete.

satheeshb@10.2.0.2.0> truncate table t;

Table truncated.

satheeshb@10.2.0.2.0> insert /*+append*/ into t nologging select * from t3;

4772728 rows created.

Statistics
----------------------------------------------------------
       4606  recursive calls
      10152  db block gets
       9078  consistent gets
       7745  physical reads
   64289508  redo size
        663  bytes sent via SQL*Net to client
        583  bytes received via SQL*Net from client
          4  SQL*Net roundtrips to/from client
         37  sorts (memory)
          0  sorts (disk)
    4772728  rows processed


Note: Though the nologging is given in query level there is no impact
on redo generation. This is because the db is in Archivelog mode.
If the db was running in NoArchivelog mode, the above insert
statement would have generated much lesser redo.

satheeshb@10.2.0.2.0> commit;

Commit complete.

satheeshb@10.2.0.2.0> truncate table t;

Table truncated.


Now let us convert the table “T” to Nologging. This is to ensure that some responsible person with “ALTER” privillege can take the decision of enabling Nologging in Archivelog DB.

satheeshb@10.2.0.2.0> alter table t nologging;

Table altered.

satheeshb@10.2.0.2.0>  insert /*+append*/ into t select * from t3;

4772728 rows created.

Statistics
----------------------------------------------------------
       4201  recursive calls
      10155  db block gets
       8991  consistent gets
       7729  physical reads
     241244  redo size
        662  bytes sent via SQL*Net to client
        574  bytes received via SQL*Net from client
          4  SQL*Net roundtrips to/from client
         21  sorts (memory)
          0  sorts (disk)
    4772728  rows processed


Note: There is huge difference in the “Redo size” generation. This extra check is required, as Nologging in Archivelog will invalidate the backup.



Visitors Count


convert this post to pdf.

Posted by Borndba on April 4, 2009 at 12:13 am under Oracle, Oracle Performance.
Tags: ,
Comments Off.

Redolog Switches in Standby

When there is switches in Primary will there be switches in Standby also? This question was itching me for sometime. Not able to get these detail anywhere. Tried asking few expert in DG. But didn’t get any convincing answer. Luckily got the answer to this question in corner of Oracle Doc 10g. “Physical standby db doesn’t have redolog associated with it”.

It means changes will be applied to physical standby datafiles directly from
archived log files or standby redolog files. So no redo generation in managed recovery stage. But when the standby is opened in read-only mode, there might be redo generation which will get into redolog. These redo may be from dictionary changes ( Not sure delayed block cleanout come into play in standby). Like oracle keep increasing the SCN even in read-only or there could be other internal reasons.

But redolog is required for logical standby as the db will be opened for read/write.

Before any changes getting applied to standby from standby redo log files, it has to be archived. However if you have enabled real-time apply the changes will get applied to datafiles from standby redolog file itself and oracle doesn’t wait for standby redo log to get archived.

To enabled real-time apply,

in physical standby,
ALTER DATABASE RECOVER MANAGED STANDBY DATABASE USING CURRENT;

in logical standby,
ALTER DATABASE START LOGICAL STANDBY APPLY IMMEDIATE;

If you want to know whether real-time apply is enabled query recovery_mode.V$ARCHIVE_DEST_STATUS.

But need to check how real-time apply will work. Whether real time apply is 10g feature?

convert this post to pdf.

Posted by Borndba on April 4, 2009 at 12:13 am under Oracle, Oracle Administration.
Tags: ,
Comments Off.

Shrink in 10g

In 10g, oracle allows us to bring the HWM down. Prerequest; table should be in ASSM and compatible should be =>10.

I am using Dbms_Space package to show the effect of Shrink command. Please refer to dbms_space.sql script below.

During shrink there are 2 phases.
1. Compact the space. This involves moving all the rows to blocks in beginning of the segments. This will be done using insert/delete. These insert/deletes will be done in several small unit transactions. So, there will be locks in rows/blocks during this phase, but it will be short lived and won’t affect the concurrent transactions. Also please note any dml trigger will not get fired by this insert/delete operations as it happens internally.

2. Bringing the HWM down. This requires exculusive locks. This phase affects the availability. But this will be for very short interval. As it requires basically updating some records in dictionary.


--dbms_space.sql

declare
v_unformatted_blocks number;
v_unformatted_bytes number;
v_fs1_blocks number;
v_fs1_bytes number;
v_fs2_blocks number;
v_fs2_bytes number;
v_fs3_blocks number;
v_fs3_bytes number;
v_fs4_blocks number;
v_fs4_bytes number;
v_full_blocks number;
v_full_bytes number;
begin
dbms_space.space_usage ('&1', '&2', '&3', v_unformatted_blocks,
v_unformatted_bytes, v_fs1_blocks, v_fs1_bytes, v_fs2_blocks, v_fs2_bytes,
v_fs3_blocks, v_fs3_bytes, v_fs4_blocks, v_fs4_bytes, v_full_blocks, v_full_bytes);
         dbms_output.put_line('FS1 Blocks       = '||v_fs1_blocks);
         dbms_output.put_line('FS2 Blocks       = '||v_fs2_blocks);
         dbms_output.put_line('FS3 Blocks       = '||v_fs3_blocks);
         dbms_output.put_line('FS4 Blocks       = '||v_fs4_blocks);
         dbms_output.put_line('Full Blocks       = '||v_full_blocks);
end;
/

satheeshb@10.2.0.2.0> @dbms_space.sql  "SATHEESHB" "T3" "TABLE"
FS1 Blocks       = 0
FS2 Blocks       = 45
FS3 Blocks       = 45
FS4 Blocks       = 295
Full Blocks       = 7739
PL/SQL procedure successfully completed.
Note:
FS1 => Blocks which are 0-25% free space
Fs2 => Blocks which are 25-50% free space
Fs3 => Blocks which are 50-75% free space
Fs4 => Blocks which are 75-99% free space
Full Blocks => Blocks which are 100% free space

satheeshb@10.2.0.2.0> alter table t3 shrink space compact;
alter table t3 shrink space compact
*
ERROR at line 1:
ORA-10636: ROW MOVEMENT is not enabled

Note: You need to enable row movement for the Shrink command to work. 

satheeshb@10.2.0.2.0> alter table t3 enable row movement;
Table altered.

satheeshb@10.2.0.2.0>  alter table t3 shrink space compact;
Table altered.
Note: The above statement is phase 1 of shrink operation. These moves the data to beginning of the segment using simple insert/delete. 

satheeshb@10.2.0.2.0> @dbms_space  "SATHEESHB" "T3" "TABLE"
FS1 Blocks       = 2
FS2 Blocks       = 0
FS3 Blocks       = 0
FS4 Blocks       = 402
Full Blocks       = 7720
PL/SQL procedure successfully completed.

satheeshb@10.2.0.2.0> alter table t3 shrink space;

Table altered.

Note: This is the Second phase of shrink operation. This involves exclusive lock. Only this stage affects the availablity. This will be quick phase, as it as to adjust some dictionary information.
 

satheeshb@10.2.0.2.0> @dbms_space  "SATHEESHB" "T3" "TABLE"
FS1 Blocks       = 2
FS2 Blocks       = 0
FS3 Blocks       = 0
FS4 Blocks       = 0
Full Blocks       = 7720
PL/SQL procedure successfully completed.



Visitors Count


convert this post to pdf.

Posted by Borndba on April 4, 2009 at 12:12 am under Oracle, Oracle Administration.
Tags: ,
Comments Off.

SYS_OP_LBID – Index Rebuild

Index rebuild seems to make sense in some extreme condition. There were many heated discussion on index rebuild in oracle community. Some say height should be considered before rebuild , some other says blevel should be considered.
The function “sys_op_lbid” gets number of rows in each leaf block of index. By seeing how the rows are distributed across the leaf blocks, one can judge whether index needs rebuilding/coalesce or not.

I am still not convinced that rebuilding index is ever required. As there will be spike in redo due to index-splic block. LBID in SYS_OP_LBID should be “leaf block id”. I will test this when i have free time to burn.



Visitors Count


convert this post to pdf.

Posted by Borndba on April 4, 2009 at 12:11 am under Oracle, Oracle Administration.
Tags: ,
Comments Off.

Plsql_Optimize_Level (POL)

If you set Plsql_Optimize_Level =2, oracle can rewrite your code to give best output. If you want your package to have the advantage of POL, define it while compiling itself. Since oracle will reqwrite the code during compilation stage and not during execution stage. I have noticed some package taking long time to compile when set to POL=2. So be aware of this little trap.


satheeshb@10.2.0.2.0> show parameter plsql_optimize_level

NAME                                 TYPE        VALUE
------------------------------------ ----------- ------------------------------
plsql_optimize_level                 integer     2

satheeshb@10.2.0.2.0> declare
  2    lv number;
  3  begin
  4    lv:=0;
  5     for i in (select rownum r1 from t3) loop
  6          i.r1 := i.r1;
  7          lv := lv+1;
  8          exit when lv=200;
  9     end loop;
 10  end;
 11  /

PL/SQL procedure successfully completed.

satheeshb@10.2.0.2.0> select rows_processed,fetches from v$sql
  2* where lower(sql_text)='select rownum r1 from t3';

ROWS_PROCESSED    FETCHES
-------------- ----------
           200          2


Note the number of fetches above.

satheeshb@10.2.0.2.0> alter system set plsql_optimize_level=1 scope=memory;

System altered.

satheeshb@10.2.0.2.0> declare
  2    lv number;
  3  begin
  4    lv:=0;
  5     for i in (select no r1 from t3) loop
  6          i.r1 := i.r1;
  7          lv := lv+1;
  8          exit when lv=200;
  9     end loop;
 10  end;
 11  /

PL/SQL procedure successfully completed.

satheeshb@10.2.0.2.0> select rows_processed,fetches from v$sql
  2   where lower(sql_text)='select no r1 from t3';

ROWS_PROCESSED    FETCHES
-------------- ----------
           200        200

satheeshb@10.2.0.2.0> 

See the spike in number of fetches when the optimize level is changed.


When “Plsql_optimizer_level=2″ the number of fetch is TWO, however for Plsql_Optimizer_Level=1 the fetch is 200. One interesting point to note here is per fetch 100 rows. Not sure why is that magic number Hundred..



Visitors Count


convert this post to pdf.

Posted by Borndba on April 4, 2009 at 12:09 am under Oracle, Oracle Administration.
Tags: ,
Comments Off.

Fixed_Date – Dangerous feature

If the sysdate of OS is by mistake is not correct, can lead to lot of confusion in database involving financial transaction. One way to prevent that is using Fixed_date parameter.

satheeshb@10.2.0.2.0> alter session set nls_date_format='dd/mon/yyyy hh24:mi:ss';

Session altered.

satheeshb@10.2.0.2.0> select sysdate from dual;

SYSDATE
--------------------
07/oct/2006 04:02:15

satheeshb@10.2.0.2.0> alter system set fixed_date='2001-11-01' scope=memory;

System altered.

satheeshb@10.2.0.2.0> alter session set nls_date_format='dd/mon/yyyy hh24:mi:ss';

Session altered.

satheeshb@10.2.0.2.0> select sysdate from dual;

SYSDATE
--------------------
01/nov/2001 00:00:00

satheeshb@10.2.0.2.0> alter session set  fixed_date='2001-11-01' scope=memory;
alter session set  fixed_date='2001-11-01' scope=memory
                   *
ERROR at line 1:
ORA-02096: specified initialization parameter is not modifiable with this
option


This rises lot of questions regarding security. So never give “ALTER SYSTEM” privs to non-dba users. However alter session will not change this parameter.
Neverever give “ALTER SYSTEM” privs to developer account. There are many other security violation involving “ALTER SYSTEM’.



Visitors Count

class="statcounter">
href=”http://www.statcounter.com/blogger/”
target=”_blank”> src="http://c.statcounter.com/4628332/0/06d2759c/0/"
alt="blogspot visitor" >


convert this post to pdf.

Posted by Borndba on April 4, 2009 at 12:08 am under Oracle, Oracle Administration.
Tags: ,
Comments Off.

Only used blocks in Transaction Freelist

Freelist will not have unused blocks.

Only used blocks, which falls below pctused will get into Transaction freelist. If oracle not able find the blocks below hwm or freelist, it will bump the HWM level by 1 block for 5 blocks and there after by greater of 5 blocks or “_bump_highwater_mark_count” blocks (which defaults to 0) times the number of process free lists plus 1 (for the master free list), up to the number of blocks remaining in the extent.

Below is a small demonstration of only used blocks getting into Transaction Freelist. You need to use ASSM, as MSSM doesnt have Freelists,Freelist groups and PctUsed.


satheeshb@10.2.0.2.0> drop table t purge;

Table dropped.

Elapsed: 00:00:01.10
satheeshb@10.2.0.2.0> create table t tablespace system as select * from all_objects;

Table created.

Elapsed: 00:00:05.18
satheeshb@10.2.0.2.0> analyze table t compute statistics;

Table analyzed.

Elapsed: 00:00:01.33
satheeshb@10.2.0.2.0> select num_freelist_blocks from user_tables where table_name='T';

NUM_FREELIST_BLOCKS
-------------------
                  0

Elapsed: 00:00:00.08
satheeshb@10.2.0.2.0> delete t ;

49302 rows deleted.

Elapsed: 00:00:16.78
satheeshb@10.2.0.2.0> analyze table t compute statistics;

Table analyzed.

Elapsed: 00:00:01.39
satheeshb@10.2.0.2.0> select num_freelist_blocks from user_tables where table_name='T';

NUM_FREELIST_BLOCKS
-------------------
                677

Elapsed: 00:00:00.02


There are 3 kind of freelists in oracle, Master/Process/Transactions Freelist. The freelist shows in Num_Freelists_blocks is “Transaction Freelists”. Transaction Freelist is the one which you define in Create/Alter table command. Unused blocks will not get into Transaction Freelist, however i believe they get into Master/Process Freelist. Need to test the uses of Master/Process freelist.



Visitors Count


convert this post to pdf.

Posted by Borndba on April 4, 2009 at 12:07 am under Oracle, Oracle Administration.
Tags: ,
Comments Off.

Extent Allocation of a object multiple datafiles of tablespace.

If a tablespace is having more than one datafile and extend of an object will be allocated in round robin fashion to each of the datafiles. However there are various factors which will affect this round robin fashion like how other objects in this tablespace grows, autoextend on or off of a datafiles, any space getting available in the existing datafiles etc.,

satheeshb@10.2.0.2.0> create tablespace s datafile 'c:1.dbf' size 1m,
  2  'c:2.dbf' size 1m,
  3  'c:3.dbf' size 1m,
  4  'c:4.dbf' size 1m,
  5  'c:5.dbf' size 1m
  6* extent management local uniform size 64k;

Tablespace created.

satheeshb@10.2.0.2.0> select file_id from dba_data_files where tablespace_name='S';

   FILE_ID
----------
         5
         6
         7
         8
         9

satheeshb@10.2.0.2.0> drop table s1;

Table dropped.

satheeshb@10.2.0.2.0> create table s1 ( no number )
  2  tablespace s
  3* storage (initial 1m );

Table created.

satheeshb@10.2.0.2.0> select file_id,extent_id from dba_extents
  2* where owner=user and segment_name='S1' order by extent_id
satheeshb@10.2.0.2.0> /

   FILE_ID  EXTENT_ID
---------- ----------
         7          0
         8          1
         9          2
         5          3
         6          4
         7          5
         8          6
         9          7
         5          8
         6          9
         7         10
         8         11
         9         12
         5         13
         6         14
         7         15

16 rows selected.

satheeshb@10.2.0.2.0> drop tablespace s including contents and datafiles;

Tablespace dropped.

     The same could be true for DMT and LMT with uniform extent. When tried with LMT with autoallocate, it gave a different behaviour. It will be based on extent size. That is once the 64k extent is over and followed by 128k extents, same patter will be followed for 128k extents as it was followed in 64k. But again number factors to change this behaviour.

satheeshb@10.2.0.2.0> select file_id,extent_id,bytes from dba_extents
  2  where owner=user and segment_name='S1' order by extent_id
  3  /

   FILE_ID  EXTENT_ID      BYTES
---------- ---------- ----------
         7          0      65536
         7          1      65536
         7          2      65536
         7          3      65536
         7          4      65536
         7          5      65536
         7          6      65536
         7          7      65536
         7          8      65536
         7          9      65536
         7         10      65536
         7         11      65536
         7         12      65536
         7         13      65536
         7         14      65536
         8         15      65536

16 rows selected.



Visitors Count


convert this post to pdf.

Posted by Borndba on April 4, 2009 at 12:06 am under Oracle, Oracle Administration.
Tags: ,
Comments Off.

checkpoint in ddl command

The checkpoing command in Alter table drop column will be used If a instance crashes while dropping a column in big table.

satheeshb@10.2.0.2.0> alter table s1 drop column id checkpoint 10;

Table altered.

You are basically checkpointing every 10 rows. So that it gets to the datafiles. One thing which i am not clear is whether it is object level checkpoint or instance level checkpoint. It may not be object level checkpoint, since i guess it is introduced in 10g.

Alternatively, if you want to restart the drop column command after restart you can use,

satheeshb@10.2.0.2.0> alter table s1 drop columns continue;

Table altered.

Note the columnS. If you give column, oracle will try to drop the column “continue”


Addendum on 8th oct.
The checkpoint here is not a real checkpoint. It is something like commit. It will go to redolog files and may or maynot got datafiles.



Visitors Count


convert this post to pdf.

Posted by Borndba on April 4, 2009 at 12:06 am under Oracle, Oracle Administration.
Tags: ,
Comments Off.

auto-increment using sys_guid()

Like MS-Sql if you want to autoincrement a column you can use sys_guid from 9iR2. But this will not be in number instead it will be in raw.

satheeshb@10.2.0.2.0> drop table s1;

Table dropped.

satheeshb@10.2.0.2.0> create table s1 ( id raw(6) default hextoraw(substr(sys_guid(),1,12)) primary key,
  2  Descrip varchar2(10));

Table created.

satheeshb@10.2.0.2.0> insert into s1(Descrip) values ('first row');

1 row created.

satheeshb@10.2.0.2.0> insert into s1(Descrip) values ('second row');

1 row created.

satheeshb@10.2.0.2.0> select * from s1;

ID                  DESCRIP
------------        ----------
8628D8F81FD2        first row
6D695F7F7547        second row

satheeshb@10.2.0.2.0> commit;

Commit complete.



Visitors Count


convert this post to pdf.

Posted by Borndba on April 4, 2009 at 12:04 am under Oracle, Oracle Administration.
Tags: ,
Comments Off.

Generating plan without executing

Generating explain plan using autotrace or dbms_xplain may not be correct when bind variable peeking comes to play. There is an interesting way to get the correct plan without executing the statement. Please see the below command.

satheeshb@10.2.0.2.0>  declare
  2    num   number := 0;
  3    --
  4    cursor c1 is
  5    select  * from t where n = num;
  6    begin
  7      dbms_session.session_trace_enable(true,false);
  8      open c1;
  9      close c1;
 10
 11    end;
 12    /

PL/SQL procedure successfully completed.

From tkprof output, you get the correct plan even without executing the query.

SELECT  *
FROM
 T WHERE N = :B1 

call     count       cpu    elapsed       disk      query    current        rows
------- ------  -------- ---------- ---------- ---------- ----------  ----------
Parse        1      0.01       0.05          0          0          0           0
Execute      1      0.00       0.00          0          0          0           0
Fetch        0      0.00       0.00          0          0          0           0
------- ------  -------- ---------- ---------- ---------- ----------  ----------
total        2      0.01       0.05          0          0          0           0

Misses in library cache during parse: 1
Optimizer mode: ALL_ROWS
Parsing user id: 56     (recursive depth: 1)

Rows     Row Source Operation
-------  ---------------------------------------------------
      0  TABLE ACCESS FULL T (cr=0 pr=0 pw=0 time=5 us)



Visitors Count

class="statcounter">

href=”http://www.statcounter.com/blogger/”
target=”_blank”> src="http://c.statcounter.com/4628332/0/06d2759c/0/"
alt="blogspot visitor" >


convert this post to pdf.

Posted by Borndba on April 4, 2009 at 12:04 am under Oracle, Oracle Performance.
Tags: ,
Comments Off.

Update Vs Insert

When sizeable portion of table to be updated which is better Update or CTAS?

To demonstrate this i have created a table with 5 million rows. Table t1 is having column “NO”. I have to add a simple function NO=NO*1.1

Using update,

SQL> update t1 set no=no*1.1;

5000000 rows updated.

Elapsed: 00:24:00.08

Statistics
----------------------------------------------------------
      19775  recursive calls
    9813469  db block gets
    5038061  consistent gets
      56546  physical reads
 2306478592  redo size
        674  bytes sent via SQL*Net to client
        554  bytes received via SQL*Net from client
          4  SQL*Net roundtrips to/from client
         19  sorts (memory)
          0  sorts (disk)
    5000000  rows processed

SQL>
Please note the time taken and the redo size.

Same using CTAS using append,
SQL> insert /*+append*/ into t2 select no*1.1 from t1;

5000000 rows created.

Elapsed: 00:00:13.31

Statistics
----------------------------------------------------------
       4585  recursive calls
      10666  db block gets
       9836  consistent gets
       8031  physical reads
     255516  redo size
        668  bytes sent via SQL*Net to client
        579  bytes received via SQL*Net from client
          4  SQL*Net roundtrips to/from client
         24  sorts (memory)
          0  sorts (disk)
    5000000  rows processed

SQL>

Note the time and redo size here. There is a huge difference here. It is 24 min vs 13 sec plus note the difference with redo size,db block gets,consistent gets, physical reads and recursive call. The performance of insert is way high. The table t1 doesn’t have any indexes. Even if you have indexes you can create with nologging and parallel. If you have constraint you can enable the constraint with “novalidate”. But there is little trap with “novalidate”, where optimizer will go for FTS instead of index scan.

Same insert i have tried without /*+append*/. Still it is far better than update.

SQL> insert into t2 select no*1.1 from t1;

5000000 rows created.

Elapsed: 00:01:12.43

Statistics
----------------------------------------------------------
       4311  recursive calls
      95857  db block gets
      19944  consistent gets
       7999  physical reads
   87332300  redo size
        684  bytes sent via SQL*Net to client
        567  bytes received via SQL*Net from client
          4  SQL*Net roundtrips to/from client
         23  sorts (memory)
          0  sorts (disk)
    5000000  rows processed

SQL>



Visitors Count

class="statcounter">
href=”http://www.statcounter.com/blogger/”
target=”_blank”> src="http://c.statcounter.com/4628332/0/06d2759c/0/"
alt="blogspot visitor" >


convert this post to pdf.

Posted by Borndba on April 4, 2009 at 12:02 am under Oracle, Oracle Administration.
Tags: ,
Comments Off.

Explain Plan output from v$sql_plan

 

If you want to get the explain plan output from v$ table you can use the below query.

Satheeshb> create or replace view dynamic_plan_table
  2  as
  3  select
  4   rawtohex(address) || '_' || child_number statement_id,
  5   sysdate timestamp, operation, options, object_node,
  6   object_owner, object_name, 0 object_instance,
  7   optimizer,  search_columns, id, parent_id, position,
  8   cost, cardinality, bytes, other_tag, partition_start,
  9   partition_stop, partition_id, other, distribution,
 10   cpu_cost, io_cost, temp_space, access_predicates,
 11   filter_predicates
 12   from v$sql_plan;

View created.

Now, you can query any plan from the database with a single query:

Satheeshb> select plan_table_output
  2    from TABLE( dbms_xplan.display
  3                ( 'dynamic_plan_table',
  4                  (select rawtohex(address)||'_'||child_number x
  5                     from v$sql
  6  where sql_text='select * from t t1 where object_id > 32000' ),
  7                  'serial' ) )
  8  /

PLAN_TABLE_OUTPUT
------------------------------------------------------------------
| Id  | Operation                   | Name|Rows| Bytes |Cst(%CPU)|
------------------------------------------------------------------
|   0 | SELECT STATEMENT            |     |    |       |         |
|   1 |  TABLE ACCESS BY INDEX ROWID| T   |291 | 27936 | 25   (0)|
|*  2 |   INDEX RANGE SCAN          | T_PK|291 |       |  2   (0)|
------------------------------------------------------------------
Predicate Information (identified by operation id):
---------------------------------------------------

   2 - access("OBJECT_ID">32000)

13 rows selected.



Visitors Count


convert this post to pdf.

Posted by Borndba on April 4, 2009 at 12:01 am under Oracle, Oracle Performance.
Tags: ,
Comments Off.

Cpu_Costing

If cpu costing is not enabled, optimizer costs both single block read and multiple block reads equally. This results in in-efficient path. Over the years CBO costing methods evolved in these ways,
Oracle 7, cost is calculated based on simple io request.
Oracle 8i, cbo accounted size and time of io request.
Oracle 9i, cbo accounted cpu costs,size and time of io request.
From 10g, cbo accounted caching,cpu costs,size and time of io request. But caching effect is not enabled by default in 10g. You need to enable “_cache_stats_monitor” to account caching by CBO.

Please find a small test case to show superior power of cbo when cpu costing is enabled.
Step 1:
~~~~~~
Delete the system statistics if any

SQL> exec dbms_stats.delete_system_stats;

PL/SQL procedure successfully completed.

Elapsed: 00:00:00.09

Step 2:
~~~~~~~
Drop, create and index the table T1. Gather table level statistics.

SQL> drop table t1;

Table dropped.

Elapsed: 00:00:00.31

SQL> create table t1 as
  2  select
  3             trunc(sysdate-1) + rownum/1440  d1,
  4             rownum                                          n1,
  5             rpad('x',100)                                   padding
  6  from
  7             all_objects
  8  where
  9             rownum <=  3000
 10  ;

Table created.

Elapsed: 00:00:00.18

SQL> alter table t1
  2     add constraint  t1_pk primary key (d1,n1)
  3     using index (create index t1_pk on  t1(d1,n1))
  4  ;

Table altered.

Elapsed: 00:00:00.13

SQL> execute dbms_stats.gather_table_stats(user,'t1',cascade=>true);

PL/SQL procedure successfully completed.

Elapsed: 00:00:00.31

Step 3:
~~~~~~~
I am firing a query again the table t1, 10000 times. Please note the timing of the executing. It is 32 seconds. I have re-executed it, just to make sure second time it takes the block from cache.

SQL> declare
  2    i binary_integer :=0;
  3    lv  varchar2(100);
  4  begin
  5    for i in 1..10000 loop
  6      select  /*+   index(t1) */
  7             padding
  8      into   lv
  9      from   t1
 10  where      d1 >= trunc(sysdate)
 11   and       n1 = 2800;
 12   --   i := i+1;
 13     end loop;
 14  end;
 15  /

PL/SQL procedure successfully completed.

Elapsed: 00:00:32.07

SQL> /

PL/SQL procedure successfully completed.

Elapsed: 00:00:32.00

Step 4:
~~~~~~
I am gathering system statistics. It also can be done using dbms_stats.gather_system_stats. Please note the flushing of shared pool. This is required to invalidate any cursor already in the shared pool. So that it generate new cursor based on cpu costing. This flushing of shared pool is not required in 10g.

SQL> begin
  2    dbms_stats.set_system_stats('CPUSPEED',500);
   3    dbms_stats.set_system_stats('SREADTIM',5.0);
  4     dbms_stats.set_system_stats('MREADTIM',30.0);
  5     dbms_stats.set_system_stats('MBRC',12);
  6  END;
  7  /

PL/SQL procedure successfully completed.

Elapsed: 00:00:00.03

SQL> alter system flush shared_pool;

System altered.

Step 5:
~~~~~
I am re-executing the plsql block executing in the step 3. Now this time it takes just 9 seconds. So cpu costing has made a huge difference in the time.

SQL> declare
  2    i binary_integer :=0;
  3    lv varchar2(100);
  4  begin
  5    for i in 1..10000 loop
  6      select /*+   index(t1) */
  7             padding
  8       into  lv
  9      from   t1
 10  where      d1 >=  trunc(sysdate)
 11  and        n1 = 2800;
 12   --   i :=  i+1;
 13     end loop;
 14  end;
 15  /

PL/SQL procedure successfully completed.

Elapsed: 00:00:08.69
SQL> /

PL/SQL procedure successfully completed.

Elapsed: 00:00:08.75

Step 6:
~~~~~~
Though the code and explain plan for the plsql block on step 3 and step 5 is same, the cpu costing has made the difference by rearranging the predicates. ( you need to have “_pred_move_arround” enabled and “ordered_predicate” hint shouldn’t be used) I have used dbms_xplan to find out the predicate order for this query.

with cpu costing enabled,Predicate Information (identified by operation  id):
---------------------------------------------------
2 - access("T1"."D1">=TRUNC(SYSDATE@!) AND "T1"."N1"=2800)
        filter("T1"."N1"=2800 AND "T1"."D1">=TRUNC(SYSDATE@!))

With cpu costing disabled,
Predicate Information (identified by operation  id):
---------------------------------------------------
2 - access("T1"."D1">=TRUNC(SYSDATE@!) AND  "T1"."N1"=2800)
       filter("T1"."D1">=TRUNC(SYSDATE@!) AND  "T1"."N1"=2800)
Note: cpu costing is off

Please note the filter value, when cpu costing disabled,
Trunc function is executed first on 3000 rows and to the output N1=2800 condition is added. Whereas when cpu costing is enabled ,N1=2800 is executed first on 3000 rows and to the output trunc function is added. It means trunc function is added to fewer than 3000 rows. Thus less load on CPU and increase in response time.How did cpu costing is making such a move?
A new code path comes into play when cpu costing is enabled. Along with selectivity of each predicate optimizer also checks, for each action how much cpu unit is required. There by without changing the execution plan it executes the query faster.Also please note, when you enabled cpu costing, you don’t have to play around with db_file_multiblock_read_count and optimizer_index* parameters. As optimizer silently changes this value based on hardware capacity.

Addendum 15th october 2006

Also please note, when you enabled cpu costing, you don’t have to play around with db_file_multiblock_read_count . As optimizer silently changes this value based on hardware capacity. optimizer_index_cost_adj is still used in exact manner when system statistics is enabled. Not sure about the other parameter optimizer_index_caching.

dbmrc will be silently set as adjusted dbmrc. But regarding optimizer_index* need to check whether system stats nullifies this.


Visitors Count


convert this post to pdf.

Posted by Borndba on April 3, 2009 at 11:56 pm under Oracle, Oracle Performance.
Tags: ,
Comments Off.

Beware of Dual

Some interesting behaviour of Dual.

SQL> startup
ORACLE instance started.

Total System Global Area   71303168 bytes
Fixed Size                  1287836 bytes
Variable Size              62916964 bytes
Database Buffers            4194304 bytes
Redo Buffers                2904064 bytes
Database mounted.
Database opened.
SQL> select  * from dual;

D
-
X

SQL> alter database close;

Database altered.

SQL> select  * from dual;

ADDR           INDX    INST_ID D
-------- ---------- ---------- -
036B2174          0          1 X

SQL> shutdown abort
ORACLE instance shut down.
SQL> startup mount
ORACLE instance started.

Total System Global Area   71303168 bytes
Fixed Size                  1287836 bytes
Variable Size              62916964 bytes
Database Buffers            4194304 bytes
Redo Buffers                2904064 bytes
Database mounted.
SQL> desc dual;
ERROR:
ORA-04043: object dual does not exist

SQL> select * from dual;

ADDR           INDX    INST_ID D
-------- ---------- ---------- -
036B2174          0          1 X

SQL> alter database open;
alter database open
*
ERROR at line 1:
ORA-01092: ORACLE instance terminated. Disconnection forced

SQL> select 2*2 from dual ;

       2*2
----------
         4

1 row selected.

SQL> column 2*2 format 9
SQL>
SQL> select 2*2 from dual ;

2*2
---
  4

1 row selected.

SQL> column 2*2 format 5
SQL>
SQL> select 3 from dual ;

         3
----------
         3

1 row selected.

SQL> select 3 "2*2" from dual ;

2*2
---
  5

1 row selected.

SQL>

Also if you want to generate N-number of records using dual then use,

select rownum from dual connect by level <=100



Visitors Count

class="statcounter">


href=”http://www.statcounter.com/blogger/”
target=”_blank”> src="http://c.statcounter.com/4628332/0/06d2759c/0/"
alt="blogspot visitor" >


convert this post to pdf.

Posted by Borndba on April 3, 2009 at 11:55 pm under Oracle, Oracle Administration.
Tags: ,
Comments Off.

RMAN backups empty block

RMAN backups all the blocks which are ever used, it means backups blocks above HWM of datafiles (Note it is datafile and not HWM of object).

1. I have created a tablespace and created a empty table. Then took a RMAN
tablespace level backup. The size was 96k
2. I have populated this table with 6million data and took RMAN tablespace level
backup. The size is 704mb.
3. I have deleted all the data, the backup size was 704mb.
4. Now i truncated the table to bring the HWM down, even this time the backup
size is 704mb.
5. Finally i droped the table, again this time the backup size is 704mb.

This tablespace has got only one object.

The reason is RMAN considers HWM of datafile and not objects. However this behaviour can be changed in 10gR2 using “Change tracking files”.



Visitors Count

class="statcounter">
href=”http://www.statcounter.com/blogger/”
target=”_blank”> src="http://c.statcounter.com/4628332/0/06d2759c/0/"
alt="blogspot visitor" >


convert this post to pdf.

Posted by Borndba on April 3, 2009 at 11:54 pm under Oracle, Oracle Backup Recovery.
Tags: ,
Comments Off.

optimizer_dynamic_sampling

I have recently came across a interesting behaviour of optimizer_dynamic_sampling. If optimizer_dynamic_sampling <=3 and set in session or system level it is not getting effective. If the table is unanalyzed then it is getting sampled.


SQL> create table t1 (id1 number(3), id2 number(3));

Table created

SQL> insert into t1 values (1,33);

1 row created.

SQL> insert into t1 values (1,33);

1 row created.

SQL> insert into t1 values (7,34);

1 row created.

SQL> insert into t1 values (7,34);

1 row created.

SQL> commit;

Commit complete.

SQL> EXEC DBMS_STATS.GATHER_TABLE_STATS('ARYAA','T1');

PL/SQL procedure successfully completed.

SQL> alter session set optimizer_dynamic_sampling=2;

Session altered.

SQL> select * from t1 where id1=1 and id2=33;

ID1        ID2
---------- ----------
1          33
1          33

Execution Plan
----------------------------------------------------------
Plan hash value: 3617692013

--------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
--------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 1 | 6 | 3 (0)| 00:00:01 |
|* 1 | TABLE ACCESS FULL| T1 | 1 | 6 | 3 (0)| 00:00:01 |
--------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

1 - filter("ID1"=1 AND "ID2"=33)

Statistics
----------------------------------------------------------
355       recursive calls
  0       db block gets
 65       consistent gets
  1       physical reads
  0       redo size
498       bytes sent via SQL*Net to client
380       bytes received via SQL*Net from client
  2       SQL*Net roundtrips to/from client
 11       sorts (memory)
  0       sorts (disk)

2 rows processed

SQL> select /*+ dynamic_sampling(t1 2) */ * from t1 where id1=1 and id2=33;

ID1        ID2
---------- ----------
1          33
1          33

Execution Plan
----------------------------------------------------------
Plan hash value: 3617692013

--------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
--------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 2 | 12 | 3 (0)| 00:00:01 |
|* 1 | TABLE ACCESS FULL| T1 | 2 | 12 | 3 (0)| 00:00:01 |
--------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

1 - filter("ID1"=1 AND "ID2"=33)

Note
-----
- dynamic sampling used for this statement

Statistics
----------------------------------------------------------
700      recursive calls
  0      db block gets
118      consistent gets
  6      physical reads
  0      redo size
498      bytes sent via SQL*Net to client
380      bytes received via SQL*Net from client
  2      SQL*Net roundtrips to/from client
  8      sorts (memory)
  0      sorts (disk)

2 rows processed

SQL>



Visitors Count


convert this post to pdf.

Posted by Borndba on April 3, 2009 at 11:52 pm under Oracle, Oracle Administration.
Tags: ,
Comments Off.

Fast Object Checkpoint

There is an interesting thread on Fast Object Ckpt in google groups. Extent Checkpoint is from 7.2, then it converted as tablespace checkpoint and now in 10.2 as segment Checkpoint. It can be enabled or disable by _db_fast_obj_ckpt =TRUE/FALSE. During Extent checking times (oracle 7.2), there were impacts on performance. Because checkpoint queues where not introduced in 7.2.

While doing export with direct=y sometime oracle does a segment checkpoint, then does direct path read. This behaviour can be seen in 10g.
http://tinyurl.com/pdnvr



Visitors Count

class="statcounter">
href=”http://www.statcounter.com/blogger/”
target=”_blank”> src="http://c.statcounter.com/4628332/0/06d2759c/0/"
alt="blogspot visitor" >


convert this post to pdf.

Posted by Borndba on April 3, 2009 at 11:51 pm under Oracle, Oracle Administration.
Tags: ,
Comments Off.

Sort_area_size

There is an general belief that sort_area_size is session level parameter. But actually it is operational parameter. That means, if the sort_area_size=5m, in a session you might actually use 5m/25m/50m etc.

Assume you open three cursor in a session which does huge sort. Each cursor will hold 5m sort_area_size.

In 9i Work_area_size=AUTO is valid only for dedicated server. If you are shared server, this parameter is not effective, you have to manually set *area_size. This behaviour is changed in 10g.



Visitors Count

class="statcounter">
href=”http://www.statcounter.com/blogger/”
target=”_blank”> src="http://c.statcounter.com/4628332/0/06d2759c/0/"
alt="blogspot visitor" >


convert this post to pdf.

Posted by Borndba on April 3, 2009 at 11:51 pm under Oracle, Oracle Administration.
Tags: ,
Comments Off.

Changing Pctused,Pctfree and Initrans

When you change pctfree or pctused, the value will get effective only to new blocks. However if oracle ever changes old blocks, that time these values will be set to pctfree and pctused.
However for initrans, only new blocks will be affected. If you want the existing block to use the new initrans, we need to rebuild the object again.



Visitors Count


convert this post to pdf.

Posted by Borndba on April 3, 2009 at 11:49 pm under Oracle, Oracle Administration.
Tags: ,
Comments Off.

Flushing Buffer_Cache

This is tried in 10.2.0.2,


SQL> select state,count(*) from x$bh group by state;

     STATE   COUNT(*)

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

         1        940

         0          6

SQL> alter system flush buffer_cache;

System altered.

SQL> select state,count(*) from x$bh group by state;

     STATE   COUNT(*)

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

         1          3

         0        943

SQL>

The STATE column of all the blocks will be set to Zero. While the buffers head which are pinned will remain same.

There is no Flush buffer_cache in 9i, you need to set the event to do the same.

ALTER SESSION SET EVENTS ‘immediate trace name flush_cache’;



Visitors Count


convert this post to pdf.

Posted by Borndba on April 3, 2009 at 11:48 pm under Oracle, Oracle Administration.
Tags: ,
Comments Off.

ITL Waits

create table x ( no number ) initrans 2 maxtrans 2 pctfree 0;
begin
 for i in 1..734 loop
   insert into x values (i);
 end loop;
end;
/
commit;

exec dbms_stats.gather_table_stats(user,'X');

first session,
SQL> update x set no=no where no=1;

1 row updated.
--don't commit
second session,
SQL> update x set no=no where no=2;

1 row updated.
--don't commit

third session,
SQL> update x set no=no where no=3;

The third session will hang due to insufficient itl. In 10g it will be waiting on “enq: TX – allocate ITL entry”. In previous release it was confusion as ITL wait will get added “enqueue” wait.

initrans is initial number of transaction slot require, additional slots are defined by maxtrans.

High number of maxtrans will compete for space with data layer. Earlier version consumes 23 bytes and latest version consumes 24 bytes, if you want to find out size a slot for your version run,

select type_size from v$type_size where description='TRANSACTION VARIABLE HEADER'
/
TYPE_SIZE
----------
24

ITL is valid only for UPDATE and DELETE. Not for INSERT,if there is no itl slot in a block, oracle will put the record into the other blocks which are in the freelist. Therefore there will not be any ITL contention for INSERT.

But if a table has index and if INSERT transalates into UPDATE in the index block, you might get ITL contention if the index block itl slot is full. If there is ITL shortage on index block during insert, then there will be block split.

ITL will have 3 parts, Transaction Id(TID),Undo DBA (uid) and SCN. If Delayed clean out happens, SCN part will be only set during this phase.

Maxtrans is deprecated in 10.1



Visitors Count

class="statcounter">

href=”http://www.statcounter.com/blogger/”
target=”_blank”> src="http://c.statcounter.com/4628332/0/06d2759c/0/"
alt="blogspot visitor" >


convert this post to pdf.

Posted by Borndba on April 3, 2009 at 11:44 pm under Oracle, Oracle Administration.
Tags: ,
Comments Off.

Redo Log Switch

Redo generation is entirely disabled during a log switch. This is done by setting an SGA variable reflecting the cause and status of the log switch. Sessions about to allocate space in the log buffer check this variable first and if a log switch is in progress they wait on the appropriate one of several wait events associated with log switching. No log buffer space allocation is attempted until after the log switch has completed, therefore the log buffer space wait event will not be seen during a log switch. However, if a large number of processes have been waiting for a log switch to complete then there can be a burst of redo generation thereafter that does result in secondary log buffer space waits



Visitors Count


convert this post to pdf.

Posted by Borndba on April 3, 2009 at 11:42 pm under Oracle, Oracle Administration.
Tags: ,
Comments Off.

Order of Instance Start

When STARTUP command is given, this the way oracle will start the instance.

  1. Read the init.ora
  2. Start the background processes
  3. Allocates the shared memory
  4. Allocates Semaphore.
  5. Then other usual stuff  of checking the SCN of the controlfile and datafile_header. Do crash recovery or request for media recovery



Visitors Count


convert this post to pdf.

Posted by Borndba on April 3, 2009 at 11:42 pm under Oracle, Oracle Administration.
Tags: ,
Comments Off.

dbms_system.kcfrms

If you execute dbms_system.kcfrms, it will reset max_wait_time of sessions events, system events and file statistics. For system events it will reset max_wait_time of underlying x$table.



Visitors Count


convert this post to pdf.

Posted by Borndba on April 3, 2009 at 11:41 pm under Oracle, Oracle Internal.
Tags: ,
Comments Off.

BUFFER=Y in export

In direct mode of export, BUFFER parameter is not valid. Instead use RECORDLENGTH. If you don’t specify RECORDLENGTH in direct mode export then i _guess_ it will only take 1k. You can set upto 65535 for RECORDLENGTH.



Visitors Count


convert this post to pdf.

Posted by Borndba on April 3, 2009 at 11:40 pm under Oracle, Oracle Backup Recovery.
Tags: ,
Comments Off.

Tuned Undo Retention

10g got a new feature, where undo_retention is tuned automatically.

When we set the undo_retention=0, then minimum value of UNDO RETENTION will be 900 sec, which is 15 minutes. MMON will calculate the MAXQUERYLEN every 30 sec interval. Based upon the MAXQUERYLEN, MMON will decide TUNED_UNDORETENTION. That means the new UNDO RETENTION will be set to TUNED_UNDORETENTION. TUNED_UNDORETENTION is one of the column in v$undostat.
The calculation is like, TUNED_UNDORETENTION = MAXQUERYLEN + 300 Sec.


Visitors Count


convert this post to pdf.

Posted by Borndba on April 3, 2009 at 11:38 pm under Oracle, Oracle Administration.
Tags: ,
Comments Off.

Tracing export sessions

There is an hidden parameter in export command, which will enable us to trace the export operation. Otherwise it will be difficult to get the sid of the export command and trace that session.

exp trace=y and other command.

Trace file will get generated in udump area. Use tkprof to format this trace file.



Visitors Count


convert this post to pdf.

Posted by Borndba on April 3, 2009 at 11:37 pm under Oracle, Oracle Administration.
Tags: ,
Comments Off.

Index Rebuild is very slow in 10g

     
       We were planning to move one of the production db from 9i to 10g. In process of this, we are doing performance testing of the application and batch program in 10g. As espected we encountered few issues and we were able to fix those, except one.
       After a bulk load to a table, which is having bitmap functional index our batch program does the rebuild of the bitmap index. The index rebuild in 9i comes out in 3-4 hrs whereas in 10g it goes for few days. The session which was rebuilding the index is spending quite a lot of time on “db file scattered read”. Oracle identified few bugs and asked us to apply the patch. But that didn’t help.
       Since it is a test environment, i was trying various settings. One of the setting was changing the workarea_size_policy to manual. This helped the index rebuild to complete in 4 hrs. But this was not acceptable to the business as this could change lot of other things.
       One thing which striked me is the size of pga_aggreagate_target. It is 20gb which to me looked unusual. Increasing the pga size will internally increase the default value of some parameters like _pga_max_size,_smm_* parameters. Since 20gb is pga size the _pga_max_size is defaulted to 2gb (10% of pga). When we changed the parameter to 200mb, the rebuild of index completed successfully.
       Oracle support team which i was intereacting was not able to give the reason for change of behaviour in 10g.


Visitors Count


convert this post to pdf.

Posted by Borndba on April 3, 2009 at 11:31 pm under Oracle, Oracle Administration.
Tags: ,
Comments Off.

Changing OEM repository Server

This note covers, how to change the oem repository server.

OEM is a monitoring tool used in many of the shops around the world. As number of target increases, we need to either upgrade the existing repository server or move to new repository server.

If your company decides to move to new server, then we need to change the agent configuration on each target.

Please follow the below steps in each agent to point to new server.

Go to $AGENT_HOME/bin

execute below command to stop the agent,
./emctl stop agent
Execute the below command to unsecure the agent,
./emctl unsecure agent
We need to delete serious of files,  as this file might point to old oem respository server.
cd ../sysman/emd/upload
rm *.*
cd ../state
rm *.*
cd ../upload
rm *.*
cd ../collection
rm *.*
cd ..
rm agntstmp.txt
rm lastupld.xml
Go to $AGENT_HOME/sysman/config and open emd.properties
change the below entry to point to new server,
REPOSITORY_URL=https://newhost:1159/em/upload
emdWalletSrcUrl=https://newhost:1159/em/wallets/emd
EMD_URL=http://localhost:1830/emd/main

That’s it.

Now restart the agent.

Go to $AGENT_HOME/bin

./emctl clearstate agent
./emctl upload agent
./emctl secure agent <password>
./emctl start agent
Agent password is what you supplied while installing the oem repository.
New OEM repository server should be able to deduct the agent now.



Visitors Count

class="statcounter">

href=”http://www.statcounter.com/blogger/”
target=”_blank”> src="http://c.statcounter.com/4628332/0/06d2759c/0/"
alt="blogspot visitor" >


convert this post to pdf.

Posted by Borndba on April 3, 2009 at 11:21 pm under Oracle, Oracle Grid Control.
Tags: ,
Comments Off.