Bajwa Consulting Need senior Oracle DBA help? Performance tuning, Cloud migrations, GoldenGate, backup and DR. Plus 70+ free DBA scripts.
Visit bajwaconsulting.com →

Friday, April 25, 2014

Scheduling Jobs with DBMS_SCHEDULER


1.  user that wants to use dbms_scheduler must have scheduler_admin role.

2.  Here is an example of how to schedule a job using dbms_scheduler (11g replacement of dbms_job)

set serveroutput on
set timing on
set feedback on

A. Create a Schedule
begin
dbms_scheduler.drop_schedule('WORK_HOURS');
end;
/

begin
dbms_scheduler.create_schedule
(schedule_name => 'WORK_HOURS',
start_date=>sysdate,
repeat_interval=>'FREQ=DAILY; BYDAY=MON,TUE,WED,THU,FRI; BYHOUR=8,9,10,11,12,13,14,15,16,17,19;',
comments=>'Run during work hours daily');
END;
/

B. Create a Program
begin
dbms_scheduler.create_program
(program_name=> 'PROG_COLLECT_GC_TRAFFIC',
program_type=> 'STORED_PROCEDURE',
program_action=> 'CAP_GC_TRAFFIC',
enabled=>true,
comments=>'Procedure to collect Global Cache traffic information'
);
end;
/

C. Create and Schedule Job using the program and scheduler created above.
begin
dbms_scheduler.create_job
  (job_name => 'JOB_COLLECT_GC_DATDA',
   program_name=> 'PROG_COLLECT_GC_TRAFFIC',
   schedule_name=>'WORK_HOURS',
   enabled=>true,
   auto_drop=>false,
 comments=>'Job to collect data about GC on top of work hour');
end;
/

Oracle Access Control List configuration for Operating System Services

Anytime you want to use UTL_SMTP, DBMS_LDAP, UTL_HTTP anything that is depending upon the usage of operating systems network (email, web, ldap), etc.  You need to do

 
1.       Make sure that XDB database option is installed.
2.       Do the following for each schema
 

Create the ACL as sysdba

begin
 dbms_network_acl_admin.create_acl (
 acl => 'mailserver_acl.xml',
 description => 'ACL for user to connect to my SMTP Server',
 principal => 'MY_DB_USER',
 is_grant => TRUE,
 privilege => 'connect');
end;
/
commit;

Assign the ACL

begin
 dbms_network_acl_admin.assign_acl (
 acl => 'mailserver_acl.xml',
 host => 'smtp.mycompany.com',
 lower_port => 25);
end;
/
commit;
 

Add a privilege to grant/deny

begin
 dbms_network_acl_admin.add_privilege (
 acl => 'mailserver_acl.xml',
 principal => 'MY_DB_USER',
 is_grant => TRUE,
 privilege => 'connect');
end;
/
commit;

Check Database block corruption

Oracle database blocks can be marked as Corrupted by Oracle., in order to check if you have any corrupted blocks.


1. Run this rman script that will go through all database blocks and verify them.


RMAN target /

RMAN>
run {
# set disk to be default device type
CONFIGURE DEFAULT DEVICE TYPE TO DISK;
# number of concurrent sessions to spawn
CONFIGURE DEVICE TYPE DISK PARALLELISM 10 BACKUP TYPE TO BACKUPSET;
# check datafiles for corruption 10 datafiles in each session
BACKUP VALIDATE CHECK LOGICAL DATABASE FILESPERSET=10;
}

2. Run this query to see if any of the database blocks were marked as corrupted.


select * from v$database_block_corruption;

How to configure the DBCONSOLE manually

create the password file for both ASM and database binaries

orapwd file=orapwORACLE_SID password=PASSWORD
 

Make sure that this directory is writeable by the ORACLE user

/opt/oracle/app/product/cfgtoollogs/emca
 

Run this command from the database binaries (not ASM), pick the correct options.

emca -config dbcontrol db -repos create
----
 
You have specified the following settings
Database ORACLE_HOME ................ /opt/oracle/app/product/oracle/11.2.0
Local hostname ................ myhostname.mydomain.type
Listener ORACLE_HOME ................ /opt/oracle/app/product/grid/11.2.0
Listener port number ................ 1534
Database SID ................ PROD
Email address for notifications ...............
Outgoing Mail (SMTP) server for notifications ...............
ASM ORACLE_HOME ................ /opt/oracle/app/product/grid/11.2.0
ASM SID ................ +ASM
ASM port ................ 1521
ASM user role ................ SYSDBA
ASM username ................ ASMSNMP
----

start/stop the console by running

emctl start/stop dbconsole.
 

drop the enterprise manager repository

emca -deconfig dbcontrol db -repos drop

ACFS file system configuration

Oracle ACFS Snapshot Feature to backup/restore

ASM:

Oracle ASM is a volume manager and a file system for Oracle database files that supports single-instance Oracle Database and Oracle Real Application Clusters (Oracle RAC) configurations. Oracle ASM is Oracle's recommended storage management solution that provides an alternative to conventional volume managers, file systems, and raw devices.

Oracle ASM uses disk groups to store data files; an Oracle ASM disk group is a collection of disks that Oracle ASM manages as a unit. Within a disk group, Oracle ASM exposes a file system interface for Oracle database files. The content of files that are stored in a disk group is evenly distributed to eliminate hot spots and to provide uniform performance across the disks. The performance is comparable to the performance of raw devices.

 

ACFS:

Oracle Automatic Storage Management Cluster File System (Oracle ACFS) is a multi-platform, scalable file system, and storage management technology that extends Oracle Automatic Storage Management (Oracle ASM) functionality to support files maintained outside of the Oracle Database. Oracle ACFS supports many database and application files, including executables, database trace files, database alert logs, application reports, BFILEs, and configuration files. Other supported files are video, audio, text, images, engineering drawings, and other general-purpose application file data.

ACFS – Advantages

  • cluster file system on top of ASM and ADVM
  • as available as ASM is (inherits storage from ASM disk group and ADVM volume)
  • Supports storage of files which cannot be directly stored in ASM, i.e.
    • executables
    • trace files
    • log files
    • …
    • Supports even oracle database binary installations
  • On ACFS read-only Snapshots can be created
  • dynamically resize able Usable across platforms

 

ADVM:

ADVM – Advantages

  • Integrated in ASM.
  • Inherits storage from ASM hence enables host-based mirroring (either 2- or 3-way-mirroring)
  • Multiple volumes within a disk group can be created with an file system such as ext3, ext4, etc. It will support storage of any file type as the file system normally would – EXCEPT files which can be place in ASM directly
  • ADVM volume dynamically resize able

ADVM – Disadvantages

  • ADVM volumes may be resized online; but the used file system must support it as well (ext3 on OEL 5 does support online resizing but does not support online shrinking)
  • Storing files which can be stored in ASM directly in ADVM + file system is not supported
  • NFS on top of ADVM is also not supported
  • ASM configuration assistant (asmca) only supports following and thus command line is required.
    • Creation of volumes
    • Creation of file system
    • Delete of volumes
    • Delete of file systems.

To create a Disk Group for use with ADVM and ACFS

1.      Get LUNs presented (run fdisk ,etc) , partition disk (one on each LUN), label the disk with oracleasm createdisk.

2.      create disk in ASM (connect / as sysasm)

CREATE DISKGROUP data2 NORMAL REDUNDANCY FAILGROU CONTROLLER1 DISK ‘ORCL:DISK005’ FAILGROUP CONTROLLER2 DISK ‘ORCL:DISK006’ ATTRIBUTE ‘au_size’=’4M’ ‘compatible.asm’=’11.2’,’compatible.rdbms’=’11.2’,’compatible.advm’=’11.2’;

3.      logon as grid, set the environment and run the asm command shell (asmcmd) and run

ASMCMD> volcreate –G data2 –s 10g volume1

To see the information about the created volumne

ASMCMD> volinfo –G data2 volume1

4.      Create ACFS file system from Operating system

mkfs –t acfs /dev/asm/volume1-390

 

5.      Register the ACFS with acfsutil

acfsutil registry –a /dev/asm/volumn1-390 /u01/app/acfsmounts/test

df-h

6.      You can have upto 63 snapshots of the same file system. They can be deleted or created on the fly. ACFS snapshots provide a point in time consistent view of the file system which can be used for instance for backups. To create a snapshot named “backups1” on /backups

acfsutil snap create backups1 /backups

7.      Once created the snapshot is available under /backups/.ACFS directory

To see information about already created snapshots

acfsutil info fs /backups

8.      To delete a snapshot

Acfsutil snap delete backups1 /backups

Linux/Unix find Command usage

Using the Unix/Linux Find command

Find command is a extremely useful command. you can search for any file anywhere using this command provided that file and directory you are searching has read write attributes set to you ,your, group or all. Find descends directory tree beginning at each pathname and finds the files that meet the specified conditions.

Some Examples:
find $HOME -print will lists all files in your home directory.
find /work -name chapter1 -print will list all files named chapter1 in /work directory.
find / -type d -name 'man*' -print will list all manpage directories.
find / -size 0 -ok rm {} \; will remove all empty files on system.
conditions of find
  • -atime +n |-n| n will find files that were last accessed more than n or less than -n days or n days.
  • -ctime +n or -n will find that were changed +n -n or n days ago.
  • -depth descend the directory structure, working on actual files first and then directories. You can use it with cpio command.
  • -exec commad {} \; run the Unix command on each file matched by find. Very useful condition.
  • -print print or list to standard output (screen).
  • -name pattern find the pattern.
  • -perm nnnfind files whole permission flags match octal number nnn.
  • -size n find files that contain n blocks.
  • -type c Find file whole type is c. C could be b or block, c Character special file, d directory, p fifo or named pipe, l symbolic link, or f plain file.

More Examples

Find 10 days old files of size 0


#/bin/ksh
echo " /tmp in /tmp/checkold.txt file"
find /tmp -size 0 -atime +10 -exec ls -l {} \; > /tmp/checkold.txt
find /tmp -size 0 -atime +10 -exec rm -f {} \; 
 

Find large files in system

#!/bin/sh
# Script to find the big files on a disk. 
# Defaults and temporary info.
# This script send the output to a default printer
DiskName=${1:?Disk name not supplied.}
TMPFILE=/tmp/$LOGNAME.$$.txt
SysName=`uname -n`
 
echo \
        "Checking for large files on $SysName $DiskName.  " \
        "Output will be sent to default printer."
 
echo "\nNewer big files on $SysName $DiskName" >> $TMPFILE
find $DiskName -type f -mtime -3 -size +5000 -exec ls -ld {} \; \
        2>/dev/null | sort -n -k 5.1,5 >> $TMPFILE
 
echo "\nOlder big files on $SysName $DiskName" >> $TMPFILE
find $DiskName -type f -mtime +3 -size +5000 -exec ls -ld {} \; \
        2>/dev/null | sort -n -k 5.1,5 >> $TMPFILE
 
#change the following line if you want to put output to a file
#or anything.

lp -onb -olandscape $TMPFILE
rm $TMPFILE
 # End of script

Find all the files named core and remove them. Saving output in mycompcore.txt file

#!/bin/ksh
find / -name core -group mycomp -print -exec rm -f {} \; >> mycompcore.txt
 
 

Allocate run time memory for java inside database

If you want to run a  java program inside the database for which you need lots of memory during run time.  
Here is what you do (assuming that JVM is already installed inside the database)
1.        Create the function to set java memory (you need to call this from your session before program)

 
create or replace function setMaxMemorySize(num number) return number
is language java name
'oracle.aurora.vm.OracleRuntime.setMaxMemorySize(long) returns long';
 
2.       To set the memory run this from your SQL> session.
 
Select setMaxMemorySize(1024*1024*1024) from dual;

3.       Create the function to see your set java session memory.
create or replace function getMaxMemorySize return number
is language java name
'oracle.aurora.vm.OracleRuntime.getMaxMemorySize() returns long';

4.       To see your current java allocated memory run
Select getMaxMemorySize from dual;

How to write the database id to its alert.log


In order to periodically write the DBID to its alert log please schedule this code.

(You might need DBID for restore/recovery purposes.)
declare
  l_dbid number;
begin
   select dbid into l_dbid from v$database;
   dbms_system.ksdwrt(2,' DBID='||l_dbid);
end;
/

How to drop columns from a very large table

Let's say you have a very large table called MOVIES with this type of data


  1* select  movie_name,genre , comments from movies where rownum < 10
SQL> /

MOVIE_NAME                GENRE                COMMENTS
------------------------- -------------------- ---------------
The good The Bad The Ugly Western              asdf
Titanic                   Drama                asdf
Avatar                    Science Fiction      asdf
Gravity                   Science Fiction      asdf
Groundhog Day             Comedy               asdf
junk                      as                   asdf
The good The Bad The Ugly Western              asdf
Titanic                   Drama                asdf
Avatar                    Science Fiction      asdf

9 rows selected.

 



Now you want to drop the column called "Comments". This is a two step operation

1. Set the column to be unused.

SQL> alter table movies set unused (comments)
  2  /

Table altered.

Elapsed: 00:00:00.24


2. Drop the column with this command.

SQL> alter table movies drop unused columns
  2  /

Table altered.

Elapsed: 00:00:38.77
SQL>

SQL plan management (cleanup of Sysaux)

Originally posted in 2014. Updated November 2026 for Oracle Database 19c and 21c.

SQL Plan Management (SPM) lets the optimizer use only execution plans you have accepted, so a statistics refresh or an upgrade cannot quietly swap a good plan for a bad one. New plans are recorded, tested and accepted only if they perform better. The plans live in the SQL Management Base (SMB) in the SYSAUX tablespace, and if nobody manages them, SYSAUX keeps growing. This post covers what to check and what to run regularly on 19c and 21c.

How SPM works

  1. Capture: plans are stored as SQL plan baselines. The first plan for a statement is accepted, and later plans are added to the plan history as unaccepted.
  2. Selection: for a statement that has a baseline, the optimizer uses only accepted plans. Any new plan it finds is recorded but not used.
  3. Evolution: unaccepted plans are test-run and accepted only if they perform better. Since 12c this happens automatically every night through the SYS_AUTO_SPM_EVOLVE_TASK in the maintenance window.

1. Capture only what you need

Setting OPTIMIZER_CAPTURE_SQL_PLAN_BASELINES=TRUE for the whole database captures a baseline for every repeatable statement, and that is what fills SYSAUX. On 19c and 21c, either load plans for the statements you care about, or keep automatic capture but limit it with filters.

-- Load the current plan of one known-good statement from the cursor cache
DECLARE
  n PLS_INTEGER;
BEGIN
  n := DBMS_SPM.LOAD_PLANS_FROM_CURSOR_CACHE(sql_id => '&sql_id');
  DBMS_OUTPUT.PUT_LINE(n || ' plan(s) loaded');
END;
/

-- Or capture automatically, but only for one application schema
EXEC DBMS_SPM.CONFIGURE('AUTO_CAPTURE_PARSING_SCHEMA_NAME', 'APP_OWNER', TRUE);
ALTER SYSTEM SET optimizer_capture_sql_plan_baselines = TRUE;

2. Check how much space SPM uses

SELECT occupant_name, ROUND(space_usage_kbytes/1024) AS mb
FROM   v$sysaux_occupants
WHERE  occupant_name = 'SQL_MANAGEMENT_BASE';

SELECT parameter_name, parameter_value, last_modified
FROM   dba_sql_management_config
WHERE  parameter_name IN ('SPACE_BUDGET_PERCENT','PLAN_RETENTION_WEEKS');

SELECT accepted, enabled, COUNT(*) AS plans
FROM   dba_sql_plan_baselines
GROUP  BY accepted, enabled;

The defaults are still SPACE_BUDGET_PERCENT = 10 (allowed range 1 to 50) and PLAN_RETENTION_WEEKS = 53 (allowed range 5 to 523). When the SMB goes over its space budget, Oracle writes a warning to the alert log every week. It does not stop capturing plans.

3. Shorten retention and set the space budget

The automatic purge removes plans that have not been used for PLAN_RETENTION_WEEKS, whether they are accepted or not. It runs as part of the nightly maintenance tasks. For most systems, half a year is enough:

EXEC DBMS_SPM.CONFIGURE('plan_retention_weeks', 26);
EXEC DBMS_SPM.CONFIGURE('space_budget_percent', 20);

4. Drop unaccepted plans safely

Correction to my 2014 version: calling DBMS_SPM.DROP_SQL_PLAN_BASELINE with only sql_handle drops every plan for that statement, accepted plans included. Always pass plan_name as well:

SET SERVEROUTPUT ON
DECLARE
  n       PLS_INTEGER;
  total   PLS_INTEGER := 0;
BEGIN
  FOR r IN (SELECT sql_handle, plan_name
            FROM   dba_sql_plan_baselines
            WHERE  accepted = 'NO'
            AND    fixed    = 'NO'
            AND    last_verified IS NOT NULL      -- already evaluated and rejected
           ) LOOP
    n := DBMS_SPM.DROP_SQL_PLAN_BASELINE(sql_handle => r.sql_handle,
                                         plan_name  => r.plan_name);
    total := total + n;
  END LOOP;
  DBMS_OUTPUT.PUT_LINE(total || ' unaccepted plan(s) dropped');
END;
/

Leave out the last_verified line if you also want to drop plans the evolve task has not tested yet.

5. Review the automatic evolve task

SELECT parameter_name, parameter_value
FROM   dba_advisor_parameters
WHERE  task_name = 'SYS_AUTO_SPM_EVOLVE_TASK'
AND    parameter_value <> 'UNUSED'
ORDER  BY parameter_name;

-- Report of the last run
SELECT DBMS_SPM.REPORT_AUTO_EVOLVE_TASK FROM dual;

If you would rather approve plans yourself, set ACCEPT_PLANS to FALSE:

EXEC DBMS_SPM.SET_EVOLVE_TASK_PARAMETER('SYS_AUTO_SPM_EVOLVE_TASK', 'ACCEPT_PLANS', 'FALSE');

Multitenant note

In a 19c or 21c container database, each PDB has its own SQL Management Base and its own settings. Run the checks and the DBMS_SPM.CONFIGURE calls while connected to each PDB, not only in CDB$ROOT. The user needs the ADMINISTER SQL MANAGEMENT OBJECT privilege.

Routine checklist

  • Monthly: check SMB size in V$SYSAUX_OCCUPANTS and look for SPM space warnings in the alert log.
  • Monthly: read the auto evolve report and drop rejected plans.
  • After upgrades or big releases: load known-good plans for critical SQL from the cursor cache or a SQL tuning set.

More current DBA scripts are in my GitHub repository: github.com/sbajwa55/dba-scripts. For help with Oracle performance, migrations or AWS, visit Bajwa Consulting Services.

Thursday, April 24, 2014

Packaging an Incident for Oracle Support with ADRCI




1. login to the machine as database owner and set the environment of your database.
2. Create the .zip file by running adrci utility (check below).

adrci
ADR base = "/oracle/app/oracle"
adrci> set home diag/rdbms/MYDB
adrci> show incident


ADR Home = /oracle/app/oracle/diag/rdbms/vger/VGER:
*************************************************************************
INCIDENT_ID          PROBLEM_KEY                                                 CREATE_TIME
-------------------- ----------------------------------------------------------- ----------------------------------------
434700               ORA 3137 [12333]                                            2012-11-10 23:46:21.145000 -05:00
497893               ORA 3137 [1010]                                             2012-12-08 11:19:51.714000 -05:00
533662               ORA 3137 [12333]                                            2012-12-29 08:28:37.406000 -05:00
584879               ORA 3137 [12333]                                            2013-01-19 16:12:55.363000 -05:00
598784               ORA 3137 [12333]                                            2013-01-26 16:14:31.048000 -05:00
.
.
.


19 rows fetched

adrci> show package
adrci> ips create package
 Created package 2 without any contents, correlation level typical
adrci> ips add incident 434700 package 2;
Added incident 434700 to package 2
adrci> ips generate package 2 in /locatin/to/my/dir


Generated package 2 in file /locatin/to/my/dir/IPSPKG_20131104090125_COM_1.zip, mode complete

3. Now you can attach this .zip file created in step 2  to your SR with Oracle Support