Archives May 2023

DIFFERENCE BETWEEN PHYSICAL_READ_BYTES_DELTA AND DISK_READS_DELTA IN dba_hist_sqlstat

What does these columns in dba_hist_sqlstat denote and what makes the difference between these values?

Trace the query with 10046 if needed.

kIsH@xHydra<>alter session set statistics_level=all;

Session altered.

kIsH@xHydra<>alter session set tracefile_identifier='10046_dbss';

Session altered.

kIsH@xHydra<>alter session set events '10046 trace name context forever, level 12';

Session altered.

kIsH@xHydra<>SELECT /*+parallel(8)*/ * from dba_source;


kIsH@xHydra<>alter session set events '10046 trace name context off';

Session altered.

kIsH@xHydra<>exit

Check dba_hist_sqlstat view for PHYSICAL_READ_BYTES_DELTA and DISK_READS_DELTA

SQL> select SQL_ID,PHYSICAL_READ_BYTES_DELTA,DISK_READS_DELTA from dba_hist_sqlstat where SQL_ID='3hbbrg389qazm';

SQL_ID        PHYSICAL_READ_BYTES_DELTA DISK_READS_DELTA
------------- ------------------------- ----------------
3hbbrg389qazm                  61587456             7518

Let us verify the and sum up the metric “physical read total bytes” from v$mystat which shows the same statistics as dba_hist_sqlstat

SQL> SELECT a.name,sum(b.value) PHYSICAL_READ_BYTES_DELTA ,c.sql_id from v$statname a,v$mystat b, v$sql c where c.sql_id='3hbbrg389qazm' and a.name in ('physical read total bytes') group by a.name,c.sql_id;

NAME                      SUM(B.VALUE) SQL_ID
------------------------- ------------ -------------
physical read total bytes   61587456 3hbbrg389qazm

In autotrace, the "physical reads" output from execution plan statistics shows the same value as DISK_READS_DELTA.

SQL> set lines 200 pages 1000
SQL> set autot traceonly
SQL> SELECT /*+parallel(8)*/ * from dba_source;

Statistics
----------------------------------------------------------
        168  recursive calls
          0  db block gets
       8610  consistent gets
       7518  physical reads <===============
          0  redo size
   29862441  bytes sent via SQL*Net to client
     213836  bytes received via SQL*Net from client
      19405  SQL*Net roundtrips to/from client
          2  sorts (memory)
          0  sorts (disk)
     291053  rows processed

Summary:

PHYSICAL_READ_BYTES_DELTA – represents the number of data in bytes read from disk between begin interval and end interval time of snapshot

DISK_READS_DELTA – is the number of data blocks read from disk between begin interval and end interval time of snapshot

CONVERT NON-CDB TO CDB IN 19C

Generally, lower version non- CDB cannot be both converted and upgraded to a PDB at the same time.

Example: If 12c non-CDB should be upgraded to 19c PDB, then

  • Either upgrade 12c non-CDB to 19c non-CDB and then convert to PDB
  • Or convert 12c non-CDB to 12c PDB and then upgrade to 19c

Source – 19c non-CDB ; Target – 19c PDB

source NON-CDB – shutdown the database and open in read only mode.

SQL> shu immediate;
Database closed.
Database dismounted.
ORACLE instance shut down.
SQL> startup open read only;
ORACLE instance started.
Total System Global Area 1778381840 bytes
Fixed Size                  8897552 bytes
Variable Size             419430400 bytes
Database Buffers         1342177280 bytes
Redo Buffers                7876608 bytes
Database mounted.
Database opened.

Export the manifest file into server. This xml file contains all the tablespaces and datafile information of non cdb to be plugged in to target CDB.

SQL> exec DBMS_PDB.DESCRIBE(pdb_descr_file => '/tmp/non_cdb.xml');

PL/SQL procedure successfully completed.

target CDB:

Always, dont skip or forget this step. This step is important in verifying the compatibility of the source non cdb to be eligible for plug in. If the output is “YES”, then well and good to go. If output is “NO”, then there are certain violations which are related to mismatch and compatibility which need to be cleared.

SQL> SET SERVEROUTPUT ON;
DECLARE
    compatible CONSTANT VARCHAR2(3) := CASE     DBMS_PDB.CHECK_PLUG_COMPATIBILITY(pdb_descr_file => '/tmp/non_cdb.xml')
    WHEN TRUE THEN 'YES'
ELSE 'NO'
END;
BEGIN
    DBMS_OUTPUT.PUT_LINE(compatible);
END;
/SQL>   2    3    4    5    6    7    8    9
YES <================


PL/SQL procedure successfully completed.

Check PDB_PLUG_IN_VIOLATIONS irrespectively, either the above procedure return YES or NO.

SQL> SELECT count(*) FROM PDB_PLUG_IN_VIOLATIONS;

  COUNT(*)
----------
         2

SQL> col NAME for a20
SQL> col CAUSE for a20
SQL> col MESSAGE for a20
SQL> SELECT name,cause,type,message,status from PDB_PLUG_IN_VIOLATIONS;

XSCALIBA             Non-CDB to PDB       WARNING   PDB plugged in is a  PENDING
                                                    non-CDB, requires no
                                                    ncdb_to_pdb.sql be r
                                                    un.

Create a new pluggable database in CDB so that the non CDB can be plugged into this PDB

SQL> CREATE PLUGGABLE DATABASE newpdb USING '/tmp/ncdb.xml'
  2  COPY
  3  FILE_NAME_CONVERT=('/u01/app/oracle/oradata/XSCALIBAL/datafile/o1_mf','/apps01/oradata/HYDRA/');

Pluggable database created.

Execute the noncdb_to_pdb.sql script to convert the non CDB to PDB

SQL> @?/rdbms/admin/noncdb_to_pdb.sql

Below are the logs which are generated as part of noncdb_to_pdb.sql script

-rw-r--r--  1 oracle oinstall        543 May 22 15:58 apxremov1_con_catcon_12797.lst
-rw-r--r--  1 oracle oinstall         42 May 22 15:58 apxremov1_con_catcon_12989.done
-rw-r--r--  1 oracle oinstall         42 May 22 15:58 apxremov1_con_catcon_12988.done
-rw-r--r--  1 oracle oinstall        439 May 22 15:58 apxremov1_con0.log
-rw-r--r--  1 oracle oinstall        439 May 22 15:58 apxremov1_con1.log
-rw-r--r--  1 oracle oinstall        543 May 22 15:59 apxremov2_con_catcon_13009.lst
-rw-r--r--  1 oracle oinstall         42 May 22 15:59 apxremov2_con_catcon_13030.done
-rw-r--r--  1 oracle oinstall        439 May 22 15:59 apxremov2_con0.log
-rw-r--r--  1 oracle oinstall         42 May 22 15:59 apxremov2_con_catcon_13031.done
-rw-r--r--  1 oracle oinstall        439 May 22 15:59 apxremov2_con1.log
-rw-r--r--  1 oracle oinstall       2360 May 26 16:06 ncdb2pdb.settings.sql

Open the pdb and check the converted new pdb.

SQL> alter pluggable database newpdb open;

Pluggable database altered.

SQL> sho pdbs

    CON_ID CON_NAME                       OPEN MODE  RESTRICTED
---------- ------------------------------ ---------- ----------
         8 NEWPDB                         READ WRITE NO
SQL> alter session set container=newpdb;

Session altered.

SQL> SELECT name from v$datafile;

NAME
--------------------------------------------------------------------------------
/apps01/oradata/HYDRA/_system_l70lf69m_.dbf
/apps01/oradata/HYDRA/_sysaux_l70lfzfy_.dbf
/apps01/oradata/HYDRA/_undotbs1_l70lggjf_.dbf
/apps01/oradata/HYDRA/_users_l70lghln_.dbf
ORA-65005: missing or invalid file name pattern for file –

Cause:

Syntax issue in FILE_NAME_CONVERT parameter

SQL> CREATE PLUGGABLE DATABASE newpdb USING '/tmp/ncdb.xml'
  COPY
  FILE_NAME_CONVERT=("/u01/app/oracle/oradata/XSCALIBAL/","/apps01/oradata/HYDRA");  2    3
  FILE_NAME_CONVERT=("/u01/app/oracle/oradata/XSCALIBAL/","/apps01/oradata/HYDRA")
                     *
ERROR at line 3:
ORA-65005: missing or invalid file name pattern for file -

Solution:

SQL> CREATE PLUGGABLE DATABASE newpdb USING '/tmp/ncdb.xml'
  2  COPY
  3  FILE_NAME_CONVERT=('/u01/app/oracle/oradata/XSCALIBAL/','/apps01/oradata/HYDRA');
ORA-65054: Cannot open a pluggable database in the desired mode.

Can we open a PDB in read write mode when CDB is in read only mode?

Since the CDB is in open read only mode, the underlying PDB cannot be opened because of the metadata synchronization between CDB and PDB

SQL> sho pdbs

    CON_ID CON_NAME                       OPEN MODE  RESTRICTED
---------- ------------------------------ ---------- ----------
         2 PDB$SEED                       READ ONLY  NO
         3 PDBHY1                         READ ONLY
         4 PROX1                          MOUNTED
SQL> SELECT name,open_mode from v$database;

NAME      OPEN_MODE
--------- --------------------
HYDRA1    READ ONLY

Close the PDB

SQL> alter session set container=PDBHY1;

Session altered.
SQL> shu immediate;
Pluggable Database closed.

Open the PDB throws ORA-65054

SQL> alter pluggable database PDBHY1 open;
alter pluggable database PDBHY1 open
                         *
ERROR at line 1:
ORA-65054: Cannot open a pluggable database in the desired mode.

This means that, if CDB is in open read only and other PDB need to be opened in read write mode, then the above error is observed.

SQL> !oerr ora 65054
65054, 00000, "Cannot open a pluggable database in the desired mode."
// *Cause:  An attempt was made to open a pluggable database (PDB) in a mode
//          incompatible with the multitenant container database (CDB) or,
//          if the PDB belonged to an application container, in a mode
//          incompatible with the application root.
// *Action: Open the CDB or the application root in a compatible mode
//          first and retry the operation.
//

Make the CDB in read write mode to open the underlying PDB.

SQL> shu immediate;
Database closed.
Database dismounted.
ORACLE instance shut down.
SQL> startup;
ORACLE instance started.

Total System Global Area 1778382528 bytes
Fixed Size                  9135808 bytes
Variable Size             419430400 bytes
Database Buffers         1342177280 bytes
Redo Buffers                7639040 bytes
Database mounted.
Database opened.

SQL> show pdbs

    CON_ID CON_NAME                       OPEN MODE  RESTRICTED
---------- ------------------------------ ---------- ----------
         2 PDB$SEED                       READ ONLY  NO
         3 PDBHY1                         READ WRITE NO

This error occur to prevent inconsistency or corruption of the metadata for internal objects.

SHELL SCRIPT TO CONVERT MULTIPLE RAW 10046 TRACE FILE OUTPUT TO TKPROF FORMAT

c=0;
for x in `ls DB_NAME_*10046.trc`;
    do 
        tkprof $x DB_NAME_$c.trc ;
        c=`expr $c + 1`;
    done
ORA-65353: The undo tablespace is missing from the XML metadata file.

Generally, lower version non- CDB cannot be both converted and upgraded to a PDB at the same time.

Example: If 12c non-CDB should be upgraded to 19c PDB, then

  • Either upgrade 12c non-CDB to 19c non-CDB and then convert to PDB
  • Or convert 12c non-CDB to 12c PDB and then upgrade to 19c

Let us try anyways to convert a 12c non-CDB to 19c PDB

Source – 12c non-CDB ; Target – 19c PDB

SOURCE – Shutdown the source and open in read only mode to print the contents of non-CDB to xml file

=Xscalibal=>shu immediate;
Database closed.
Database dismounted.
ORACLE instance shut down.

=Xscalibal=>startup open read only;
ORACLE instance started.

Total System Global Area 1761607680 bytes
Fixed Size                  2925360 bytes
Variable Size             536874192 bytes
Database Buffers         1207959552 bytes
Redo Buffers               13848576 bytes
Database mounted.
Database opened.

=Xscalibal=>EXEC DBMS_PDB.DESCRIBE(pdb_descr_file => '/tmp/npdb.xml');

PL/SQL procedure successfully completed.


=Xscalibal=>shu immediate;
Database closed.
Database dismounted.
ORACLE instance shut down.

TARGET – Compatibility check failed in 19c PDB because the source is in 12c

SQL> SET SERVEROUTPUT ON;
DECLARE
compatible CONSTANT VARCHAR2(3) := CASE DBMS_PDB.CHECK_PLUG_COMPATIBILITY(pdb_descr_file => '/tmp/npdb.xml')
WHEN TRUE THEN 'YES'
ELSE 'NO'
END;
BEGIN
DBMS_OUTPUT.PUT_LINE(compatible);
END;
/SQL>   2    3    4    5    6    7    8    9
NO


PL/SQL procedure successfully completed.

There are lot of plugin violations related to upgrading the 12c non-cdb to 19c non-cdb

SQL> set lines 200 pages 1000
SQL> col NAME for a20
SQL> col CAUSE for a20
SQL> col MESSAGE for a20
SQL> col STATUS for a20
SQL> col ACTION for a20
SQL> SELECT name,cause,message,action,status FROM pdb_plug_in_violations;

NAME                 CAUSE                MESSAGE              ACTION               STATUS
-------------------- -------------------- -------------------- -------------------- --------------------
PDB$SEED             SQL Patch            '19.3.0.0.0 Release_ Call datapatch to in RESOLVED
                                          Update 1904101227' i stall in the PDB or
                                          s installed in the C the CDB
                                          DB but no release up
                                          dates are installed
                                          in the PDB

XSCALIBA             Non-CDB to PDB       PDB plugged in is a  Run noncdb_to_pdb.sq PENDING
                                          non-CDB, requires no l.
                                          ncdb_to_pdb.sql be r
                                          un.

XSCALIBA             PDB not Unicode      PDB not in Unicode ( Oracle recommends us PENDING
                                          AL32UTF8) character  ing Unicode (AL32UTF
                                          set. PDB character s 8) character set for
                                          et WE8MSWIN1252.      the database. Consi
                                                               der migrating the da
                                                               tabase to Unicode.

XSCALIBA             VSN not match        PDB's version does n Either upgrade the P PENDING
                                          ot match CDB's versi DB or reload the com
                                          on: PDB's version 12 ponents in the PDB.
                                          .1.0.2.0. CDB's vers
                                          ion 19.0.0.0.0.

XSCALIBA             OPTION               PDB's version is low Install the missing  PENDING
                                          er than CDB and PDB  components in the CD
                                          has more components  B or plug in to comp
                                          than the CDB, plug i atible CDB
                                          n is not allowed.

XSCALIBA             APEX                 APEX mismatch: PDB h Please contact Oracl PENDING
                                          as installed common  e Support.
                                          APEX. CDB has not in
                                          stalled APEX.

XSCALIBA             Parameter            CDB parameter sga_ta Please check the par PENDING
                                          rget mismatch: Previ ameter in the curren
                                          ous 1680M Current 16 t CDB
                                          96M

XSCALIBA             Parameter            CDB parameter compat Please check the par PENDING
                                          ible mismatch: Previ ameter in the curren
                                          ous '12.1.0.2.0' Cur t CDB
                                          rent '19.0.0'

XSCALIBA             Parameter            CDB parameter pga_ag Please check the par PENDING
                                          gregate_target misma ameter in the curren
                                          tch: Previous 560M C t CDB
                                          urrent 565M

XSCALIBA             CDB undo mode        Undo mode mismatch:  Either create an und PENDING
                                          PDB using SHARED und o tablespace in the
                                          o.  CDB using LOCAL  PDB or be aware that
                                          undo.                 the CDB will not lo
                                                               ok at undo in the PD
                                                               B.


10 rows selected.

Again apex mismatch due to lower version

SQL> CREATE PLUGGABLE DATABASE APDB USING '/tmp/npdb.xml'
  2  COPY
  3  FILE_NAME_CONVERT = ('/u01/app/oracle/oradata/xscalibal/','/apps01/oradata/HYDRA1/');
CREATE PLUGGABLE DATABASE APDB USING '/tmp/npdb.xml'
*
ERROR at line 1:
ORA-65346: The PDB version is lower and components (APEX) are missing in CDB.

Removed apex itself from source

=Xscalibal=>select COMP_ID, VERSION, STATUS from CDB_REGISTRY where COMP_ID='APEX';

COMP_ID                        VERSION                        STATUS
------------------------------ ------------------------------ -----------
APEX                           4.2.5.00.08                    VALID

=Xscalibal=>col COMP_NAME for a20
=Xscalibal=>SELECT c.comp_name,c.version,con.name FROM cdb_registry c
  2         INNER JOIN v$containers con on (c.con_id = con.con_id)
  3         WHERE c.comp_name like '%Application E%';

COMP_NAME            VERSION                        NAME
-------------------- ------------------------------ ------------------------------
Oracle Application E 4.2.5.00.08                    xscaliba
xpress

=Xscalibal=>@?/apex/apxremov_con

PL/SQL procedure successfully completed.

Performing installation in multitenant container database in the background.
The installation progress is spooled into apxremov*_con*.log files.

Please wait...

catcon: ALL catcon-related output will be written to apxremov1_con_catcon_12797.lst
catcon: See apxremov1_con*.log files for output generated by scripts
catcon: See apxremov1_con_*.lst files for spool files, if any
validate_script_path: sqlplus script apxremov1.sql does not exist or is unreadable
catconExec: empty Path returned by validate_script_path for
    SrcDir = 0, FileName = apxremov1.sql
catcon.pl: Unexpected error encountered in catconExec; exiting

catcon: ALL catcon-related output will be written to apxremov2_con_catcon_13009.lst
catcon: See apxremov2_con*.log files for output generated by scripts
catcon: See apxremov2_con_*.lst files for spool files, if any
validate_script_path: sqlplus script apxremov2.sql does not exist or is unreadable
catconExec: empty Path returned by validate_script_path for
    SrcDir = 0, FileName = apxremov2.sql
catcon.pl: Unexpected error encountered in catconExec; exiting


Installation completed. Log files for each container can be found in:

apxremov*_con*.log

You can quickly scan for ORA errors or compilation errors by using a utility
like grep:

grep ORA- *.log
grep PLS- *.log

=Xscalibal=>@?/apex/apxremov.sql
...Removing Application Express

Session altered.


PL/SQL procedure successfully completed.


no rows selected


PL/SQL procedure successfully completed.


Session altered.


PL/SQL procedure successfully completed.


Session altered.


no rows selected


User dropped.


PL/SQL procedure successfully completed.


PL/SQL procedure successfully completed.


PL/SQL procedure successfully completed.


PL/SQL procedure successfully completed.


PL/SQL procedure successfully completed.

...Application Express Removed

********************************************************************
** You must exit this SQL*Plus session before running apexins.sql **
********************************************************************

Again re-exported the data to xml file

=Xscalibal=>EXEC DBMS_PDB.DESCRIBE(pdb_descr_file => '/tmp/npdb.xml');

PL/SQL procedure successfully completed

Atlast, there is a missing undo tablespace in xml file because, non-cdb does not have local undo but in pdb, local undo is a separate concept.

SQL> CREATE PLUGGABLE DATABASE APDB USING '/tmp/npdb.xml'
  2  COPY
  3  FILE_NAME_CONVERT = ('/u01/app/oracle/oradata/xscalibal/','/apps01/oradata/HYDRA1/newpdb');
CREATE PLUGGABLE DATABASE APDB USING '/tmp/npdb.xml'
*
ERROR at line 1:
ORA-65353: The undo tablespace is missing from the XML metadata file.
NOSEGMENT INDEX OR FAKE INDEX IN ORACLE

Invisible index is the index which is not visible for optimizer in 11g and later versions.

Previously, the same invisible index was called as fake or no segment or virtual index.

This index can be logically created in memory without any segments in the disk. Fake index cannot be eligible for any maintenance operations like unusable, rebuild etc..

To create a virtual index, use nosegment clause in syntax

kIsH@xHydra<>CREATE INDEX logicalidx on rp(r_name,r_cost) local (partition R_JUN2022, partition R_MAY2022, partition R_APR2022, partition R_FEB2022) nosegment;

Index created.

Fake index are not visible or stored in dba_indexes view but has to be checked under dba_ind_partitions.

kIsH@xHydra<>SELECT index_name FROM dba_indexes WHERE index_name='LOGICALIDX';

no rows selected

kIsH@xHydra<>SELECT index_name FROM dba_ind_partitions WHERE index_name not in (SELECT index_name FROM dba_indexes);

INDEX_NAME
--------------------------------------------------------------------------------
BIN$7+HiycqkhSXgU8c4qMD3Bw==$0
BIN$7+HiycqkhSXgU8c4qMD3Bw==$0
BIN$7+HiycqkhSXgU8c4qMD3Bw==$0
BIN$7+HiycqkhSXgU8c4qMD3Bw==$0
BIN$7+HiycqkhSXgU8c4qMD3Bw==$0
BIN$7+HiycqkhSXgU8c4qMD3Bw==$0
LOGICALIDX
LOGICALIDX
LOGICALIDX
LOGICALIDX

10 rows selected.

_use_nosegment_indexes is a hidden parameter to enable the virtual index at optimizer level.

kIsH@xHydra<>alter session set "_use_nosegment_indexes" = true;

Session altered.
kIsH@xHydra<>set autot traceonly explain
kIsH@xHydra<>set lines 200 pages 1000
kIsH@xHydra<>SELECT r_name FROM RP where r_cost < 100;

Execution Plan
----------------------------------------------------------
Plan hash value: 1602089251

--------------------------------------------------------------------------------------------------------------------------
| Id  | Operation                                  | Name        | Rows  | Bytes | Cost (%CPU)| Time     | Pstart| Pstop |
--------------------------------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT                           |             |     1 |    16 |     3   (0)| 00:00:01 |       |       |
|   1 |  TABLE ACCESS BY GLOBAL INDEX ROWID BATCHED| RP          |     1 |    16 |     3   (0)| 00:00:01 | ROWID | ROWID |
|*  2 |   INDEX RANGE SCAN                         | LOGICALIDX |     1 |       |     2   (0)| 00:00:01 |       |       |
--------------------------------------------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   2 - access("R_COST"<100)

Any maintenance operations throw ORA-08114

kIsH@xHydra<>ALTER INDEX LOGICALIDX unusable;
ALTER INDEX LOGICALIDX unusable
*
ERROR at line 1:
ORA-08114: can not alter a fake index
SHELL SCRIPT TO STOP OR HALT OR CANCEL A SPECIFIC SQL WHICH EXECUTE FOR LONGER TIME

Is it possible to stop a sql query which is executing for quite long time than threshold?

In 19c, we can stop the sql using inbuilt ddl which stops a specific sql based on sid, serial#

This script can be useful, if a particular query is executed beyond the time and blocking other DML in enqueues or such events.

Here elapsed_time from v$sql contains the db time of the sql rather than wall clock time. So modify the script accordingly to needs and time frame.

This script provides basic functionalities to cancel the sql. This script is also inspired based on an incident, where a specific DML was locking a table for 1 hour and blocking 100’s of sessions in enq: tx row lock contention with performance degradation. There are also other options which may help to cancel a query like resource manager or sql quarantine in exadata.

REM Procedure to stop a specific sql
REM
REM Author -- Kishan
REM
CREATE OR REPLACE PROCEDURE stopsql (sql_id IN VARCHAR2)
AS
   stmt VARCHAR (1000);
   CURSOR get_sql
   IS
	  SELECT s.sid, s.serial# serial, sq.sql_id FROM v$session s
                 INNER JOIN v$sql sq on (s.sql_id = sq.sql_id)
                 WHERE sq.sql_text like '%xtbl%'
                  AND
                 sq.sql_text not like '%INNER JOIN v$sql%'
                  AND 
                 sq.elapsed_time/1000000 > 1;
BEGIN
   FOR x IN get_sql
   LOOP
	  BEGIN
		 stmt :=  'ALTER SYSTEM CANCEL SQL ''' || x.sid || ',' || x.serial || '''' || '';
		 BEGIN
			EXECUTE IMMEDIATE stmt;
		 EXCEPTION
			WHEN OTHERS
			THEN
			   -- If there are any exceptions specify here
			   CONTINUE;
		 END;
	  END;
   END LOOP;
END;
/

######################
# Author - Kishan M  #
######################
#!/bin/bash


#Remove the temporary files at the end of execution of script
trap 'rm -rf /home/oracle/oratab_new' EXIT
#For logging purpose
_LOG_0()
{
echo "*************************************$1"
}

#Set the environment variables
_SET_ENV_1()
{
cat /etc/oratab|grep -v '#'|grep -v '^$' > /home/oracle/oratab_new
while read x
   do
     IFS=':' read -r -a array <<< $x
                ORACLE_SID="${array[0]}"
                ORACLE_HOME="${array[1]}"
                echo $ORACLE_SID
                echo $ORACLE_HOME
                export PATH=$PATH:$ORACLE_HOME/bin
   done < /home/oracle/oratab_new
}

#Fetch the sql which takes time

_GET_SQL(){
$ORACLE_HOME/bin/sqlplus -S '/ as sysdba' <<EOF
          spool stopsql.txt
          set heading off
          set feedback off
          SELECT s.sid, s.serial# serial, sq.sql_id FROM v\$session s
                 INNER JOIN v\$sql sq on (s.sql_id = sq.sql_id)
                 WHERE sq.sql_text like '%xtbl%'
                  AND
                 sq.sql_text not like '%INNER JOIN v$sql%'
                  AND
                 sq.elapsed_time/1000000 > 1;
          spool off
exit;
EOF
}

#Stop only the specific sql without killing the session
_STOP_SQL(){
        touch sql.sql && echo -ne "EXEC stopsql('sql')\n exit;" > sql.sql
        sqlid=/home/oracle/stopsql.txt
        if [ -s $sqlid ]
        then
                sql=`cat $sqlid |awk '{print $NF}'|uniq|grep -v '^$'`
                sqlplus -S '/ as sysdba' @sql.sql
        else
                break
        fi
}



_SET_ENV_1
_GET_SQL
_STOP_SQL

Demonstration:

Execute the specific sql which need to be stopped after particular time.

[oracle@staxhost ~]$ ./stopsql.sh
eXhydra
/u01/app/oracle/product/19.0.0/dbhome_1

        62      53762 gycyg7ysuw1h4
        64      22468 gycyg7ysuw1h4
        66      49427 gycyg7ysuw1h4
        70      10667 gycyg7ysuw1h4
        74      55475 gycyg7ysuw1h4
        76      50988 gycyg7ysuw1h4
        85      26671 gycyg7ysuw1h4
        86      36067 gycyg7ysuw1h4
        91      13897 gycyg7ysuw1h4

PL/SQL procedure successfully completed.

The executed sql is cancelled with ORA-01013 after the execution of shell script.

SELECT * from atbl a , xtbl x where a.xid <> x.xid and A.salary > 100 and a.city <> 'India'
.....

NAME
--------------------------------------------------------------------------------
       XID
----------
CITY
--------------------------------------------------------------------------------
COUNTRY
--------------------------------------------------------------------------------
DEPARTMENT
--------------------------------------------------------------------------------
   ZIPCODE XDATE         SALARY
---------- --------- ----------

ERROR:
ORA-01013: user requested cancel of current operation



1680 rows selected.
SQL QUERY TO IDENTIFY THE OS PID OR SPID

There is often

kIsH@xHydra<>set lines 200 pages 1000
kIsH@xHydra<>col USERNAME for a20
kIsH@xHydra<>SELECT s.username,s.sid,s.serial#,s.program,p.spid
          FROM v$process p
          INNER JOIN v$session s
          ON (s.paddr = p.addr)
          WHERE s.username='SYS';
HOW TO BACKUP INTERNAL TABLES OF SYSTEM AND SYSAUX TABLESPACES

It is not always expected that the system or sysaux objects can be back up at any specific time in the life of every DBA career. But, it is mandatory to take backup during sysaux housekeeping and system tables cleanup as a workaround for another major issue.

EXP utility is an underrated one which is very light and simple in this situation to take backup of system and sysaux related objects in an efficient way.

Use the below command and the internal tables are packed up in a dump file.

[oracle@staxhost ~]$ exp sys/password FILE=expstat.dmp TABLES=tab$,ind$,ts$,hist_head$,aud$,exp_stat$,exp_obj$,exp_head$

Export: Release 19.0.0.0.0 - Production on Thu Jan 19 17:18:09 2023
Version 19.16.0.0.0

Copyright (c) 1982, 2019, Oracle and/or its affiliates.  All rights reserved.


EXP-00056: ORACLE error 28009 encountered
ORA-28009: connection as SYS should be as SYSDBA or SYSOPER
Username: sys as sysdba
Password:

Connected to: Oracle Database 19c Enterprise Edition Release 19.0.0.0.0 - Production
Version 19.16.0.0.0
Export done in US7ASCII character set and AL16UTF16 NCHAR character set
server uses AL32UTF8 character set (possible charset conversion)

About to export specified tables via Conventional Path ...
. . exporting table                           TAB$       2284 rows exported
EXP-00091: Exporting questionable statistics.
EXP-00091: Exporting questionable statistics.
. . exporting table                           IND$       2934 rows exported
EXP-00091: Exporting questionable statistics.
EXP-00091: Exporting questionable statistics.
. . exporting table                            TS$          7 rows exported
EXP-00091: Exporting questionable statistics.
EXP-00091: Exporting questionable statistics.
EXP-00064: HIST_HEAD$ is an inner nested table and cannot be exported.
. . exporting table                           AUD$          0 rows exported
EXP-00091: Exporting questionable statistics.
. . exporting table                      EXP_STAT$         74 rows exported
EXP-00091: Exporting questionable statistics.
EXP-00091: Exporting questionable statistics.
. . exporting table                       EXP_OBJ$         22 rows exported
EXP-00091: Exporting questionable statistics.
EXP-00091: Exporting questionable statistics.
. . exporting table                      EXP_HEAD$        266 rows exported
EXP-00091: Exporting questionable statistics.
EXP-00091: Exporting questionable statistics.
Export terminated successfully with warnings.