Archive for the ‘Oracle Administration’ 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.

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.

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.

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.

 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.

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.

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.

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.

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

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.

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.

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.

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.

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.

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.

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.

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.