Monday, February 10, 2020

Dataguard Broker Basics

Dataguard Broker Basics


- The Data Guard broker logically groups primary and standby databases in a Data Guard setup into a broker configuration that allows the broker to manage and monitor them together as an integrated unit. You can manage a broker configuration using either the Oracle Enterprise Manager graphical user interface or the Data Guard command-line interface.

- Data Guard Broker is part of the normal Oracle Database Enterprise Edition installation and an integral part of dataguard. You can do Data Guard related configuration, set transport methods, apply setup and role change services and also change overall protection mode.

The Broker consists of three major parts:

A) BACKGROUND PROCESSES ON EACH NODE
B) BROKER CONFIGURATION FILES
C) COMMAND LINE INTERFACE KNOWN AS DGMGRL.

A) BACKGROUND PROCESSES ON EACH NODE
All of the processes run on every node of Data Guard setup.

i) Data Guard Monitor (DMON)
Coordinates all Broker actions as well as maintains the Broker configuration files
Enabled or disabled with the DG_BROKER_START parameter.

ii) Broker Resource Manager (RSM)
RSM process comes in play whenever broker need to run any SQL command in the database.
SQL may be required to be run during Data Guard setup or because of result of a change to the conguration made through DGMGRL

iii) Data Guard Net Server (NSVn)
NSV processes are responsible for making connection with the remote database and to send across anywork items to the remote database. So, DMON or RSM process may ask NSV process to connect to other node for any work request. DMON may need to send some communication to the other node and RSM may have to get some data through SQL from other node.

iv) DRCn
NSV processes contact DRC process running on other node to establish the connection, so DRC process acts like a receiver on other node. Each NSV process will have a partner DRC process on the target database, which will perform the actual work on behalf of the source database NSV process and return the results or status.

v) Internode servers (INSVs)
If Data Guard setup involves Real Application Clusters (RAC), INSV process come into play. It maintain a connection between the RAC database nodes in the cluster to ensure that the Broker on each node knows the state of the cluster.

WHAT HAPPENS AT DATABASE STARTUP:

Step 1) Primary database startup.
Step 2) DMON process at primary ask local NSV process to connect to each standby database.
Step 3) NSV process in turn will contact DRC process on standby and get confirmation.
Step 4) DMON process at primary will then ask local RSM to send the setup commands to the standby database.
Step 5) RSM will send the setup commands to NSV.
Step 6) NSV process in turn will contact DRC process on standby to run the setup commands.


B) BROKER CONFIGURATION FILES

Broker keeps its configuration details in flat file. The files are stored at each database nodes in the Data Guard configuration. Additionally two copies of the configuration files are always stored on each database for redundancy.

Below parameters control where the configuration files will be stored.

DG_BROKER_CONFIG_FILE1
DG_BROKER_CONFIG_FILE2

For RAC instances, you need to keep the files in shared location where all database instances can access it. Broker keeps in sync all of these configuration files but DMON process running on the primary database is the owner of the master copy of the files.

This means that if you started the standby database while Data guard process are down at primary node, then no data guard related activities will be done until the standby database can connect to the primary database.

Primary purpose of keeping configuration files on each node is when your primary node is gone and you need to failover, Data Guard processes can determine the original settings for the entire configuration from the configuration files on other surviving node.

C) COMMAND LINE INTERFACE (CLI) KNOWN AS DGMGRL

The third important part of Broker setup is the interface through which users will interact with Broker. The Broker CLI DGMGRL is included in the Oracle Database Enterprise Edition.

To access DGMGRL, type dgmgrl at the command prompt. Use the CONNECT command after you have started DGMGRL to connect to databases.

Below steps to configure Dataguard Broker

SQL> select NAME,DATABASE_ROLE,DATAGUARD_BROKER from v$database;
NAME      DATABASE_ROLE    DATAGUAR
--------- ---------------- --------
DELL      PRIMARY          DISABLED

- Change the location of config files

Since our Primary and Standby databases are RAC, we will change the default location of DG Broker files to a centralized location so that all nodes can access them. In our case, we will be using the ACFS mount point.

Login as oracle user on Primary and execute below commands.

SQL> show parameter dg_broker_config

NAME                                 TYPE        VALUE
------------------------------------ ----------- ------------------------------
dg_broker_config_file1               string      /u01/app/oracle/products/12.1.0/db/dbs/dr1orcldb.dat
dg_broker_config_file2               string      /u01/app/oracle/products/12.1.0/db/dbs/dr2orcldb.dat

SQL> !mkdir -p /u01/app/acfs/reco/dg_broker_config_file

SQL> alter system set dg_broker_config_file1='/u01/app/acfs/reco/dg_broker_config_file/dr1orcldb.dat';
System altered.

SQL> alter system set dg_broker_config_file2='/u01/app/acfs/reco/dg_broker_config_file/dr2orcldb.dat';
System altered.

Similarly, change the settings on Standby database server.

SQL> !mkdir -p /u01/app/acfsreco/dg_broker_config_file

SQL> alter system set dg_broker_config_file1='/u01/app/acfsreco/dg_broker_config_file/dr1orcldbs.dat';
System altered.

SQL> alter system set dg_broker_config_file2='/u01/app/acfsreco/dg_broker_config_file/dr2orcldbs.dat';
System altered.

- Change the dg_broker_start parameter value

Now change the parameter 'dg_broker_start' to TRUE on both Primary and Standby databases as shown below.
SQL> alter system set dg_broker_start=TRUE;
System altered.

- Register databases using dgmgrl

On the primary server, login to command line interface using dgmgrl and register the primary database in the broker configuration.

[oracle@rac1 ~]$ dgmgrl
DGMGRL for Linux: Version 12.1.0.2.0 - 64bit Production
Copyright (c) 2000, 2013, Oracle. All rights reserved.
Welcome to DGMGRL, type "help" for information.
DGMGRL> connect sys/password@orcldb
Connected as SYSDBA.
DGMGRL>

DGMGRL> CREATE CONFIGURATION dg_config AS PRIMARY DATABASE IS orcldb CONNECT IDENTIFIER IS orcldb;
Configuration "dg_config" created with primary database "orcldb"

[oracle@rac1 ~]$ dgmgrl
DGMGRL for Linux: Version 12.1.0.2.0 - 64bit Production
Copyright (c) 2000, 2013, Oracle. All rights reserved.
Welcome to DGMGRL, type "help" for information.
DGMGRL> connect sys/password@orcldb
Connected as SYSDBA.

DGMGRL> CREATE CONFIGURATION dg_config AS PRIMARY DATABASE IS orcldb CONNECT IDENTIFIER IS orcldb;
Configuration "dg_config" created with primary database "orcldb"
Now add the standby database in broker configuration.

DGMGRL> ADD DATABASE orcldbs AS CONNECT IDENTIFIER IS orcldbs MAINTAINED AS PHYSICAL;
Database "orcldbs" added

- Enable and Check the broker configuration
We need to enable the broker configuration and check if the configuration is enabled successfully or not.

DGMGRL> ENABLE CONFIGURATION;
Enabled.

DGMGRL> show configuration;
Configuration - dg_config
Protection Mode: MaxPerformance
Members:
orcldb  - Primary database
orcldbs - Physical standby database
Fast-Start Failover: DISABLED
Configuration Status:
SUCCESS   (status updated 13 seconds ago)

DGMGRL> ENABLE CONFIGURATION;
Enabled.

DGMGRL> show configuration;
Configuration - dg_config
Protection Mode: MaxPerformance
Members:
orcldb  - Primary database
orcldbs - Physical standby database
Fast-Start Failover: DISABLED
Configuration Status:
SUCCESS   (status updated 13 seconds ago)

Once the broker configuration is enabled, the MRP process should get start on the Standby database server. You can check using below command.

DGMGRL> show database orcldbs
Database - orcldbs
Role:               PHYSICAL STANDBY
Intended State:     APPLY-ON
Transport Lag:      0 seconds (computed 0 seconds ago)
Apply Lag:          0 seconds (computed 0 seconds ago)
Average Apply Rate: 39.00 KByte/s
Real Time Query:    OFF
Instance(s):
orcldbs1 (apply instance)
orcldbs2
Database Status:
SUCCESS

DGMGRL> show database orcldbs
Database - orcldbs
Role:               PHYSICAL STANDBY
Intended State:     APPLY-ON
Transport Lag:      0 seconds (computed 0 seconds ago)
Apply Lag:          0 seconds (computed 0 seconds ago)
Average Apply Rate: 39.00 KByte/s
Real Time Query:    OFF
Instance(s):
orcldbs1 (apply instance)
orcldbs2
Database Status:
SUCCESS

The output of above command shows that the MRP process is started on instance1 (orcldbs1) server. You can login to standby Node1 server and check whether MRP is running or not as shown below.
$ ps -ef | grep mrp
oracle   26667     1  0 15:17 ?        00:00:00 ora_mrp0_orcldbs1
oracle   27826 20926  0 15:21 pts/1    00:00:00 /bin/bash -c ps -ef | grep mrp

$ ps -ef | grep mrp
oracle   26667     1  0 15:17 ?        00:00:00 ora_mrp0_orcldbs1
oracle   27826 20926  0 15:21 pts/1    00:00:00 /bin/bash -c ps -ef | grep mrp
Now that the MRP process is running, login to both Primary and Standby database and check whether the logs are in sync or not.

- Dataguard Broker commands
Below are some extra commands which you can use and check status of database.

DGMGRL> VALIDATE DATABASE orcldb;
Database Role:    Primary database
Ready for Switchover:  Yes
Flashback Database Status:
orcldb:  Off

DGMGRL> VALIDATE DATABASE orcldb;
Database Role:    Primary database
Ready for Switchover:  Yes
Flashback Database Status:
orcldb:  Off

DGMGRL> VALIDATE DATABASE orcldbs;
Database Role:     Physical standby database
Primary Database:  orcldb
Ready for Switchover:  Yes
Ready for Failover:    Yes (Primary Running)
Flashback Database Status:
orcldb:   Off
orcldbs:  Off

DGMGRL> VALIDATE DATABASE orcldbs;

Database Role:     Physical standby database
Primary Database:  orcldb
Ready for Switchover:  Yes
Ready for Failover:    Yes (Primary Running)
Flashback Database Status:
orcldb:   Off
orcldbs:  Off
STANDBY DB (192.168.1.12)

SQL> select NAME,DATABASE_ROLE,DATAGUARD_BROKER from v$database;

NAME   DATABASE_ROLE    DATAGUAR
------ ---------------- --------
DELL   PHYSICAL STANDBY ENABLED

SQL> archive log list;
Database log mode              Archive Mode
Automatic archival             Enabled
Archive destination            /u01/app/oracle/DELL/arch
Oldest online log sequence     9
Next log sequence to archive   0
Current log sequence           11


Sunday, February 9, 2020

Node Eviction Overview

Node Eviction Overview


The Oracle Clusterware is designed to perform a node eviction by removing one or more nodes from the cluster if some critical problem is detected.  A critical problem could be a node not responding via a network heartbeat, a node not responding via a disk heartbeat, a hung or severely degraded machine, or a hung ocssd.bin process.  The purpose of this node eviction is to maintain the overall health of the cluster by removing bad members.

Starting in 11.2.0.2 RAC or above (or if you are on Exadata), a node eviction may not actually reboot the machine.  This is called a rebootless restart.  In this case we restart most of the clusterware stack to see if that fixes the unhealthy node.

1.0 - PROCESS ROLES FOR REBOOTS

OCSSD (aka CSS daemon) - This process is spawned by the cssdagent process. It runs in both
vendor clusterware and non-vendor clusterware environments.  OCSSD's primary job is internode health monitoring and RDBMS instance endpoint discovery. The health monitoring includes a network heartbeat and a disk heartbeat (to the voting files).  OCSSD can also evict a node after escalation of a member kill from a client (such as a database LMON process). This is a multi-threaded process that runs at an elevated priority and runs as the Oracle user.

Startup sequence: INIT --> init.ohasd --> ohasd --> ohasd.bin --> cssdagent --> ocssd --> ocssd.bin

CSSDAGENT - This process is spawned by OHASD and is responsible for spawning the OCSSD process, monitoring for node hangs (via oprocd functionality), and monitoring to the OCSSD process for hangs (via oclsomon functionality), and monitoring vendor clusterware (via vmon functionality).  This is a multi-threaded process that runs at an elevated priority and runs as the root user.

Startup sequence: INIT --> init.ohasd --> ohasd --> ohasd.bin --> cssdagent

CSSDMONITOR - This proccess also monitors for node hangs (via oprocd functionality), monitors the OCSSD process for hangs (via oclsomon functionality), and monitors vendor clusterware (via vmon functionality). This is a multi-threaded process that runs at an elevated priority and runs as the root user.

Startup sequence: INIT --> init.ohasd --> ohasd --> ohasd.bin --> cssdmonitor

2.0 - DETERMINING WHICH PROCESS IS RESPONSIBLE FOR A REBOOT
Important files to review:

Clusterware alert log in
The cssdagent log(s)
The cssdmonitor log(s)
The ocssd log(s)
The lastgasp log(s) in /etc/oracle/lastgasp or /var/opt/oracle/lastgasp
CHM or OS Watcher data
opatch lsinventory -detail' output for the GRID home
Messages files

* Messages file locations:

Linux: /var/log/messages
Sun: /var/adm/messages
HP-UX: /var/adm/syslog/syslog.log
IBM: /bin/errpt -a > messages.out

11.2 Clusterware evictions should, in most cases, have some kind of meaningful error in the clusterware alert log.  This can be used to determine which process is responsible for the reboot.  Example message from a clusterware alert log:

[ohasd(11243)]CRS-8011:reboot advisory message from host: sta00129, component: cssagent, with timestamp: L-2009-05-05-10:03:25.340
[ohasd(11243)]CRS-8013:reboot advisory message text: Rebooting after limit 28500 exceeded; disk timeout 27630, network timeout 28500, last heartbeat from CSSD at epoch seconds 1241543005.340, 4294967295 milliseconds ago based on invariant clock value of 93235653

This particular eviction happened when we had hit the network timeout.  CSSD exited and the cssdagent took action to evict. The cssdagent knows the information in the error message from local heartbeats made from CSSD.

If no message is in the evicted node's clusterware alert log, check the lastgasp logs on the local node and/or the clusterware alert logs of other nodes.

3.0 - TROUBLESHOOTING OCSSD EVICTIONS

If you have encountered an OCSSD eviction review common causes in section 3.1 below.

3.1 - COMMON CAUSES OF OCSSD EVICTIONS
Network failure or latency between nodes. It would take 30 consecutive missed checkins (by default - determined by the CSS misscount) to cause a node eviction.
Problems writing to or reading from the CSS voting disk.  If the node cannot perform a disk heartbeat to the majority of its voting files, then the node will be evicted.
A member kill escalation.  For example, database LMON process may request CSS to remove an instance from the cluster via the instance eviction mechanism.  If this times out it could escalate to a node kill.
An unexpected failure or hang of the OCSSD process, this can be caused by any of the above issues or something else.
An Oracle bug.
3.2 - FILES TO REVIEW AND GATHER FOR OCSSD EVICTIONS

All files from section 2.0 from all cluster nodes.  More data may be required.

Example of an eviction due to loss of voting disk:

CSS log:

2012-03-27 22:05:48.693: [ CSSD][1100548416](:CSSNM00018:)clssnmvDiskCheck: Aborting, 0 of 3 configured voting disks available, need 2
2012-03-27 22:05:48.693: [ CSSD][1100548416]###################################
2012-03-27 22:05:48.693: [ CSSD][1100548416]clssscExit: CSSD aborting from thread clssnmvDiskPingMonitorThread

OS messages:

Mar 27 22:03:58 choldbr132p kernel: Error:Mpx:All paths to Symm 000190104720 vol 0c71 are dead.
Mar 27 22:03:58 choldbr132p kernel: Error:Mpx:Symm 000190104720 vol 0c71 is dead.
Mar 27 22:03:58 choldbr132p kernel: Buffer I/O error on device sdbig, logical block 0

4.0 - TROUBLESHOOTING CSSDAGENT OR CSSDMONITOR EVICTIONS

If you have encountered a CSSDAGENT or CSSDMONITOR eviction review common causes in section 4.1 below.

4.1 - COMMON CAUSES OF CSSDAGENT OR CSSDMONITOR EVICTIONS
An OS scheduler problem.  For example, if the OS is getting locked up in a driver or hardware or there is excessive amounts of load on the machine (at or near 100% cpu utilization), thus preventing the scheduler from behaving reasonably.
A thread(s) within the CSS daemon hung.
An Oracle bug.
4.2 - FILES TO REVIEW AND GATHER FOR CSSDAGENT OR CSSDMONITOR EVICTIONS

All files from section 2.0 from all cluster nodes. More data may be required.

Reference metalink Doc ID 1050693.1

Saturday, January 25, 2020

SQL Server Basic Queries

SQL Server Basic Queries


How to See Active SQL Server Connections For Database?

SELECT DB_NAME(dbid) AS DBName, COUNT(dbid) AS NumberOfConnections, loginame FROM    sys.sysprocesses GROUP BY dbid, loginame ORDER BY DB_NAME(dbid);

-- Get Current DatabaseID
SELECT DB_ID() DatabaseID;

-- Get Current DatabaseName
SELECT DB_NAME() DatabaseName;

-- Get DatabaseName from DatabaseID
SELECT DB_NAME(4) DatabaseName;

-- Get DatabaseID from DatabaseName
SELECT DB_ID('tempdb') DatabaseID;

-- Get all DatabaseName and DBID
SELECT name,database_id FROM sys.databases;

SQL Server Basics Commands

SQL Server Basics Commands



How to create a database in SQL Server ?

Creating a new database using the CREATE DATABASE statement
The CREATE DATABASE statement creates a new database. The following shows the minimal syntax of the CREATE DATABASE statement:
CREATE DATABASE database_name;
CREATE DATABASE mqmprod;

Creating a new database using SQL Server Management Studio
First, right-click the Database and choose New Database… menu item.

How to check the database status of SQL Server?

This statement lists all databases in the SQL Server:
SELECT name FROM master.sys.databases ORDER BY name;
(or)
EXEC sp_databases;
(or)
sp_helpdb;

How to connect to a database in SQL Server?

USE database_name;
use mqmprod;

Monday, January 20, 2020

Converting Physical Standby Database to Snapshot Standby Database (Manually)

Converting Physical Standby Database to Snapshot Standby Database (Manually)


Below are the major steps:

Configure the flash recovery area, if it is not already done.

alter system set db_recovery_file_dest_size = 10G;
alter system set db_recovery_file_dest= '/u01/oracleFRA';

Check the status of database before converting:
SQL> select name,status,open_mode,database_role,protection_mode from v$instance,v$database;
NAME      STATUS       OPEN_MODE       DATABASE_ROLE    PROTECTION_MODE
--------- ------------ --------------- ---------------- --------------------
DELL      MOUNTED      MOUNTED         PHYSICAL STANDBY MAXIMUM PERFORMANCE

Stop the recovery MRP process.
alter database recover managed standby database cancel;

Now convert physical standby database to snapshot standby
STANDBY> alter database convert to snapshot standby;
STANDBY> alter database open;

Check the status of database after converting:
SQL> select name,status,open_mode,database_role,protection_mode from v$instance,v$database;
NAME      STATUS       OPEN_MODE       DATABASE_ROLE    PROTECTION_MODE
--------- ------------ --------------- ---------------- --------------------
DELL      OPEN         READ WRITE      SNAPSHOT STANDBY MAXIMUM PERFORMANCE

Do some testing:

SQL> create table dba_objects_bkp as select * from dba_objects;
Table created.
SQL> select count(*) from dba_objects_bkp;
  COUNT(*)
----------
     74510
SQL> insert into dba_objects_bkp select * from dba_objects;
74510 rows created.
SQL> select count(*) from dba_objects_bkp;
  COUNT(*)
----------
    149020

After testing, now again we will convert the snapshot standby database back to a regular physical standby database:

Check the status of database before converting:
SQL> select name,status,open_mode,database_role,protection_mode from v$instance,v$database;
NAME      STATUS       OPEN_MODE       DATABASE_ROLE    PROTECTION_MODE
--------- ------------ --------------- ---------------- --------------------
DELL      OPEN         READ WRITE      SNAPSHOT STANDBY MAXIMUM PERFORMANCE

Now shutdown the standby standby database and open in mount state:
SQL> shut immediate;
SQL> startup mount;

Convert snapshot standby to physical standby database and shutdown the database and open in mount state:
alter database convert to physical standby;
shutdown immediate;
startup mount;

Now start the recovery MRP process
alter database recover managed standby database disconnect from session;

Check the status of database after converting:
SQL> select name,status,open_mode,database_role,protection_mode from v$instance,v$database;
NAME      STATUS       OPEN_MODE       DATABASE_ROLE    PROTECTION_MODE
--------- ------------ --------------- ---------------- --------------------
DELL      MOUNTED      MOUNTED         PHYSICAL STANDBY MAXIMUM PERFORMANCE

During the whole activity alertlog will show the below useful information:

[oracle@rac2 trace]$ tail -f alert_DELL.log
Mon Jan 20 19:31:08 2020
MRP0: Background Media Recovery cancelled with status 16037
Errors in file /u01/app/oracle/diag/rdbms/dell_stby/DELL/trace/DELL_mrp0_5467.trc:
ORA-16037: user requested cancel of managed recovery operation
Managed Standby Recovery not using Real Time Apply
Recovery interrupted!
Recovered data files to a consistent state at change 1017666
MRP0: Background Media Recovery process shutdown (DELL)
Managed Standby Recovery Canceled (DELL)
Completed: alter database recover managed standby database cancel
Mon Jan 20 19:34:23 2020
db_recovery_file_dest_size of 40960 MB is 0.15% used. This is a
user-specified limit on the amount of space that will be used by this
database for recovery-related files, and does not reflect the amount of
space available in the underlying filesystem or ASM diskgroup.
Mon Jan 20 19:40:33 2020
alter database convert to snapshot standby
Created guaranteed restore point SNAPSHOT_STANDBY_REQUIRED_01/20/2020 19:40:33
krsv_proc_kill: Killing 20 processes (all RFS)
Begin: Standby Redo Logfile archival
End: Standby Redo Logfile archival
RESETLOGS after incomplete recovery UNTIL CHANGE 1017666
Resetting resetlogs activation ID 4000706007 (0xee75edd7)
Online log /u01/app/oracle/DELL/redo01.log: Thread 1 Group 1 was previously cleared
Online log /u01/app/oracle/DELL/redo02.log: Thread 1 Group 2 was previously cleared
Online log /u01/app/oracle/DELL/redo03.log: Thread 1 Group 3 was previously cleared
Standby became primary SCN: 1017664
Mon Jan 20 19:40:34 2020
Setting recovery target incarnation to 3
CONVERT TO SNAPSHOT STANDBY: Complete - Database mounted as snapshot standby
Completed: alter database convert to snapshot standby
Mon Jan 20 19:42:30 2020
alter database open
Data Guard Broker initializing...
Data Guard Broker initialization complete
Mon Jan 20 19:42:30 2020
Assigning activation ID 4000911416 (0xee791038)
Thread 1 opened at log sequence 1
  Current log# 1 seq# 1 mem# 0: /u01/app/oracle/DELL/redo01.log
Successful open of redo thread 1
MTTR advisory is disabled because FAST_START_MTTR_TARGET is not set
Mon Jan 20 19:42:30 2020
ARCa: Becoming the 'no SRL' ARCH
Mon Jan 20 19:42:30 2020
ARC9: Becoming the 'no SRL' ARCH
Mon Jan 20 19:42:30 2020
SMON: enabling cache recovery
[5351] Successfully onlined Undo Tablespace 2.
Undo initialization finished serial:0 start:952634 end:952704 diff:70 (0 seconds)
Dictionary check beginning
Mon Jan 20 19:42:30 2020
Dictionary check complete
Verifying file header compatibility for 11g tablespace encryption..
Verifying 11g file header compatibility for tablespace encryption completed
SMON: enabling tx recovery
Re-creating tempfile /u01/app/oracle/DELL/temp01.dbf
Database Characterset is WE8MSWIN1252
No Resource Manager plan active
**********************************************************
WARNING: Files may exists in db_recovery_file_dest
that are not known to the database. Use the RMAN command
CATALOG RECOVERY AREA to re-catalog any such files.
If files cannot be cataloged, then manually delete them
using OS command.
One of the following events caused this:
1. A backup controlfile was restored.
2. A standby controlfile was restored.
3. The controlfile was re-created.
4. db_recovery_file_dest had previously been enabled and
   then disabled.
**********************************************************
replication_dependency_tracking turned off (no async multimaster replication found)
Starting background process QMNC
Mon Jan 20 19:42:31 2020
QMNC started with pid=53, OS id=5978
LOGSTDBY: Validating controlfile with logical metadata
LOGSTDBY: Validation complete
Completed: alter database open
Mon Jan 20 19:42:32 2020
Starting background process CJQ0
Mon Jan 20 19:42:32 2020
CJQ0 started with pid=56, OS id=6006
Mon Jan 20 19:44:25 2020
ARC0: Becoming the 'no SRL' ARCH
Mon Jan 20 19:44:26 2020

Starting and stoping of MRP process:

alter database recover managed standby database
Media Recovery Start: Managed Standby Recovery (DELL)
Serial Media Recovery started
Managed Standby Recovery not using Real Time Apply
Media Recovery Waiting for thread 1 sequence 110 (in transit)
Mon Jan 20 20:49:01 2020
Recovery interrupted!
Media Recovery user canceled with status 1013
alter database recover managed standby database disconnect from session
Attempt to start background Managed Standby Recovery process (DELL)
Mon Jan 20 20:49:23 2020
MRP0 started with pid=56, OS id=7654
MRP0: Background Managed Standby Recovery process started (DELL)
Serial Media Recovery started
Managed Standby Recovery not using Real Time Apply
Waiting for all non-current ORLs to be archived...

alter database recover managed standby database cancel
Mon Jan 20 19:31:08 2020
MRP0: Background Media Recovery cancelled with status 16037
Errors in file /u01/app/oracle/diag/rdbms/dell_stby/DELL/trace/DELL_mrp0_5467.trc:
ORA-16037: user requested cancel of managed recovery operation
Managed Standby Recovery not using Real Time Apply
Recovery interrupted!
Recovered data files to a consistent state at change 1017666
MRP0: Background Media Recovery process shutdown (DELL)
Managed Standby Recovery Canceled (DELL)
Completed: alter database recover managed standby database cancel

Few errors are also captured in alertlog:

Errors in file /u01/app/oracle/diag/rdbms/dell_stby/DELL/trace/DELL_dbw0_5217.trc:
ORA-01157: cannot identify/lock data file 201 - see DBWR trace file
ORA-01110: data file 201: '/u01/app/oracle/DELL/temp01.dbf'
ORA-27037: unable to obtain file status
Linux-x86_64 Error: 2: No such file or directory
Additional information: 3
Errors in file /u01/app/oracle/diag/rdbms/dell_stby/DELL/trace/DELL_dbw0_5217.trc:
ORA-01186: file 201 failed verification tests
ORA-01157: cannot identify/lock data file 201 - see DBWR trace file
ORA-01110: data file 201: '/u01/app/oracle/DELL/temp01.dbf'
File 201 not verified due to error ORA-01157

Tuesday, December 31, 2019

Gather Statistics Commands

Gather Statistics Commands



1. Gather dictionary stats:


EXEC DBMS_STATS.gather_dictionary_stats;
It gathers statistics for dictionary schemas 'SYS', 'SYSTEM' and other internal schemas.


2. Gather fixed object stats:


EXEC DBMS_STATS.GATHER_FIXED_OBJECTS_STATS;
Fixed object means gv$ or v$views


3. Gather full database stats:


EXEC DBMS_STATS.gather_database_stats;

-- With estimate_percent to 15 percent or any other value , if the db size very huge.

EXEC DBMS_STATS.gather_database_stats(estimate_percent => 15);
EXEC DBMS_STATS.gather_database_stats(estimate_percent => 15, cascade => TRUE);

-- With auto sample size and parallel degree

EXEC DBMS_STATS.gather_database_stats(estimate_percent => DBMS_STATS.AUTO_SAMPLE_SIZE,degree => 8);


4. Gather schema statistics:


EXEC DBMS_STATS.gather_schema_stats('QRUM');

EXEC DBMS_STATS.gather_schema_stats('QRUM', estimate_percent => 25);

EXEC DBMS_STATS.gather_schema_stats('QRUM', estimate_percent => 100, cascade => TRUE);

-- STATS WITH AUTO ESTIMATION and degree 8

exec dbms_stats.gather_schema_stats( ownname => 'QRUM',method_opt => 'FOR ALL COLUMNS SIZE 1',
granularity => 'ALL', degree => 8, cascade => TRUE,
estimate_percent=>dbms_stats.auto_sample_size);


5. Gather table statistics: 


EXEC DBMS_STATS.gather_table_stats('DBACLASS', 'EMP');
EXEC DBMS_STATS.gather_table_stats('DBACLASS', 'EMP', estimate_percent => 15);
EXEC DBMS_STATS.gather_table_stats('DBACLASS', 'EMP', estimate_percent => 15, cascade => TRUE);

exec DBMS_STATS.GATHER_TABLE_STATS  (ownname => 'DBACLASS' , tabname => 'EMP',cascade => true,
method_opt=>'for all indexed columns size 1', granularity => 'ALL', degree => 8);

exec DBMS_STATS.GATHER_TABLE_STATS (ownname => 'DBACLASS' , tabname => 'EMP',
cascade => true, method_opt=>'FOR ALL COLUMNS SIZE 1', granularity => 'ALL', degree => 8);


6. Gather stats for single partition of a table:


BEGIN
DBMS_STATS.GATHER_TABLE_STATS (
ownname => 'SCOTT',
tabname => 'TEST', --- TABLE NAME
partname => 'TEST_JAN2016' --- PARTITOIN NAME
method_opt=>'for all indexed columns size 1',
GRANULARITY => 'APPROX_GLOBAL AND PARTITION',
degree => 8);
END;
/


7. Lock/unlock statistics:


-- Lock stats of a schema:
EXEC DBMS_STATS.lock_schema_stats('DBACLASS');

-- Lock stats of a table:
EXEC DBMS_STATS.lock_table_stats('DBACLASS', 'EMP');

-- Lock stats of a partition:
EXEC DBMS_STATS.lock_partition_stats('DBACLASS', 'EMP', 'EMP');

-- unlock stats of a schema:

EXEC DBMS_STATS.unlock_schema_stats('DBACLASS');
-- unlock stats of a table:

EXEC DBMS_STATS.unlock_table_stats('DBACLASS', 'DBACLASS');
--unlock stats of a partition:

EXEC DBMS_STATS.unlock_partition_stats('DBACLASS', 'EMP', 'TEST_JAN2016');

--- check stats status:

SELECT stattype_locked FROM dba_tab_statistics WHERE table_name = 'TEST' and owner = 'SCOTT';


8 . Delete statistics:


-- Delete complete db statistics:
EXEC DBMS_STATS.delete_database_stats;

-- Delete schema statistics:
EXEC DBMS_STATS.delete_schema_stats('DBACLASS');

-- Delete table statistics:
EXEC DBMS_STATS.delete_table_stats('DBACLASS', 'EMP');

-- Delete column statistics:
EXEC DBMS_STATS.delete_column_stats('DBACLASS', 'EMP', 'EMPNO');

-- Delete index statistics:

EXEC DBMS_STATS.delete_index_stats('DBACLASS', 'EMP_PK');

-- Delete dictionary statistics:
EXEC DBMS_STATS.delete_dictionary_stats;


-- Delete fixed object statistics:

exec dbms_stats.delete_fixed_objects_stats;

-- Delete system statistics:

exec dbms_stats.delete_system_stats('STAT_TAB');


8. Setting statistics preference:


-- View preference details for the database:

SELECT dbms_stats.get_prefs('PUBLISH') EST_PCT FROM dual;

-- View Publish preference for table


-- View Publish preference for schema:

select dbms_stats.get_prefs('PUBLISH', 'SCOTT') from dual

-- View preference details for table

select dbms_stats.get_prefs(ownname=>'DBACLASS',tabname=>'EMP',pname=>'PUBLISH') FROM DUAL;
select  DBMS_STATS.get_prefs(ownname=>'DBACLASS',tabname=>'EMP',pname=>'INCREMENTAL') FROM DUAL;
select  DBMS_STATS.get_prefs(ownname=>'DBACLASS',tabname=>'EMP',pname=>'GRANULARITY') FROM DUAL;
select  DBMS_STATS.get_prefs(ownname=>'DBACLASS',tabname=>'EMP',pname=>'STALE_PERCENT')  FROM DUAL;
select   DBMS_STATS.get_prefs(ownname=>'DBACLASS',tabname=>'EMP',pname=>'ESTIMATE_PERCENT')  FROM DUAL;
select   DBMS_STATS.get_prefs(ownname=>'DBACLASS',tabname=>'EMP',pname=>'DEGREE')  FROM DUAL;

-- Set table  preferences

exec dbms_stats.set_table_prefs('DBACLASS','EMP','PUBLISH','FALSE');
exec dbms_stats.set_table_prefs('DBACLASS','EMP','ESTIMATE_PERCENT','20');
exec dbms_stats.set_table_prefs('DBACLASS','EMP','DEGREE','8');

-- Set schema preferences:

exec dbms_stats.SET_SCHEMA_PREFS('DBATEST','PUBLISH','FALSE');
exec dbms_stats.SET_SCHEMA_PREFS('DBATEST','ESTIMATE_PERCENT','20');
exec dbms_stats.SET_SCHEMA_PREFS('DBATEST','CASCADE','TRUE');

-- Set database preference:

exec dbms_stats.set_database_prefs('PUBLISH', 'TRUE');
exec dbms_stats.set_database_prefs('DEGREE', '16');

-- Set global preference:

exec dbms_stats.set_global_prefs('PUBLISH', 'TRUE');
exec dbms_stats.set_global_prefs('DEGREE', '16');


9 . Deleting preferences:


-- Deleting schema preference:

exec dbms_stats.delete_schema_prefs('DBACLASS', 'DEGREE');
exec dbms_stats.delete_schema_prefs('DBACLASS', 'CASCADE');


-- Delete database preference:
exec dbms_stats.delete_database_prefs('ESTIMATE_PERCENT', FALSE);
exec dbms_stats.delete_database_prefs('DEGREE', FALSE);


10 . Publish pending statistics:


-- For schema DBACLASS
exec dbms_stats.publish_pending_stats('DBACLASS',null);

-- For table DBACLASS.EMP
EXEC DBMS_STATS.PUBLISH_PENDING_STATS ('DBACLASS','EMP');


11. Delete pending statistics:


-- for table DBACLASS.EMP
exec dbms_stats.delete_pending_stats('DBACLASS', 'EMP');

-- For schema DBACLASS
exec dbms_stats.delete_pending_stats('DBACLASS', null);


12. Upgrade stats table:


----- If we are importing stats table from higher version to lower version,
then before importing in the database, we need to upgrade the stats table.


EXECUTE DBMS_STATS.UPGRADE_STAT_TABLE(OWNNAME =>'RAJ',STATTAB =>'STAT_TEST');


13. View/modify statistics retention period:


-- View current stats retention

select dbms_stats.get_stats_history_retention from dual;

-- Modify the stats retention

exec DBMS_STATS.ALTER_STATS_HISTORY_RETENTION(60);


14. create stats table:


--- Create staging table to store the statistics data

exec dbms_stats.create_stat_table(ownname => 'SCOTT', stattab => 'STAT_BACKUP',tblspace=>'USERS');


15. Export stats data:


-- Export full database stats to a table SCOTT.STAT_BACKUP

exec dbms_stats.export_database_stats(statown => 'SCOTT' ,stattab=>'STAT_BACKUP');

-- Export stats for table DBACLASS.EMP to a stats table SCOTT.STAT_BACKUP

exec dbms_stats.export_table_stats(ownname=>'DBACLASS', tabname=>'EMP', statown =>'SCOTT',stattab=>'STAT_BACKUP', cascade=>true);

-- Export stats for schema DBACLASS to a stats table SCOTT.STAT_BACKUP

exec dbms_stats.export_schema_stats(ownname=>'DBACLASS', statown =>'SCOTT' , stattab=>'STAT_BACKUP');

-- Export fixed object stats to table SCOTT.STAT_BACKUP

exec dbms_stats.export_fixed_objects_stats(statown => 'SCOTT' ,stattab=>'STAT_BACKUP');

-- Export dictionary stats to table SCOTT.STAT_BACKUP

exec dbms_stats.export_dictionary_stats(statown => 'SCOTT' ,stattab=>'STAT_BACKUP');

-- Export stats for index DBACLAS.EMP_UK1 to SCOTT.STAT_BACKUP table

exec dbms_stats.export_index_stats(ownname=>'DBACLASS', indname=>'EMP_UK1', statown =>'SCOTT',stattab=>'STAT_BACKUP')


16. Import stats table data:


-- Import full database stats from stats table SCOTT.STAT_BACKUP

exec dbms_stats.import_database_stats(statown => 'SCOTT' ,stattab=>'STAT_BACKUP');

-- Import stats for table DBACLASS.EMP from stats table SCOTT.STAT_BACKUP

exec dbms_stats.import_table_stats(ownname=>'DBACLASS', tabname=>'EMP', statown =>'SCOTT',stattab=>'STAT_BACKUP', cascade=>true);

-- Import stats for schema DBACLASS from  stats table SCOTT.STAT_BACKUP

exec dbms_stats.import_schema_stats(ownname=>'DBACLASS', statown =>'SCOTT' , stattab=>'STAT_BACKUP');

-- Import fixed object stats from stats table SCOTT.STAT_BACKUP

exec dbms_stats.import_fixed_objects_stats(statown => 'SCOTT' ,stattab=>'STAT_BACKUP');

-- Import dictionary stats from  table SCOTT.STAT_BACKUP

exec dbms_stats.import_dictionary_stats(statown => 'SCOTT' ,stattab=>'STAT_BACKUP');

-- Import stats for index DBACLAS.EMP_UK1 from  SCOTT.STAT_BACKUP table

exec dbms_stats.import_index_stats(ownname=>'DBACLASS', indname=>'EMP_UK1', statown =>'SCOTT',stattab=>'STAT_BACKUP');


17 . Few stats related sql queries:


-- Check stale stats for table:

select owner,table_name,STALE_STATS from dba_tab_statistics where owner='&SCHEMA_NAME' and table_name='&TABLE_NAME';

--Check stale stats for index:

select owner,INDEX_NAME,TABLE_NAME from DBA_IND_STATISTICS where owner='&SCHEMA_NAME' and index_name='&INDEX_NAME';

-- For getting history of TABLE statistics
setlines 200
col owner for a12
col table_name for a21
select owner,TABLE_NAME,STATS_UPDATE_TIME from dba_tab_stats_history where table_name='&TABLE_NAME';

-- Space used to store statistic data in SYSAUX tablespace:

SQL> select occupant_desc, space_usage_kbytes from v$sysaux_occupants where OCCUPANT_DESC like '%Statistics%';

-- Check whether table stats locked or not:

select owner, table_name, stattype_locked from dba_tab_statistics where stattype_locked is not null and owner not in ('SYS','SYSTEM');