Oracle SQL Tuning Advisor

This is very useful :

Snapper and this  SQLd360, SQL diagnostics collection made faster

Great site on how to use the tuning advisor :

https://thehelpfuldba.com/index.php/2018/01/24/instructions-to-run-the-sql-tuning-advisor/

but as websites have a nasty way of disappearing :


 Findings and Recommendations
          ----------------------------
 
Finding 1: Top SQL Statements
Impact is .22 active sessions, 95% of total activity.
-----------------------------------------------------
SQL statements consuming significant database time were found. These
statements offer a good opportunity for performance improvement.
 
   Recommendation 1: SQL Tuning
   Estimated benefit is .22 active sessions, 95% of total activity.
   ----------------------------------------------------------------
   Action
      Run SQL Tuning Advisor on the SELECT statement with SQL_ID
      "gbwan1836hj3c".
      Related Object
         SQL statement with SQL_ID gbwan1836hj3c.
         SELECT time_key + (:"SYS_B_00" / :"SYS_B_01") period,
         in_value,
         out_value
         FROM  (SELECT time_key,

Create an SQL Tuning task as follows:

DECLARE
  l_sql_tune_task_id  VARCHAR2(100);
BEGIN
  l_sql_tune_task_id := DBMS_SQLTUNE.create_tuning_task (
                          sql_id      => 'gbwan1836hj3c',
                          scope       => DBMS_SQLTUNE.scope_comprehensive,
                          time_limit  => 500,
                          task_name   => 'gbwan1836hj3c_tuning_task',
                          description => 'Tuning task1 for statement gbwan1836hj3c');
  DBMS_OUTPUT.put_line('l_sql_tune_task_id: ' || l_sql_tune_task_id);
END;
/

Run the tuning task

EXEC DBMS_SQLTUNE.execute_tuning_task(task_name => 'gbwan1836hj3c_tuning_task');

The above will take a couple of minutes. Depending on the complexity of the query, the time_limit may need to be increased.

After the task is complete, query the output:

set long 65536 set longchunksize 65536 set linesize 100
select dbms_sqltune.report_tuning_task('gbwan1836hj3c_tuning_task11') from dual;

Patch 29314339 - Database Apr 2019 Release Update 12.2.0.1.190416

Quick notes on applying latest Oracle Patch on standalone database

This post is superseded - see this link:

https://www.durham.computer/2019/06/oracle-psu-patch.html

NB - This patch is not to be installed to an environment that has a Grid Infrastructure (GI) home. Please refer to the following My Oracle Support Document 756671.1 to determine the appropriate Grid Infrastructure patch to be installed.

Ensure OPatch is a supported version and run opatch from the Oracle Home using the directory where the latest patch has been applied

i.e.

$ cd /u01/software/patch_apr2019/29314339

$ /u01/app/oracle/product/12.2.0.1/dbhome_1/OPatch/opatch apply

Oracle Interim Patch Installer version 12.2.0.1.17
Copyright (c) 2019, Oracle Corporation. All rights reserved.

Oracle Home : /u01/app/oracle/product/12.2.0.1/dbhome_1


Central Inventory : /u01/app/oraInventory
from : /u01/app/oracle/product/12.2.0.1/dbhome_1/oraInst.loc


OPatch version : 12.2.0.1.17
OUI version : 12.2.0.1.4
Log file location : /u01/app/oracle/product/12.2.0.1/dbhome_1/cfgtoollogs/opatch/opatch2019-05-09_13-23-27PM_1.log

Verifying environment and performing prerequisite checks...
Prerequisite check "CheckActiveFilesAndExecutables" failed.
The details are:

Following active executables are not used by opatch process :


/u01/app/oracle/product/12.2.0.1/dbhome_1/lib/libskgxp12.so
/u01/app/oracle/product/12.2.0.1/dbhome_1/bin/oracle

Following active executables are used by opatch process :

UtilSession failed: Prerequisite check "CheckActiveFilesAndExecutables" failed.
Log file location: /u01/app/oracle/product/12.2.0.1/dbhome_1/cfgtoollogs/opatch/opatch2019-05-09_13-23-27PM_1.log

OPatch failed with error code 73



This was because we had an oracle database running, so we shutdown the database and ran the prereq which should have been ran in the first place :

/u01/app/oracle/product/12.2.0.1/dbhome_1/OPatch/opatch prereq CheckActiveFilesAndExecutables -ph ./
Oracle Interim Patch Installer version 12.2.0.1.17
Copyright (c) 2019, Oracle Corporation. All rights reserved.

PREREQ session

Oracle Home : /u01/app/oracle/product/12.2.0.1/dbhome_1
Central Inventory : /u01/app/oraInventory
from : /u01/app/oracle/product/12.2.0.1/dbhome_1/oraInst.loc
OPatch version : 12.2.0.1.17
OUI version : 12.2.0.1.4
Log file location : /u01/app/oracle/product/12.2.0.1/dbhome_1/cfgtoollogs/opatch/opatch2019-05-09_13-48-08PM_1.log

Invoking prereq "checkactivefilesandexecutables"

Prereq "checkActiveFilesAndExecutables" for patch 29314339 passed.

OPatch succeeded.


Now able to run the patch

/u01/app/oracle/product/12.2.0.1/dbhome_1/OPatch/opatch apply
Oracle Interim Patch Installer version 12.2.0.1.17
Copyright (c) 2019, Oracle Corporation. All rights reserved.

Oracle Home : /u01/app/oracle/product/12.2.0.1/dbhome_1
Central Inventory : /u01/app/oraInventory
from : /u01/app/oracle/product/12.2.0.1/dbhome_1/oraInst.loc
OPatch version : 12.2.0.1.17
OUI version : 12.2.0.1.4
Log file location : /u01/app/oracle/product/12.2.0.1/dbhome_1/cfgtoollogs/opatch/opatch2019-05-09_13-43-05PM_1.log

Verifying environment and performing prerequisite checks...
OPatch continues with these patches: 29314339

Do you want to proceed? [y|n]
y
User Responded with: Y
All checks passed.

Please shutdown Oracle instances running out of this ORACLE_HOME on the local system.
(Oracle Home = '/u01/app/oracle/product/12.2.0.1/dbhome_1')


Is the local system ready for patching? [y|n]
y
User Responded with: Y
Backing up files...
Applying interim patch '29314339' to OH '/u01/app/oracle/product/12.2.0.1/dbhome_1'
ApplySession: Optional component(s) [ oracle.has.crs, 12.2.0.1.0 ] , [ oracle.network.cman, 12.2.0.1.0 ] , [ oracle.ons.daemon, 12.2.0.1.0 ] , [ oracle.oid.client, 12.2.0.1.0 ] not present in the Oracle Home or a higher version is found.

Patching component oracle.rdbms.util, 12.2.0.1.0...

Patching component oracle.precomp.rsf, 12.2.0.1.0...

Patching component oracle.rdbms.rsf.ic, 12.2.0.1.0...


....etc

Patching component oracle.sdo, 12.2.0.1.0...

Patch 29314339 successfully applied.

Log file location: /u01/app/oracle/product/12.2.0.1/dbhome_1/cfgtoollogs/opatch/opatch2019-05-09_13-43-05PM_1.log

OPatch succeeded.


Startup the database and apply the datapach as per the README.html in the patch directory.

Load Modified SQL Files into the Database

[oracle@ol7-122-dg1 OPatch]$ ./datapatch -verbose

SQL Patching tool version 12.2.0.1.0 Production on Thu May 9 13:51:46 2019
Copyright (c) 2012, 2019, Oracle. All rights reserved.

Log file for this invocation: /u01/app/oracle/cfgtoollogs/sqlpatch/sqlpatch_10215_2019_05_09_13_51_46/sqlpatch_invocation.log

Connecting to database...OK
Bootstrapping registry and package to current versions...done
Determining current state...done

Current state of SQL patches:
Bundle series DBRU:
ID 190416 in the binary registry and not installed in the SQL registry

Adding patches to installation queue and performing prereq checks...
Installation queue:
Nothing to roll back
The following patches will be applied:
29314339 (DATABASE APR 2019 RELEASE UPDATE 12.2.0.1.190416)

Installing patches...


Please refer to MOS Note 1609718.1 and/or the invocation log
/u01/app/oracle/cfgtoollogs/sqlpatch/sqlpatch_10215_2019_05_09_13_51_46/sqlpatch_invocation.log
for information on how to resolve the above errors.
SQL Patching tool complete on Thu May  9 13:53:29 2019

SQL> select patch_id, status, description from dba_registry_sqlpatch
  2  /
  PATCH_ID STATUS
---------- -------------------------
DESCRIPTION
--------------------------------------------------------------------------------
  29314339 BEGIN
DATABASE APR 2019 RELEASE UPDATE 12.2.0.1.190416


Please check for any invalid objects and run ultrp as per the readme if you have any.

Clearing down archive logs / audit / trace files (RMAN and o/s level)

A very quick script to clear down rman archive logs over 4 days - crontab entry to run 10pm every day


*NB* The 'sysdate' command below - when using cut&paste from Windows to Unix may fail as the single quote changes when pasting into Linux - please check.

[root@ora01 oracle]# cat rman_arch_del.sh

export ORACLE_HOME=/u01/app/oracle/product/12.2.0
export ORACLE_SID=db01
export PATH=$ORACLE_HOME/bin:$PATH


delbackup () {
rman log=/home/oracle/arch_del.log << EOF
connect target /
DELETE noprompt ARCHIVELOG ALL COMPLETED BEFORE ‘sysdate-4’;
CROSSCHECK ARCHIVELOG ALL;
DELETE EXPIRED ARCHIVELOG ALL;
exit
EOF
}
# Main
delbackup



We can delete the archivelogs by force using the following command "sledge hammer" approach

RMAN > delete noprompt force archivelog all;


[root@ora01 oracle]# crontab -l

00 22 * * * su - oracle -c "/home/oracle/rman_arch_del.sh" > /tmp/rmanarch.log


+++++++++++++++++++

At unix level run :

NLS_DATE_FORMAT='DD-MON-YYYY HH24:MI:SS'; export NLS_DATE_FORMAT

prior to running rman to output date/time in required format.


######  Clearing down old  RMAN / rman logs
From wthin rman :

crosscheck backup;
crosscheck archivelog all;
delete expired backup;
list copy of archivelog all;
delete obsolete recovery window of 14 days;
delete expired archivelog all;
report obsolete;
delete obsolete;
list backup;


++++++++++++++++++++++

A slightly more expanded version :

#!/bin/bash
# del_arch_no_backup.sh  Use this script to "cleanly" remove archivelogs when not
# backing up the database.
# Usage: del_arch_no_backup.sh sid num_of_days_to_keep

declare rman_ctl="/tmp/rman_ctl.ctl"
if [[ "$#" = 2 ]]; then
   declare sid=$1
   declare -i num_days=$2
else
   echo "usage: del_arch_no_backup.sh sid num_of_days_to_keep"
   exit 1
fi

if [[ ${ORACLE_HOME} = '' ]]; then
        echo "ORACLE_HOME is not set"
        exit 1
fi

# Check if DB is running
if ! `ps -ef|grep pmon|grep -q ${sid}`; then
   echo "Not a running database: ${sid}"
   echo "usage: del_arch_no_backup.sh sid num_of_days_to_keep"
fi

# Must keep at least one of day of archivelogs
if [[ ${num_days} < 1 ]]; then
   echo "Not a valid number of days"
   echo "usage: del_arch_no_backup.sh sid num_of_days_to_keep"
   exit 1
fi

echo "connect target" >${rman_ctl}
echo "delete archivelog all completed before 'sysdate-${num_days}';" >>${rman_ctl}
echo "crosscheck archivelog all;" >>${rman_ctl}
$ORACLE_HOME/bin/rman @${rman_ctl} >/dev/null

rm ${rman_ctl}
exit 0


Script to clean up oracle audit files :

[oracle@scripts]$ cat clean_oracle_audit_files.sh

#!/bin/bash
#
# This shell script will dynamically find and remove Oracle audit files after a given number of days.
# This shell script will work on any uncommented entries in the oratab file, including RAC instances,
# ASM and MGMTDB instances.
#
# usage: clean_oracle_audit_files.sh full_path_to_oratab number_of_days_to_keep
#

if [[ "$#" = 2 ]]; then
   declare ora_tab=$1
   declare -i num_days=$2
else
   echo "usage: clean_oracle_audit_files.sh full_path_to_oratab num_of_days_to_keep"
   exit 1
fi

if [[ !(-f ${ora_tab}) ]]; then
   echo "Not a valid ora_tab path/filename"
   echo "usage: clean_oracle_audit_files.sh full_path_to_oratab num_of_days_to_keep"
   exit 1
fi

if [[ ${num_days} < 1 ]]; then
   echo "Not a valid number of days"
   echo "usage: clean_oracle_audit_files.sh full_path_to_oratab num_of_days_to_keep"
   exit 1
fi

get_instance_name()
{
#Get all instances including RAC
local sid=$1
ps -eo args|grep pmon|grep $sid|sort -u
}

get_audit_home()
{
$ORACLE_HOME/bin/sqlplus -s / as sysdba <<EOF
set pages 0
set head off
set feed off
select value from v\$parameter where name = 'audit_file_dest';
EOF
}

while read -r line
do
   test_char=${line:0:1}
   if [[ "$test_char" != "#" && "$test_char" != "" && "$test_char" != " " ]]; then
      IFS=':' read sid ora_home rest <<< "$line"
      inst_name=$(get_instance_name $sid)
      inst_name=${inst_name:9}
      if [[ "$inst_name" != "" ]]; then #Skip non-running databases
         declare -x ORACLE_HOME=${ora_home}
         declare -x ORACLE_SID=${inst_name}
         audit_dest=$(get_audit_home);
         find ${audit_dest}/ -daystart -mtime +${num_days} -exec rm {} \;
      fi
   fi
done < "${ora_tab}"


Script to clean up trace files :


[oracle@scripts]$ cat clean_oracle_trace_files.sh
#!/bin/bash
#
# This shell script will dynamically find and remove Oracle trace files after a given number of days.
# This shell script will work on any uncommented entries in the oratab file, including RAC instances,
# ASM and MGMTDB instances.
# Updated to include xml files in alert directory.
#
# usage: clean_oracle_trace_files.sh full_path_to_oratab number_of_days_to_keep
#

if [[ "$#" = 2 ]]; then
   declare ora_tab=$1
   declare -i num_days=$2
else
   echo "usage: clean_oracle_trace_files.sh full_path_to_oratab num_of_days_to_keep"
   exit 1
fi

if [[ !(-f ${ora_tab}) ]]; then
   echo "Not a valid ora_tab path/filename"
   echo "usage: clean_oracle_trace_files.sh full_path_to_oratab num_of_days_to_keep"
   exit 1
fi

if [[ ${num_days} < 1 ]]; then
   echo "Not a valid number of days"
   echo "usage: clean_oracle_trace_files.sh full_path_to_oratab num_of_days_to_keep"
   exit 1
fi

get_instance_name()
{
#Get all instances including RAC
local sid=$1
ps -eo args|grep pmon|grep $sid|sort -u
}

get_trace_home()
{
$ORACLE_HOME/bin/sqlplus -s / as sysdba <<EOF
set pages 0
set head off
set feed off
select value from v\$diag_info where name = 'Diag Trace';
EOF
}

get_alert_home()
{
$ORACLE_HOME/bin/sqlplus -s / as sysdba <<EOF
set pages 0
set head off
set feed off
select value from v\$diag_info where name = 'Diag Alert';
EOF
}

while read -r line
do
   test_char=${line:0:1}
   if [[ "$test_char" != "#" && "$test_char" != "" && "$test_char" != " " ]]; then
      IFS=':' read sid ora_home rest <<< "$line"
      inst_name=$(get_instance_name $sid)
      inst_name=${inst_name:9}
      if [[ "$inst_name" != "" ]]; then #Skip non-running databases
         declare -x ORACLE_HOME=${ora_home}
         declare -x ORACLE_SID=${inst_name}
         trace_dest=$(get_trace_home);
         alert_dest=$(get_alert_home);
         find ${trace_dest}/ -daystart -mtime +${num_days} -exec rm {} \;
         find ${alert_dest}/ -daystart -mtime +${num_days} -exec rm {} \;
      fi
   fi
done < "${ora_tab}"
[oracle@usze2qmbtora01 scripts]$





## Log in to rman and show configuration items

RMAN> show all
2> ;

RMAN configuration parameters for database with db_unique_name ORADB01 are:

CONFIGURE RETENTION POLICY TO REDUNDANCY 1; # default
CONFIGURE BACKUP OPTIMIZATION OFF; # default
CONFIGURE DEFAULT DEVICE TYPE TO DISK; # default
CONFIGURE CONTROLFILE AUTOBACKUP ON; # default
CONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE DISK TO '%F'; # default
CONFIGURE DEVICE TYPE DISK PARALLELISM 1 BACKUP TYPE TO BACKUPSET; # default
CONFIGURE DATAFILE BACKUP COPIES FOR DEVICE TYPE DISK TO 1; # default
CONFIGURE ARCHIVELOG BACKUP COPIES FOR DEVICE TYPE DISK TO 1; # default
CONFIGURE MAXSETSIZE TO UNLIMITED; # default
CONFIGURE ENCRYPTION FOR DATABASE OFF; # default
CONFIGURE ENCRYPTION ALGORITHM 'AES128'; # default
CONFIGURE COMPRESSION ALGORITHM 'BASIC' AS OF RELEASE 'DEFAULT' OPTIMIZE FOR LOAD TRUE ; # default
CONFIGURE RMAN OUTPUT TO KEEP FOR 7 DAYS; # default
CONFIGURE ARCHIVELOG DELETION POLICY TO NONE; # default
CONFIGURE SNAPSHOT CONTROLFILE NAME TO '/u01/app/oracle/product/12.2.0.1/dbhome_1/dbs/snapcf_emrep.f'; # default

## Currently archivelog deletion policy is set to none - so we can delete the archivelogs

RMAN> delete archivelog all;

released channel: ORA_DISK_1
allocated channel: ORA_DISK_1
channel ORA_DISK_1: SID=269 device type=DISK
List of Archived Log Copies for database with db_unique_name EMREP
=====================================================================

Key Thrd Seq S Low Time
------- ---- ------- - ---------
1 1 5 A 10-JUN-19
Name: /u01/oradata/recovery/EMREP/archivelog/2019_06_10/o1_mf_1_5_ghw4xs8r_.arc

2 1 6 A 10-JUN-19
Name: /u01/oradata/recovery/EMREP/archivelog/2019_06_10/o1_mf_1_6_ghw4xyx4_.arc

Do you really want to delete the above objects (enter YES or NO)? NO

## Change the parameter so the logs have to be backed up at least once.

RMAN> CONFIGURE ARCHIVELOG DELETION POLICY TO BACKED UP 1 TIMES TO DISK;

new RMAN configuration parameters:
CONFIGURE ARCHIVELOG DELETION POLICY TO BACKED UP 1 TIMES TO DISK;
new RMAN configuration parameters are successfully stored

RMAN> delete archivelog all;

released channel: ORA_DISK_1
allocated channel: ORA_DISK_1
channel ORA_DISK_1: SID=269 device type=DISK

RMAN-08138: warning: archived log not deleted - must create more backups

archived log file name=/u01/oradata/recovery/archivelog/2019_06_10/o1_mf_1_5_ghw4xs8r_.arc thread=1 sequence=5

RMAN-08138: warning: archived log not deleted - must create more backups

archived log file name=/u01/oradata/recovery/archivelog/2019_06_10/o1_mf_1_6_ghw4xyx4_.arc thread=1 sequence=6
## Logs won't delete so we change it the policy back to default.

RMAN> CONFIGURE ARCHIVELOG DELETION POLICY TO NONE;

old RMAN configuration parameters:
CONFIGURE ARCHIVELOG DELETION POLICY TO BACKED UP 1 TIMES TO DISK;
new RMAN configuration parameters:
CONFIGURE ARCHIVELOG DELETION POLICY TO NONE;
new RMAN configuration parameters are successfully stored

RMAN> delete archivelog all;

released channel: ORA_DISK_1
allocated channel: ORA_DISK_1
channel ORA_DISK_1: SID=269 device type=DISK
List of Archived Log Copies for database with db_unique_name ORADB01
=====================================================================

Key Thrd Seq S Low Time
------- ---- ------- - ---------
1 1 5 A 10-JUN-19
Name: /u01/oradata/recovery/EMREP/archivelog/2019_06_10/o1_mf_1_5_ghw4xs8r_.arc

2 1 6 A 10-JUN-19
Name: /u01/oradata/recovery/EMREP/archivelog/2019_06_10/o1_mf_1_6_ghw4xyx4_.arc

Do you really want to delete the above objects (enter YES or NO)?

Enter YES and et voilla.

Now put the policy back to it's original value.

The easier option is to use :

RMAN > delete noprompt force archivelog all;