Friday, 3 February 2017

Table stats gather commands

                                            Table stats gather

The Oracle RDBMS allows you to collect statistics of many different kinds as an aid to improving performance.DBMS_STATS.gather_table_stats package is used to gather stats for table.


Here are some useful commands for table stats gather.

exec dbms_stats.gather_table_stats(ownname=>'ADM',tabname=>'PS_SCH',cascade=>TRUE,estimate_percent=>DBMS_STATS.AUTO_SAMPLE_SIZE ,method_opt=>'FOR ALL  COLUMNS SIZE AUTO');

select 'exec dbms_stats.gather_table_stats(ownname=>'||''''||'SYSADM'||''''||',tabname=>'||''''||table_name||''''||',cascade=>TRUE,estimate_percent
=>DBMS_STATS.AUTO_SAMPLE_SIZE ,method_opt=>'||''''||'FOR ALL COLUMNS SIZE AUTO'||''''||');' from dba_tables  where TABLE_NAME like 'PS_GP\_%' ESCAPE '\' and owner='ADM'


Comment me if you find this post is useful also let me know if you need any new topics.

Wednesday, 1 February 2017

how to drop and installing the statspack

The Statspack package is a set of SQL, PL/SQL, and SQL*Plus scripts that allow the collection, automation, storage, and viewing of performance data. Statspack stores the performance statistics permanently in Oracle tables, which can later be used for reporting and analysis. The data collected can be analyzed using Statspack reports, which includes an instance health and load summary page, high resource SQL statements, and the traditional wait events and initialization parameters.

Staspack drop:-

Checking the objects in PREFSTAT tablespace.

select table_name from dba_tables where tablespace_name='PERFSTAT';

select object_name,object_type from dba_objects where object_name='STATSPACK';

 set lines 300
 col OWNER for a12
 col SEGMENT_NAME for a30
 col SEGMENT_TYPE for a20
 set pages 300
 select owner,SEGMENT_NAME,SEGMENT_TYPE from dba_segments where tablespace_name='PERFSTAT'; 


spdrop.sql is used to drop user, tables and package for  performance diagnostic tool STATSPACK

@?/rdbms/admin/spdrop.sql

Now all statspack data has been dropped.So now we can drop the PREFSTAT tablespace.

drop tablespace perfstat including contents and datafiles;







Installing statspack:-


spcreate.sql  SQL*PLUS command file which creates the STATSPACK user, tables and package for the performance diagnostic tool STATSPACK


Before running spcreate.sql we need to create prefstat tablespace for holding statspack user , tables and package for the performance diagnostic tool

create tablespace PERFSTAT datafile '/oracle/data11/perfstat01.dbf' size 2g;


The first step in the installation is the creation of the PERFSTAT user, which owns all PL/SQL code and database objects created, including the Statspack tables, constraints, and the Statspack package. During installation, you are prompted for the PERFSTAT user's password, default tablespace, and temporary tablespace. The default tablespace is used to create all Statspack objects, such as tables and indexes. The temporary tablespace is used for sort-type activities.

@?/rdbms/admin/spcreate.sql

Choose the PERFSTAT user's password
-----------------------------------
Not specifying a password will result in the installation FAILING

Enter value for perfstat_password: perfstat
perfstat


Choose the Default tablespace for the PERFSTAT user
---------------------------------------------------
Below is the list of online tablespaces in this database which can
store user data.  Specifying the SYSTEM tablespace for the user's
default tablespace will result in the installation FAILING, as
using SYSTEM for performance data is not supported.

Choose the PERFSTAT users's default tablespace.  This is the tablespace
in which the STATSPACK tables and indexes will be created.

TABLESPACE_NAME                CONTENTS  STATSPACK DEFAULT TABLESPACE
------------------------------ --------- ----------------------------
KABA                           PERMANENT
PERFSTAT                       PERMANENT
SYSAUX                         PERMANENT *
USERS                          PERMANENT

Pressing <return> will result in STATSPACK's recommended default
tablespace (identified by *) being used.

Enter value for default_tablespace: PERFSTAT

Using tablespace PERFSTAT as PERFSTAT default tablespace.


Choose the Temporary tablespace for the PERFSTAT user
-----------------------------------------------------
Below is the list of online tablespaces in this database which can
store temporary data (e.g. for sort workareas).  Specifying the SYSTEM
tablespace for the user's temporary tablespace will result in the
installation FAILING, as using SYSTEM for workareas is not supported.

Choose the PERFSTAT user's Temporary tablespace.

TABLESPACE_NAME                CONTENTS  DB DEFAULT TEMP TABLESPACE
------------------------------ --------- --------------------------
TEMP                           TEMPORARY *

Pressing <return> will result in the database's default Temporary
tablespace (identified by *) being used.

Enter value for temporary_tablespace: TEMP

Using tablespace TEMP as PERFSTAT temporary tablespace.
 


 Comment me if you find this post is useful also let me know if you need any new topics.


Oracle 12c : Startup and Shutdown CDB & PDB step by step

The multitenant option introduced in Oracle Database 12c allows a single container database (CDB) to host multiple separate pluggable databases (PDB).

Starting the container database:-



Starting the CDB is same as it has always been for regular instances.

STARTUP;















Normal startup command will start only the cdb and seed database.but still if you look pdb it will be in mounted mode.

Starting the pluggable database:-

ALTER PLUGGABLE DATABASE PDB_ORCL OPEN;







 starting the one or more pdb .

ALTER PLUGGABLE DATABASE OPEN ALL;

Shutdown PDB:-

ALTER PLUGGABLE DATABASE PDB_ORCL CLOSE;




ALTER PLUGGABLE DATABASE CLOSE ALL;

Shutdown CDB:-

Shutdown  the CDB is same as it has always been for regular instances.

SHUT IMMEDIATE;



Comment me if you find this post is useful also let me know if you need any new topics.











tablespace monitor html report shell script

#!/bin/ksh
export ORACLE_SID=orcl
export ORACLE_HOME=/u01/oracle
PATH=$ORACLE_HOME/bin:$PATH
export PATH
$ORACLE_HOME/bin/sqlplus "/ as sysdba" <<EOF > /home/oraprod/TBS.log
SET ECHO OFF
set pages 1000
set feedback off
SET MARKUP HTML ON SPOOL ON
SPOOL TBS.html
select tablespace_name, free_percent, free_size_mb
from (
            SELECT b.tablespace_name, b.tablespace_size_mb, sum(nvl(fs.bytes,0))/1024/1024 free_size_mb,
            (sum(nvl(fs.bytes,0))/1024/1024/b.tablespace_size_mb *100) free_percent
            FROM dba_free_space fs,
                 (SELECT tablespace_name, sum(bytes)/1024/1024 tablespace_size_mb FROM dba_data_files
                  GROUP BY tablespace_name
                 ) b
           where fs.tablespace_name = b.tablespace_name
           group by b.tablespace_name, b.tablespace_size_mb
        ) ts_free_percent
WHERE free_percent < 10
ORDER BY free_percent;
spool off
exit
EOF
export MAILTO="mail address"
export CONTENT="/home/oraprod/TBS.html"
export SUBJECT="TABLESPACE FREESPACE REPORT"
(
 echo "Subject: $SUBJECT"
 echo "MIME-Version: 1.0"
 echo "Content-Type: text/html"
 echo "Content-Disposition: inline"
 cat $CONTENT
) | /usr/sbin/sendmail $MAILTO


Comment me if you find this post is useful also let me know if you need any new topics.

oracle silent install

Manual software install --->silent

./runInstaller -silent -debug -force \
FROM_LOCATION=/home/oracle/database/stage/products.xml \
oracle.install.option=INSTALL_DB_SWONLY \
UNIX_GROUP_NAME=oinstall \
INVENTORY_LOCATION=/oradata/prods/oracle/product/oraInventory \
ORACLE_HOME=/oradata/prods/oracle/product/NOTL01UD_binb/11.2.0 \
ORACLE_HOME_NAME="OraDb11g_Home1" \
ORACLE_BASE=/oradata/prods/oracle \
oracle.install.db.InstallEdition=EE \
oracle.install.db.isCustomInstall=false \
oracle.install.db.DBA_GROUP=dba \
oracle.install.db.OPER_GROUP=dba \
DECLINE_SECURITY_UPDATES=true

manual client install -->silent

./runInstaller -silent -debug -force \
FROM_LOCATION=/oradata/prods/oracle/client/client/stage/products.xml \
UNIX_GROUP_NAME=oinstall \
ORACLE_HOME=/oradata/data/oracle/client/11.2.0 \
ORACLE_HOME_NAME="client11g_Home1" \
ORACLE_BASE=/oradata/data/oracle \
oracle.install.client.installType="Administrator"


Comment me if you find this post is useful also let me know if you need any new topics.

Manual db creation

1.create spfile/pfile
2.startup nomount
3.Run below script (change the file names depends on your environment)

CREATE DATABASE DB_NAME
   USER SYS IDENTIFIED BY avery123
   USER SYSTEM IDENTIFIED BY avery123
   LOGFILE GROUP 1 ('/oradata/data/oracle_dev/NOTL01UD/datafile02/redo01.log') SIZE 100M,
           GROUP 2 ('/oradata/data/oracle_dev/NOTL01UD/datafile02/redo02.log') SIZE 100M,
           GROUP 3 ('/oradata/data/oracle_dev/NOTL01UD/datafile02/redo03.log') SIZE 100M
   MAXLOGFILES 5
   MAXLOGMEMBERS 5
   MAXLOGHISTORY 1
   MAXDATAFILES 100
   MAXINSTANCES 1
   CHARACTER SET WE8ISO8859P1
   DATAFILE '/oradata/data/oracle_dev/NOTL01UD/datafile01/system01.dbf' SIZE 500M REUSE
   EXTENT MANAGEMENT LOCAL
   SYSAUX DATAFILE '/oradata/data/oracle_dev/NOTL01UD/datafile01/sysaux01.dbf' SIZE 500M REUSE
   DEFAULT TABLESPACE USERTBS datafile '/oradata/data/oracle_dev/NOTL01UD/datafile01/usertbs01.dbf' size 500M
   DEFAULT TEMPORARY TABLESPACE TEMP
      TEMPFILE '/oradata/data/oracle_dev/NOTL01UD/datafile01/temp01.dbf'
      SIZE 20M REUSE
   UNDO TABLESPACE UNDOTBS
      DATAFILE '/oradata/data/oracle_dev/NOTL01UD/datafile01/undotbs01.dbf'
      SIZE 200M REUSE AUTOEXTEND ON MAXSIZE UNLIMITED;

4 Run below scripts for data dictionary tables creation

@/u01/oracle/rdbms/admin/catalog.sql
@/u01/oracle/rdbms/admin/catproc.sql


Comment me if you find this post is useful also let me know if you need any new topics.

Oracle logmining

1.select supplemental_log_data_min  from v$database;

If supplemental log data is not enabled then

2.ALTER DATABASE ADD SUPPLEMENTAL LOG DATA;


3.  To check the max of logfile.

SELECT NAME FROM V$ARCHIVED_LOG
       WHERE FIRST_TIME = (SELECT MAX(FIRST_TIME) FROM V$ARCHIVED_LOG);

4.For checking log files in specific time and date:
SELECT *
  FROM (SELECT MIN (
                     'EXECUTE DBMS_LOGMNR.ADD_LOGFILE(LOGFILENAME => '''
                  || val.name
                  || ''', OPTIONS => DBMS_LOGMNR.NEW);')
          FROM V$ARCHIVED_LOG val
        WHERE     val.first_time BETWEEN TO_TIMESTAMP (
                                             '&&START_DDMONYYYYHH24MISS.',
                                             'DDMONYYYYHH24MISS')
                                      AND TO_TIMESTAMP (
                                             '&&END_DDMONYYYYHH24MISS.',
                                             'DDMONYYYYHH24MISS')
               AND val.dest_id = 1
               )
UNION ALL
(SELECT    'EXECUTE DBMS_LOGMNR.ADD_LOGFILE(LOGFILENAME => '''
        || val.name
        || ''', OPTIONS => DBMS_LOGMNR.ADDFILE);'
   FROM V$ARCHIVED_LOG val
  WHERE     val.first_time BETWEEN TO_TIMESTAMP (
                                             '&&START_DDMONYYYYHH24MISS.',
                                             'DDMONYYYYHH24MISS')
                               AND TO_TIMESTAMP (
                                             '&&END_DDMONYYYYHH24MISS.',
                                             'DDMONYYYYHH24MISS')
       AND val.dest_id = 1
        );

It will ask Start Date & time and End date and time. (Ex : 28APR2013070000)

Take the output....and execute plsql procedures completely.

EXECUTE DBMS_LOGMNR.ADD_LOGFILE( LOGFILENAME => '/disk05/oradata/DEVT/archive/1_7315_613831530.arc',OPTIONS => DBMS_LOGMNR.NEW);
EXECUTE DBMS_LOGMNR.ADD_LOGFILE( LOGFILENAME => '/disk05/oradata/DEVT/archive/1_7316_613831530.arc', OPTIONS => DBMS_LOGMNR.ADDFILE);
.
.
.
.
EXECUTE DBMS_LOGMNR.ADD_LOGFILE( LOGFILENAME => '/disk05/oradata/DEVT/archive/1_7330_613831530.arc', OPTIONS => DBMS_LOGMNR.ADDFILE);

       
5.Start log miner:
To collect also the commit timestamp -> EXECUTE DBMS_LOGMNR.START_LOGMNR( OPTIONS => DBMS_LOGMNR.DICT_FROM_ONLINE_CATALOG + DBMS_LOGMNR.COMMITTED_DATA_ONLY);

6.  Collect the row IDs for particular seg_name and seg_owner

select distinct row_id from v$logmnr_contents where seg_name='CMS_INVENTORY' and seg_owner='LILYPLU';


7.create table  as
  select timestamp,commit_timestamp, audit_sessionid,seg_owner,seg_name,username,session#,serial#,operation_code,sql_redo,sql_undo,row_id  FROM V$LOGMNR_CONTENTS where seg_owner = 'LILYPLU' and seg_name = 'COATING_ORDER' and
  row_id in ('AAAeHJAAQAAJ0f5AAU',
'AAAeHJAAQAAJ0eLAAg',
'AAAeHJAAQAAJ0f5AAO',
'AAAeHJAAQAAJ0f2AAU',
'AAAeHJAAQAAJ0ftAAi',
'AAAeHJAAQAAJ0fZAAe',
'AAAeHJAAQAAJ0f5AAR',
'AAAeHJAAQAAJ0f2AAV',
'AAAeHJAAQAAJ0fpAAk',
'AAAeHJAAQAAJ0f5AAk',
'AAAeHJAAQAAJ0fTAAL',
'AAAeHJAAQAAJ0fpAAg',
'AAAeHJAAQAAJ0ftAAl',
'AAAeHJAAQAAJ0f5AAS'
)

8.Below query gives number of Update,insert & delete for particular owner for particular table.

select seg_owner, seg_name, username, operation, count(*) from V$LOGMNR_CONTENTS where seg_name='RUN' and seg_owner='LILYPGO'group by seg_owner, seg_name, username, operation

9. To find the user session on the audit log when the information at the logminer is not complete
==============================================================================================-=

    select * from dba_audit_session where sessionid = '123'

    :Where 123 is the value of column AUDIT_SESSIONID you took from the V$LOGMNR_CONTENTS table


select distinct audit_sessionid from v$logmnr_contents where seg_name='RUN' and seg_owner='LILYPGO';

10.Turn off the minering

    EXECUTE DBMS_LOGMNR.END_LOGMNR();


NOTES:  When we are using sql developer, it is better to divide the time period, create table, and  turn off log miner. Then start for second set of log mining session. (Example : If there is more than 1000 rows for row IDs we can't execute the script on sqldeveloper)


To get the visible timestamps:
select TO_CHAR (timestamp ,'YYYY-MON-DD HH24:MI:SS') as time,TO_CHAR (COMMIT_TIMESTAMP ,'YYYY-MON-DD HH24:MI:SS') as commit_time, AUDIT_SESSIONID,SEG_OWNER,SEG_NAME,USERNAME,session#,SERIAL#,OPERATION_CODE,SQL_REDO,SQL_UNDO,ROW_ID  from babus.miner01 where SEG_OWNER = 'LILYPLU' and SEG_NAME = 'CMS_INVENTORY' and
  row_id in ('AAAeGXAAQAAAv2GAAA');


Comment me if you find this post is useful also let me know if you need any new topics.



Dataguard useful commands



Verify archived redo log files were applied.
============================================

SELECT SEQUENCE#,APPLIED FROM V$ARCHIVED_LOG ORDER BY SEQUENCE#;


To determine if a gap exists:
============================

SELECT * FROM V$ARCHIVE_GAP;


Query the physical standby database to monitor log apply and log transport services activity at the standby site.
=================================================================================================================

SELECT PROCESS, STATUS, THREAD#, SEQUENCE#, BLOCK#, BLOCKS FROM V$MANAGED_STANDBY;


Messages in regards to the data guard status
============================================

column message format a80
SELECT to_char(TIMESTAMP,'DD-MM-YY HH24:MM:SS'), MESSAGE FROM V$DATAGUARD_STATUS;

column message format a80
select  to_char(dgs.TIMESTAMP,'DD-MM-YY HH24:MM:SS')
,       dgs.severity
,       dgs.error_code
,       dgs.message
from    v$dataguard_status  dgs
where severity in ('Error','Fatal')
or      error_code <> '0'
/

>> With Borker


show database "DB_NAME" LatestLog;



Recovery start on standby
=========================

>> without broker

sqlplus / as sysdba
ALTER DATABASE RECOVER MANAGED STANDBY DATABASE DISCONNECT FROM SESSION;
SELECT RECOVERY_MODE FROM V$ARCHIVE_DEST_STATUS WHERE DEST_ID=2 ;

>> with broker
dgmgrl
connect sys
edit database "DB_NAME" SET STATE='ONLINE';
show database verbose "DB_NAME";





Recovery stoppen  op standby (without broker)
=============================================

>> Without broker

sqlplus / as sysdba
RECOVER MANAGED STANDBY DATABASE CANCEL nowait;

>> With Broker

edit database "DB_NAME" set state=LOG-APPLY-OFF;
show database verbose "DB_NAME";



Transport stop with broker
==========================

edit database "DB_NAME" set state=LOG-TRANSPORT-OFF;

reactivate -> edit database "DB_NAME" set state=online;



Role check
==========

select name, database_role from v$database;


Sessions check
==============

select username, osuser from v$session where username is not null;



Status check archiving
======================

column error format a55 tru
select     dest_id
,    status
,    error
from     v$archive_dest;

select     dest_id
,    process
,    transmit_mode
,    async_blocks
,       net_timeout
,    delay_mins
,    reopen_secs
,    register
,    binding
from     v$archive_dest;




Query archive status
====================

column  Status        format a10      heading "Status"
column  destination     format a35      heading "Destination"
SELECT DEST_ID "ID"
,      STATUS "DB_status"
,      DESTINATION
,      ERROR "Error"
FROM   V$ARCHIVE_DEST
/


To register a log that is not on the catalog (v$archived_logs)
==============================================================

alter database register logfile '/disk05/oradata/SWML/archives/1_0000031863_644148730.arc';

# If you get
# ORA-00317: file type 0 in header is not log file
# ORA-00334: archived log: '/disk05/oradata/DGT/archive/1_1_717000018.arc'
#
cancel recovery on the standby
copy (eventually) the archive log again to the standby
alter database register or replace physical logfile '/disk05/oradata/DGT/archive/1_1_717000018.arc';
resume recovery




 Run this query on the primary to know how big is your GAP and how long it will take:
======================================================================================


select sum(loc.blocks),
sum(((loc.blocks+1)*loc.block_size)/1024/1024)  "Size MB",
sum((((loc.blocks+1)*loc.block_size) * 8 ) / 1000000) "Size Megabits",
sum(((((loc.blocks+1)*loc.block_size) * 8 ) / 1000000 )) /&linkcapacitymbps "Seconds to Transfer (Uncomp)"
from
  (select * from v$archived_log where dest_id = 1) loc,
  (select * from v$archived_log where dest_id = 2) remote
where remote.sequence# (+) = loc.sequence#
  and remote.sequence# is null
  and loc.status = 'A'
order by loc.sequence# desc



Comment me if you find this post is useful also let me know if you need any new topics.