Search This Blog

Total Pageviews

Friday, 12 March 2010

Oracle script to monitor for the PGA per session

 
 
 ORACLE PGA


The PGA (Program or Process Global Area) is a memory area (RAM) that stores data and control information for a single process. For example, it typically contains a sort area, hash area, session cursor cache, etc.


prompt
prompt PGA Usage Summary Report
prompt ------------------------

col alloc_sum format 999,999,990 heading 'Total Allocation'
col free_sum format 999,999,990 heading 'Total Freeable'
col used_sum format 999,999,990 heading 'Total In Use'
col pga_range heading 'PGA Range'
col sessions heading 'No.|Sessions'

compute sum of alloc_sum on report
compute sum of used_sum on report
compute sum of free_sum on report
break on report

select count (*) as sessions
, case
when pga_alloc_mem < (1*1024*1024) then ' < 1Mb'
when pga_alloc_mem < (2*1024*1024) then ' 1Mb-> 2Mb'
when pga_alloc_mem < (3*1024*1024) then ' 2Mb-> 3Mb'
when pga_alloc_mem < (4*1024*1024) then ' 3Mb-> 4Mb'
when pga_alloc_mem < (5*1024*1024) then ' 4Mb-> 5Mb'
when pga_alloc_mem < (10*1024*1024) then ' 5Mb->10Mb'
when pga_alloc_mem < (15*1024*1024) then '10Mb->15Mb'
when pga_alloc_mem < (20*1024*1024) then '15Mb->20Mb'
when pga_alloc_mem < (25*1024*1024) then '20Mb->25Mb'
else '25Mb+ '
end as pga_range
, sum (pga_alloc_mem) as alloc_sum
, sum (pga_used_mem) as used_sum
, sum (pga_freeable_mem) as free_sum
from v$process
group by case
when pga_alloc_mem < (1*1024*1024) then ' < 1Mb'
when pga_alloc_mem < (2*1024*1024) then ' 1Mb-> 2Mb'
when pga_alloc_mem < (3*1024*1024) then ' 2Mb-> 3Mb'
when pga_alloc_mem < (4*1024*1024) then ' 3Mb-> 4Mb'
when pga_alloc_mem < (5*1024*1024) then ' 4Mb-> 5Mb'
when pga_alloc_mem < (10*1024*1024) then ' 5Mb->10Mb'
when pga_alloc_mem < (15*1024*1024) then '10Mb->15Mb'
when pga_alloc_mem < (20*1024*1024) then '15Mb->20Mb'
when pga_alloc_mem < (25*1024*1024) then '20Mb->25Mb'
else '25Mb+ '
end
order by pga_range
/



prompt SQL work area (current)
col sid for 99990
col operation_type for a20
col wsize  for 999,990 heading 'Current|W.Size(k)'
col esize  for 999,990 heading 'Expected|W.Size(k)'
col amsize for 999,999,990 heading 'Current|Mem.(k)'
col mmsize for 999,999,990 heading 'Maximum|Mem.(k)'
col tsize  for 999,999,990 heading 'Tmp. Seg.|Size (k)'
col passes for 999,990 heading 'Passes'
select SID
     , OPERATION_TYPE
     , WORK_AREA_SIZE/1024   as wsize
     , EXPECTED_SIZE/1024    as esize
     , ACTUAL_MEM_USED/1024  as amsize
     , MAX_MEM_USED/1024     as mmsize
     , TEMPSEG_SIZE/1024     as tsize
     , NUMBER_PASSES         as passes
from gv$sql_workarea_active
order by sid
/

--clear breaks
--clear computes

Script to monitor for the 'session pga memory'



col VALUE format 9999999999999
col name format a40
select name,value ,unit from V$PGASTAT ;


SELECT PROGRAM, PGA_USED_MEM, PGA_ALLOC_MEM/(1024*1024) "ALLOC(MB)",
PGA_FREEABLE_MEM FREEABLE, PGA_MAX_MEM
FROM V$PROCESS
order by pga_alloc_mem asc;

Show the maximum PGA usage per process:

select max(pga_used_mem), max(pga_alloc_mem), max(pga_max_mem) from v$process;


 
 set pagesize 100
prompt PER SESSION PGA
col TXT format a30
col MACHINE format a12
col MODULE format a12
col "MEMORY/SESSION" format a10
col EVENT format a12
col program format a12
col unix_pid format a8
col schemaname format a10
col username format a12
col sid_serial format a10
SELECT
a.sid||','|| c.serial# sid_serial, lpad(e.spid,7) unix_pid,
round(sum(a.value)/1024/1024,2) || ' MB ' "MEMORY/SESSION",
c.username, c.schemaname, c.machine, c.status, c.server,
c.program, c.module, c.event,d.sql_id,
round(e.pga_used_mem/1024/1024,2) as pga_used_mem,
round(e.pga_alloc_mem/1024/1024,2) as pga_alloc_mem,
round(e.pga_freeable_mem/1024/1024,2) as pga_freeable_mem,
round(e.pga_max_mem/1024/1024,2) as pga_max_mem
FROM v$sesstat a, v$statname b, v$session c, v$sqlarea d, v$process e
WHERE name = 'session pga memory'
AND a.statistic# = b.statistic#
AND a.sid = c.sid
AND c.sql_address = d.address(+)
AND c.sql_hash_value = d.hash_value(+)
AND e.addr=c.paddr
GROUP BY a.sid, c.serial#, lpad(e.spid,7),
c.username, c.schemaname, c.machine, c.status, c.server, c.program,
c.module, c.event,d.sql_id,e.pga_used_mem/1024/1024, e.pga_alloc_mem/1024/1024,
e.pga_freeable_mem/1024/1024, e.pga_max_mem/1024/1024
ORDER BY round(sum(a.value)/1024/1024,2) DESC;
 
 
 SGA Pools History Report from AWR (include free memory)
 
 https://github.com/carlos-sierra/cscripts/blob/master/cs_sgastat_awr_report.sql
 
 set linesize 300 pagesize 300
 
 VARIABLE BgnSnap NUMBER
VARIABLE EndSnap NUMBER
VARIABLE DID NUMBER
VARIABLE INST_NUMBER number
VARIABLE x VARCHAR2(30)
exec select max(snap_id) -2 into :BgnSnap from dba_hist_snapshot ;
exec select max(snap_id) into :EndSnap from dba_hist_snapshot ;
exec select DBID into :DID from v$database;
exec select INSTANCE_NUMBER into :INST_NUMBER from v$instance ;
 
 define cs_instance_number=1
 define cs_dbid=''
 COL snap_id 					FOR 9999999 	HEA 'Snap ID'
COL begin_time 					FOR A19 		HEA 'Begin Time'
COL end_time 					FOR A19 		HEA 'End Time'
COL pga_aggregate_target 		FOR 9,990.000 	HEA 'PGA|Aggregate|Target'
COL sga_target 					FOR 9,990.0 	HEA 'SGA|Target'
COL buffer_cache 				FOR 9,990.000 	HEA 'Buffer|Cache'
COL log_buffer 					FOR 9,990.000 	HEA 'Log|Buffer'
COL shared_io_pool 				FOR 9,990.000 	HEA 'Shared|IO Pool'
COL fixed_sga 					FOR 9,990.000 	HEA 'Fixed|SGA'
COL shared_pool 				FOR 9,990.000 	HEA 'Shared|Pool'
COL shared_pool_free_memory 	FOR 9,990.000 	HEA 'Shared|Pool|Free|Memory'
COL large_pool 					FOR 9,990.000 	HEA 'Large|Pool'
COL large_pool_free_memory 		FOR 9,990.000 	HEA 'Large|Pool|Free|Memory'
COL java_pool 					FOR 9,990.000 	HEA 'Java|Pool'
COL java_pool_free_memory 		FOR 9,990.000 	HEA 'Java|Pool|Free|Memory'
COL streams_pool 				FOR 9,990.000 	HEA 'Streams|Pool'
COL streams_pool_free_memory 	FOR 9,990.000 	HEA 'Streams|Pool|Free|Memory'
--
PRO
PRO Memory Pools (GBs)
PRO ~~~~~~~~~~~~~~~~~~
WITH
sgastat AS (
SELECT /*+ MATERIALIZE NO_MERGE */
       snap_id,
       ROUND(SUM(CASE WHEN name = 'buffer_cache' AND pool IS NULL THEN bytes ELSE 0 END)/POWER(2,30), 3) buffer_cache, -- see bug 18166499
       ROUND(SUM(CASE WHEN name = 'log_buffer' AND pool IS NULL THEN bytes ELSE 0 END)/POWER(2,30), 3) log_buffer,
       ROUND(SUM(CASE WHEN name = 'shared_io_pool' AND pool IS NULL THEN bytes ELSE 0 END)/POWER(2,30), 3) shared_io_pool,
       ROUND(SUM(CASE WHEN name = 'fixed_sga' AND pool IS NULL THEN bytes ELSE 0 END)/POWER(2,30), 3) fixed_sga,
       ROUND(SUM(CASE WHEN pool = 'shared pool' AND name IS NULL THEN bytes ELSE 0 END)/POWER(2,30), 3) shared_pool, -- see bug 18166499
       ROUND(SUM(CASE WHEN pool = 'shared pool' AND name = 'free memory' THEN bytes ELSE 0 END)/POWER(2,30), 3) shared_pool_free_memory,
       ROUND(SUM(CASE WHEN pool = 'large pool'  AND name IS NULL THEN bytes ELSE 0 END)/POWER(2,30), 3) large_pool, -- see bug 18166499
       ROUND(SUM(CASE WHEN pool = 'large pool' AND name = 'free memory' THEN bytes ELSE 0 END)/POWER(2,30), 3) large_pool_free_memory,
       ROUND(SUM(CASE WHEN pool = 'java pool' AND name IS NULL THEN bytes ELSE 0 END)/POWER(2,30), 3) java_pool, -- see bug 18166499
       ROUND(SUM(CASE WHEN pool = 'java pool' AND name = 'free memory' THEN bytes ELSE 0 END)/POWER(2,30), 3) java_pool_free_memory,
       ROUND(SUM(CASE WHEN pool = 'streams pool' AND name IS NULL THEN bytes ELSE 0 END)/POWER(2,30), 3) streams_pool, -- see bug 18166499
       ROUND(SUM(CASE WHEN pool = 'streams pool' AND name = 'free memory' THEN bytes ELSE 0 END)/POWER(2,30), 3) streams_pool_free_memory
  FROM dba_hist_sgastat
 WHERE 1=1
 and dbid = TO_NUMBER(:DID)
   AND instance_number = TO_NUMBER(:INST_NUMBER )
   AND snap_id BETWEEN TO_NUMBER(:BgnSnap) AND TO_NUMBER(:EndSnap)
 GROUP BY
       snap_id
),
param AS (
SELECT /*+ MATERIALIZE NO_MERGE */
       snap_id,
       ROUND(SUM(CASE parameter_name WHEN '__db_cache_size' THEN TO_NUMBER(value) ELSE 0 END)/POWER(2,30), 3) buffer_cache,
       ROUND(SUM(CASE parameter_name WHEN '__shared_io_pool_size' THEN TO_NUMBER(value) ELSE 0 END)/POWER(2,30), 3) shared_io_pool,
       ROUND(SUM(CASE parameter_name WHEN '__shared_pool_size' THEN TO_NUMBER(value) ELSE 0 END)/POWER(2,30), 3) shared_pool,
       ROUND(SUM(CASE parameter_name WHEN '__large_pool_size' THEN TO_NUMBER(value) ELSE 0 END)/POWER(2,30), 3) large_pool,
       ROUND(SUM(CASE parameter_name WHEN '__java_pool_size' THEN TO_NUMBER(value) ELSE 0 END)/POWER(2,30), 3) java_pool,
       ROUND(SUM(CASE parameter_name WHEN '__streams_pool_size' THEN TO_NUMBER(value) ELSE 0 END)/POWER(2,30), 3) streams_pool,
       ROUND(SUM(CASE parameter_name WHEN '__sga_target' THEN TO_NUMBER(value) ELSE 0 END)/POWER(2,30), 3) sga_target,
       ROUND(SUM(CASE parameter_name WHEN '__pga_aggregate_target' THEN TO_NUMBER(value) ELSE 0 END)/POWER(2,30), 3) pga_aggregate_target
  FROM dba_hist_parameter
 WHERE 1=1 
 and dbid = TO_NUMBER(:DID)
   AND instance_number = TO_NUMBER(:INST_NUMBER )
   AND snap_id BETWEEN TO_NUMBER(:BgnSnap) AND TO_NUMBER(:EndSnap)
 --  AND parameter_name IN ('__db_cache_size', '__java_pool_size', '__large_pool_size', '__pga_aggregate_target', '__sga_target', '__shared_io_pool_size', '__shared_pool_size', '__streams_pool_size')
 GROUP BY
       snap_id
),
my_query AS (
SELECT /*+ MATERIALIZE NO_MERGE */
       s.snap_id,
       CAST(s.begin_interval_time AS DATE) begin_time,
       CAST(s.end_interval_time AS DATE) end_time,
       p.pga_aggregate_target,
       p.sga_target,
       p.buffer_cache,
       p.shared_pool,
       p.large_pool,
       p.java_pool,
       p.streams_pool,
       p.shared_io_pool,
       t.shared_pool_free_memory,
       t.large_pool_free_memory,
       t.java_pool_free_memory,
       t.streams_pool_free_memory
  FROM dba_hist_snapshot s,
       sgastat t,
       param p
 WHERE 1=1
 and s.dbid = TO_NUMBER(:DID)
   AND s.instance_number = TO_NUMBER(:INST_NUMBER )
   AND s.snap_id BETWEEN TO_NUMBER(:BgnSnap) AND TO_NUMBER(:EndSnap)
   AND t.snap_id = s.snap_id
   AND p.snap_id = s.snap_id
)
SELECT end_time,
       pga_aggregate_target,
       sga_target,
       buffer_cache,
       shared_pool,
       large_pool,
       java_pool,
       streams_pool,
       shared_io_pool,
       shared_pool_free_memory,
       large_pool_free_memory,
       java_pool_free_memory,
       streams_pool_free_memory
  FROM my_query
 ORDER BY
       snap_id
/



                                                                                                                Shared      Large       Java    Streams
                           PGA                                                                                  Pool       Pool       Pool       Pool
                     Aggregate      SGA     Buffer     Shared      Large       Java    Streams     Shared       Free       Free       Free       Free
End Time                Target   Target      Cache       Pool       Pool       Pool       Pool    IO Pool     Memory     Memory     Memory     Memory
------------------- ---------- -------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ----------
23-SEP-22                0.000      0.0      0.000      0.000      0.000      0.000      0.000      0.000      0.535      0.035      0.016      0.000
23-SEP-22                0.000      0.0      0.000      0.000      0.000      0.000      0.000      0.000      0.535      0.035      0.016      0.000
23-SEP-22                0.000      0.0      0.000      0.000      0.000      0.000      0.000      0.000      0.521      0.035      0.016      0.000





WITH
pgastat_denorm_1 AS (
SELECT /*+ MATERIALIZE NO_MERGE */
       snap_id,
       dbid,
       instance_number,
       SUM(CASE name WHEN 'PGA memory freed back to OS'           THEN value ELSE 0 END) pga_mem_freed_to_os,
       SUM(CASE name WHEN 'aggregate PGA auto target'             THEN value ELSE 0 END) aggr_pga_auto_target,
       SUM(CASE name WHEN 'aggregate PGA target parameter'        THEN value ELSE 0 END) aggr_pga_target_param,
       SUM(CASE name WHEN 'bytes processed'                       THEN value ELSE 0 END) bytes_processed,
       SUM(CASE name WHEN 'extra bytes read/written'              THEN value ELSE 0 END) extra_bytes_rw,
       SUM(CASE name WHEN 'global memory bound'                   THEN value ELSE 0 END) global_memory_bound,
       SUM(CASE name WHEN 'maximum PGA allocated'                 THEN value ELSE 0 END) max_pga_allocated,
       SUM(CASE name WHEN 'maximum PGA used for auto workareas'   THEN value ELSE 0 END) max_pga_used_aut_wa,
       SUM(CASE name WHEN 'maximum PGA used for manual workareas' THEN value ELSE 0 END) max_pga_used_man_wa,
       SUM(CASE name WHEN 'total PGA allocated'                   THEN value ELSE 0 END) tot_pga_allocated,
       SUM(CASE name WHEN 'total PGA inuse'                       THEN value ELSE 0 END) tot_pga_inuse,
       SUM(CASE name WHEN 'total PGA used for auto workareas'     THEN value ELSE 0 END) tot_pga_used_aut_wa,
       SUM(CASE name WHEN 'total PGA used for manual workareas'   THEN value ELSE 0 END) tot_pga_used_man_wa,
       SUM(CASE name WHEN 'total freeable PGA memory'             THEN value ELSE 0 END) tot_freeable_pga_mem
  FROM dba_hist_pgastat
 WHERE name IN
('PGA memory freed back to OS'
,'aggregate PGA auto target'
,'aggregate PGA target parameter'
,'bytes processed'
,'extra bytes read/written'
,'global memory bound'
,'maximum PGA allocated'
,'maximum PGA used for auto workareas'
,'maximum PGA used for manual workareas'
,'total PGA allocated'
,'total PGA inuse'
,'total PGA used for auto workareas'
,'total PGA used for manual workareas'
,'total freeable PGA memory'
)
   AND snap_id in (select snap_id from dba_hist_snapshot where begin_interval_time > sysdate -60)
 GROUP BY
       snap_id,
       dbid,
       instance_number
),
pgastat_denorm_2 AS (
SELECT /*+ MATERIALIZE NO_MERGE */
       h.dbid,
       h.instance_number,
       s.startup_time,
       MIN(h.pga_mem_freed_to_os) pga_mem_freed_to_os,
       MIN(h.bytes_processed) bytes_processed,
       MIN(h.extra_bytes_rw) extra_bytes_rw
  FROM pgastat_denorm_1 h,
       dba_hist_snapshot s
 WHERE s.snap_id = h.snap_id
   AND s.dbid = h.dbid
   AND s.instance_number = h.instance_number
 GROUP BY
       h.dbid,
       h.instance_number,
       s.startup_time
),
pgastat_delta AS (
SELECT /*+ MATERIALIZE NO_MERGE */
       h1.snap_id,
       h1.dbid,
       h1.instance_number,
       s1.begin_interval_time,
       s1.end_interval_time,
       ROUND((CAST(s1.end_interval_time AS DATE) - CAST(s1.begin_interval_time AS DATE)) * 24 * 60 * 60) interval_secs,
       (h1.pga_mem_freed_to_os - h0.pga_mem_freed_to_os) pga_mem_freed_to_os,
       h1.aggr_pga_auto_target,
       h1.aggr_pga_target_param,
       (h1.bytes_processed - h0.bytes_processed) bytes_processed,
       (h1.extra_bytes_rw - h0.extra_bytes_rw) extra_bytes_rw,
       h1.global_memory_bound,
       h1.max_pga_allocated,
       h1.max_pga_used_aut_wa,
       h1.max_pga_used_man_wa,
       h1.tot_pga_allocated,
       h1.tot_pga_inuse,
       h1.tot_pga_used_aut_wa,
       h1.tot_pga_used_man_wa,
       h1.tot_freeable_pga_mem
  FROM pgastat_denorm_1 h0,
       pgastat_denorm_1 h1,
       dba_hist_snapshot s0,
       dba_hist_snapshot s1,
       pgastat_denorm_2 min /* to see cumulative use (replace h0 with min on select list above) */
 WHERE h1.snap_id = h0.snap_id + 1
   AND h1.dbid = h0.dbid
   AND h1.instance_number = h0.instance_number
   AND s0.snap_id = h0.snap_id
   AND s0.dbid = h0.dbid
   AND s0.instance_number = h0.instance_number
   AND s1.snap_id = h1.snap_id
   AND s1.dbid = h1.dbid
   AND s1.instance_number = h1.instance_number
   AND s1.snap_id = s0.snap_id + 1
   AND s1.startup_time = s0.startup_time
   AND s1.begin_interval_time > (s0.begin_interval_time + (1 / (24 * 60))) /* filter out snaps apart < 1 min */
   AND min.dbid = s1.dbid
   AND min.instance_number = s1.instance_number
   AND min.startup_time = s1.startup_time
)
SELECT snap_id,
       TO_CHAR(MIN(begin_interval_time), 'YYYY-MM-DD HH24:MI') begin_time,
       TO_CHAR(MIN(end_interval_time), 'YYYY-MM-DD HH24:MI') end_time,
       ROUND(SUM(pga_mem_freed_to_os) / POWER(2, 30), 3) pga_mem_freed_to_os,
       ROUND(SUM(aggr_pga_auto_target) / POWER(2, 30), 3) aggr_pga_auto_target,
       ROUND(SUM(aggr_pga_target_param) / POWER(2, 30), 3) aggr_pga_target_param,
       ROUND(SUM(bytes_processed) / POWER(2, 30), 3) bytes_processed,
       ROUND(SUM(extra_bytes_rw) / POWER(2, 30), 3) extra_bytes_rw,
       ROUND(SUM(global_memory_bound) / POWER(2, 30), 3) global_memory_bound,
       ROUND(SUM(max_pga_allocated) / POWER(2, 30), 3) max_pga_allocated,
       ROUND(SUM(max_pga_used_aut_wa) / POWER(2, 30), 3) max_pga_used_aut_wa,
       ROUND(SUM(max_pga_used_man_wa) / POWER(2, 30), 3) max_pga_used_man_wa,
       ROUND(SUM(tot_pga_allocated) / POWER(2, 30), 3) tot_pga_allocated,
       ROUND(SUM(tot_pga_inuse) / POWER(2, 30), 3) tot_pga_inuse,
       ROUND(SUM(tot_pga_used_aut_wa) / POWER(2, 30), 3) tot_pga_used_aut_wa,
       ROUND(SUM(tot_pga_used_man_wa) / POWER(2, 30), 3) tot_pga_used_man_wa,
       ROUND(SUM(tot_freeable_pga_mem) / POWER(2, 30), 3) tot_freeable_pga_mem,
       0 dummy_15
  FROM pgastat_delta
 GROUP BY
       snap_id
 ORDER BY
       snap_id;
	  
	

=====	


https://weidongzhou.wordpress.com/2016/02/25/pga_aggregate_target-vs-pga_aggregate_limit/comment-page-1/

set linesize 700 pagesize 300	  
WITH
pgastat_denorm_1 AS (
SELECT /*+ MATERIALIZE NO_MERGE */
       snap_id,
       dbid,
       instance_number,
       SUM(CASE name WHEN 'PGA memory freed back to OS'           THEN value ELSE 0 END) pga_mem_freed_to_os,
       SUM(CASE name WHEN 'aggregate PGA auto target'             THEN value ELSE 0 END) aggr_pga_auto_target,
       SUM(CASE name WHEN 'aggregate PGA target parameter'        THEN value ELSE 0 END) aggr_pga_target_param,
       SUM(CASE name WHEN 'bytes processed'                       THEN value ELSE 0 END) bytes_processed,
       SUM(CASE name WHEN 'extra bytes read/written'              THEN value ELSE 0 END) extra_bytes_rw,
       SUM(CASE name WHEN 'global memory bound'                   THEN value ELSE 0 END) global_memory_bound,
       SUM(CASE name WHEN 'maximum PGA allocated'                 THEN value ELSE 0 END) max_pga_allocated,
       SUM(CASE name WHEN 'maximum PGA used for auto workareas'   THEN value ELSE 0 END) max_pga_used_aut_wa,
       SUM(CASE name WHEN 'maximum PGA used for manual workareas' THEN value ELSE 0 END) max_pga_used_man_wa,
       SUM(CASE name WHEN 'total PGA allocated'                   THEN value ELSE 0 END) tot_pga_allocated,
       SUM(CASE name WHEN 'total PGA inuse'                       THEN value ELSE 0 END) tot_pga_inuse,
       SUM(CASE name WHEN 'total PGA used for auto workareas'     THEN value ELSE 0 END) tot_pga_used_aut_wa,
       SUM(CASE name WHEN 'total PGA used for manual workareas'   THEN value ELSE 0 END) tot_pga_used_man_wa,
       SUM(CASE name WHEN 'total freeable PGA memory'             THEN value ELSE 0 END) tot_freeable_pga_mem
  FROM dba_hist_pgastat
 WHERE name IN
('PGA memory freed back to OS'
,'aggregate PGA auto target'
,'aggregate PGA target parameter'
,'bytes processed'
,'extra bytes read/written'
,'global memory bound'
,'maximum PGA allocated'
,'maximum PGA used for auto workareas'
,'maximum PGA used for manual workareas'
,'total PGA allocated'
,'total PGA inuse'
,'total PGA used for auto workareas'
,'total PGA used for manual workareas'
,'total freeable PGA memory'
)
   AND snap_id in (select snap_id from dba_hist_snapshot where begin_interval_time > sysdate -60)
 GROUP BY
       snap_id,
       dbid,
       instance_number
),
pgastat_denorm_2 AS (
SELECT /*+ MATERIALIZE NO_MERGE */
       h.dbid,
       h.instance_number,
       s.startup_time,
       MIN(h.pga_mem_freed_to_os) pga_mem_freed_to_os,
       MIN(h.bytes_processed) bytes_processed,
       MIN(h.extra_bytes_rw) extra_bytes_rw
  FROM pgastat_denorm_1 h,
       dba_hist_snapshot s
 WHERE s.snap_id = h.snap_id
   AND s.dbid = h.dbid
   AND s.instance_number = h.instance_number
 GROUP BY
       h.dbid,
       h.instance_number,
       s.startup_time
),
pgastat_delta AS (
SELECT /*+ MATERIALIZE NO_MERGE */
       h1.snap_id,
       h1.dbid,
       h1.instance_number,
       s1.begin_interval_time,
       s1.end_interval_time,
       ROUND((CAST(s1.end_interval_time AS DATE) - CAST(s1.begin_interval_time AS DATE)) * 24 * 60 * 60) interval_secs,
       (h1.pga_mem_freed_to_os - h0.pga_mem_freed_to_os) pga_mem_freed_to_os,
       h1.aggr_pga_auto_target,
       h1.aggr_pga_target_param,
       (h1.bytes_processed - h0.bytes_processed) bytes_processed,
       (h1.extra_bytes_rw - h0.extra_bytes_rw) extra_bytes_rw,
       h1.global_memory_bound,
       h1.max_pga_allocated,
       h1.max_pga_used_aut_wa,
       h1.max_pga_used_man_wa,
       h1.tot_pga_allocated,
       h1.tot_pga_inuse,
       h1.tot_pga_used_aut_wa,
       h1.tot_pga_used_man_wa,
       h1.tot_freeable_pga_mem
  FROM pgastat_denorm_1 h0,
       pgastat_denorm_1 h1,
       dba_hist_snapshot s0,
       dba_hist_snapshot s1,
       pgastat_denorm_2 min /* to see cumulative use (replace h0 with min on select list above) */
 WHERE h1.snap_id = h0.snap_id + 1
   AND h1.dbid = h0.dbid
   AND h1.instance_number = h0.instance_number
   AND s0.snap_id = h0.snap_id
   AND s0.dbid = h0.dbid
   AND s0.instance_number = h0.instance_number
   AND s1.snap_id = h1.snap_id
   AND s1.dbid = h1.dbid
   AND s1.instance_number = h1.instance_number
   AND s1.snap_id = s0.snap_id + 1
   AND s1.startup_time = s0.startup_time
   AND s1.begin_interval_time > (s0.begin_interval_time + (1 / (24 * 60))) /* filter out snaps apart < 1 min */
   AND min.dbid = s1.dbid
   AND min.instance_number = s1.instance_number
   AND min.startup_time = s1.startup_time
)
SELECT snap_id,
       TO_CHAR(MIN(begin_interval_time), 'YYYY-MM-DD HH24:MI') begin_time,
       TO_CHAR(MIN(end_interval_time), 'YYYY-MM-DD HH24:MI') end_time,
       ROUND(SUM(pga_mem_freed_to_os) / POWER(2, 30), 3) pga_mem_freed_to_os,
       ROUND(SUM(aggr_pga_auto_target) / POWER(2, 30), 3) aggr_pga_auto_target,
       ROUND(SUM(aggr_pga_target_param) / POWER(2, 30), 3) aggr_pga_target_param,
       ROUND(SUM(bytes_processed) / POWER(2, 30), 3) bytes_processed,
       ROUND(SUM(extra_bytes_rw) / POWER(2, 30), 3) extra_bytes_rw,
       ROUND(SUM(global_memory_bound) / POWER(2, 30), 3) global_memory_bound,
       ROUND(SUM(max_pga_allocated) / POWER(2, 30), 3) max_pga_allocated,
       ROUND(SUM(max_pga_used_aut_wa) / POWER(2, 30), 3) max_pga_used_aut_wa,
       ROUND(SUM(max_pga_used_man_wa) / POWER(2, 30), 3) max_pga_used_man_wa,
       ROUND(SUM(tot_pga_allocated) / POWER(2, 30), 3) tot_pga_allocated,
       ROUND(SUM(tot_pga_inuse) / POWER(2, 30), 3) tot_pga_inuse,
       ROUND(SUM(tot_pga_used_aut_wa) / POWER(2, 30), 3) tot_pga_used_aut_wa,
       ROUND(SUM(tot_pga_used_man_wa) / POWER(2, 30), 3) tot_pga_used_man_wa,
       ROUND(SUM(tot_freeable_pga_mem) / POWER(2, 30), 3) tot_freeable_pga_mem,
       0 dummy_15
  FROM pgastat_delta
 GROUP BY
       snap_id
 ORDER BY
       snap_id;
	   
	Snap ID Begin Time          End Time            PGA_MEM_FREED_TO_OS AGGR_PGA_AUTO_TARGET AGGR_PGA_TARGET_PARAM BYTES_PROCESSED EXTRA_BYTES_RW GLOBAL_MEMORY_BOUND MAX_PGA_ALLOCATED MAX_PGA_USED_AUT_WA MAX_PGA_USED_MAN_WA TOT_PGA_ALLOCATED TOT_PGA_INUSE TOT_PGA_USED_AUT_WA TOT_PGA_USED_MAN_WA TOT_FREEABLE_PGA_MEM   DUMMY_15
-------- ------------------- ------------------- ------------------- -------------------- --------------------- --------------- -------------- ------------------- ----------------- ------------------- ------------------- ----------------- ------------- ------------------- ------------------- -------------------- ----------
    8399 2022-09-14 21:00    2022-09-14 22:00                   .009                 .644                 2.666           1.233              0                .267             2.528                .182       .028              2.257         1.954                .006                   0                 .035          0
    8400 2022-09-14 22:00    2022-09-14 23:00                   .005                 .717                 2.666            3.32              0                .267             2.537                .182       .028               2.13         1.869                   0                   0                 .035          0
    8403 2022-09-16 06:16    2022-09-16 07:00                   .008                 .706                 2.666            .578              0                .267             2.537                .182       .028              2.126         1.886                   0                   0                 .035          0
    8404 2022-09-16 07:00    2022-09-16 08:00                   .007                 .716                 2.666            .847              0                .267             2.537                .182       .028              2.118         1.879                   0                   0                 .034          0
    8405 2022-09-16 08:00    2022-09-16 09:00                   .009                 .718                 2.666            .865              0                .267             2.537                .182       .028              2.117         1.878                   0                   0                 .034          0
    8406 2022-09-16 09:00    2022-09-16 10:00                    .01                 .709                 2.666            .858              0                .267             2.537                .182       .028              2.128         1.886                   0                   0                 .036          0
    8407 2022-09-16 10:00    2022-09-16 11:00                   .007                 .696                 2.666            .966              0                .267             2.537                .182       .028              2.143         1.901                   0                   0                 .035          0
    8408 2022-09-16 11:00    2022-09-16 12:00                   .009                 .698                 2.666            .864              0                .267             2.537                .182       .028          
	
	
	
	col NAME for a40
SELECT NAME, VALUE, UNIT FROM V$PGASTAT 
where
NAME in ( 'aggregate PGA target parameter', 'aggregate PGA auto target', 'total PGA inuse ', 
'total PGA allocated', 'maximum PGA used for auto workareas', 'cache hit percentage', 'over allocation count');

NAME                                          VALUE UNIT
---------------------------------------- ---------- ------------
aggregate PGA target parameter           1431306240 bytes
aggregate PGA auto target                 348337152 bytes
total PGA allocated                      1173649408 bytes
maximum PGA used for auto workareas        98097152 bytes
over allocation count                             0
cache hit percentage                          99.99 percent

6 rows selected.




SELECT * FROM (
  SELECT 
         count(*) AS count,
         user_id, program, module, machine, sql_id
  FROM SYS.DBA_HIST_ACTIVE_SESS_HISTORY
  WHERE sample_time > sysdate-1
  AND sample_time < sysdate
 -- AND pga_allocated > 1024*1024*1024
  GROUP BY user_id, program, module, machine, sql_id
  ORDER BY count(*) DESC
)
WHERE rownum <= 20



define sql_id='8cnh50qfgwg73'



SELECT    sql_id, 
       TO_CHAR(sample_time,'DD-MON-YYYY HH24:MI:SS') AS sample_time, 
       pga_allocated
FROM SYS.DBA_HIST_ACTIVE_SESS_HISTORY
WHERE sample_time > sysdate-1
AND sample_time < sysdate
AND sql_id = '&SQL_ID'
ORDER BY sample_time;



set lines 155
col execs for 999,999,999
col avg_etime for 999,999.999
col avg_lio for 9,999,999,999.9
col avg_pio for 9,999,999,999.9
col begin_interval_time for a30
col node for 99999
break on plan_hash_value on startup_time skip 1
select ss.snap_id, ss.instance_number node, begin_interval_time, sql_id, plan_hash_value,
nvl(executions_delta,0) execs,
(elapsed_time_delta/decode(nvl(executions_delta,0),0,1,executions_delta))/1000000 avg_etime,
(buffer_gets_delta/decode(nvl(executions_delta,0),0,1,executions_delta)) avg_lio,
(disk_reads_delta/decode(nvl(executions_delta,0),0,1,executions_delta)) avg_pio,
rows_processed_delta total_rows
from DBA_HIST_SQLSTAT S, DBA_HIST_SNAPSHOT SS
where sql_id = nvl('&sql_id','8cnh50qfgwg73')
and ss.snap_id = S.snap_id
and ss.instance_number = S.instance_number
and s.instance_number like nvl('&instance_number',s.instance_number)
order by 1, 2, 3
/



col sid for 99999 
col operation for a20
col start_time for a20
col expected_size_MB for 99,999.9 
col Act_Used_MB for 99,999.9 
col Max_Used_MB for 99,999.9
col TEMP_Seg_MB for 999,999
select to_char(sql_exec_start, 'yyyy-mm-dd hh24:mi:ss') start_time, sql_id,
       to_number(decode(sid, 65535, NULL, sid)) sid,
       operation_type operation, trunc(expected_size/1024/1024) expected_size_MB,
       trunc(actual_mem_used/1024/1024) Act_Used_MB, trunc(max_mem_used/1024/1204) Max_Used_MB,
       number_passes pass, trunc(tempseg_size/1024/1024) TEMP_Seg_MB
FROM gv$sql_workarea_active
where 1=1
and SQL_ID='&SQL_ID'
ORDER BY 1,2;


	   
define top=50	
col STAR for a50		   
select SQL_ID,round(PGA_MB,1) PGA_MB,percent,rpad('*',percent*10/100,'*') star
from
(
select SQL_ID,sum(DELTA_PGA_MB) PGA_MB ,(ratio_to_report(sum(DELTA_PGA_MB)) over ())*100 percent,rank() over(order by sum(DELTA_PGA_MB) desc) rank
from
(
select SESSION_ID,SESSION_SERIAL#,sample_id,SQL_ID,SAMPLE_TIME,IS_SQLID_CURRENT,SQL_CHILD_NUMBER,PGA_ALLOCATED,
greatest(PGA_ALLOCATED - first_value(PGA_ALLOCATED) over (partition by SESSION_ID,SESSION_SERIAL# order by sample_time rows 1 preceding),0)/power(1024,2) "DELTA_PGA_MB"
from
gv$active_session_history
where
IS_SQLID_CURRENT='Y'
and sample_time > sysdate - interval '30' minute
order by 1,2,3,4
)
group by sql_id
having sum(DELTA_PGA_MB) > 0
)
where rank < (&top+1)
order by rank

Saturday, 6 March 2010

Oracle 10g Advance Function

Oracle Advance Function



Function Name Description
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
REGEXP_LIKE
Similar to the LIKE operator, but performs
regular expression matching instead of
simple pattern matching
REGEXP_INSTR
Searches for a given string for a regular
expression pattern and returns the position
were the match is found
REGEXP_REPLACE
Searches for a regular expression pattern and
replaces it with a replacement string
REGEXP_SUBSTR
Searches for a regular expression pattern
within a given string and returns the matched
substring
REGEXP_COUNT
Searches for a regular expression pattern and
returns the count


REGEXP_LIKE
(sourcestr, pattern [,options])
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
options: are as follows
'c': Use case-sensitive matching (default)
'i': Use case-insensitive matching
'n': Allow match-any-character operator
'm': Treat source string as multiple line



options: are as follows
'c': Use case-sensitive matching (default)
'i': Use case-insensitive matching
'n': Allow match-any-character operator
'm': Treat source string as multiple line

options: are as follows
'c': Use case-sensitive matching (default)
'i': Use case-insensitive matching
'n': Allow match-any-character operator
'm': Treat source string as multiple line

options: are as follows
'c': Use case-sensitive matching (default)
'i': Use case-insensitive matching
'n': Allow match-any-character operator
'm': Treat source string as multiple line


options: are as follows
'c': case sensitive search/match
'i': case insensitive search/match
'm': parses the source string as individual lines
's': parses the source string as a single line
'n': allows a period (.) wild character to match a newline
'x': instructs parser to ignore whitespace characters


Character Class Description
^ Anchor the expression to the start of a line
$ Anchor the expression to the end of a line


Equivalence Classes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Character Class Description
= = Oracle supports the equivalence classes through
the POSIX '[==]' syntax. A base letter and all of
its accented versions constitute an equivalence
class. For example, the equivalence class '[=a=]'
matches ä and â. The equivalence classes are valid
only inside the bracketed expression


Match Options determine if the target is treated checked for
case-sensitivity and whether or not the target is evaluated
line by line or as a continuous string.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Character Class Description
c Case sensitive matching
i Case insensitive matching
m Treat source string as multi-line activating Anchor chars
n Allow the period (.) to match any newline character


Posix Characters tend to look very ugly but have the advantage
that also take into account the 'locale', that is, any variant
of the local language/coding system.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Character Class Description
[:digit:] Only the digits 0 to 9
[:alnum:] Any alphanumeric character 0 to 9 OR A to Z or a to z.
[:alpha:] Any alpha character A to Z or a to z.
[:blank:] Space and TAB characters only.
[:xdigit:] Hexadecimal notation 0-9, A-F, a-f.
[:punct:] Punctuation symbols
--------------------------------
% . , " ' ? ! : # $ & ( ) * ;
+ - / = @ [ ] \ ^ _ { } | ~
--------------------------------
[:print:] Any printable character.
[:space:] Any whitespace characters (space, tab, NL, FF, VT, CR).
Many system abbreviate as \s.
[:graph:] Exclude whitespace (SPACE, TAB). Many system abbreviate as \W.
[:upper:] Any alpha character A to Z.
[:lower:] Any alpha character a to z.
[:cntrl:] Control Characters NL CR LF TAB VT FF NUL SOH STX
EXT EOT ENQ ACK SO SI DLE DC1 DC2 DC3 DC4 NAK SYN
ETB CAN EM SUB ESC IS1 IS2 IS3 IS4 DEL.


Quantifier Characters control the number of times a character
or string is found in a search.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Character Class Description
* Match 0 or more times
? Match 0 or 1 time
+ Match 1 or more times
{m} Match exactly m times
{m,} Match at least m times
{m, n} Match at least m times but no more than n times
\n Cause the previous expression to be repeated n times


Alternative Matching And Grouping Characters
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Character Class Description
| Separates alternates, often used with grouping
operator ()

( ) Groups subexpression into a unit for alternations, for
quantifiers, or for backreferencing

[char] Indicates a character list; most metacharacters inside a
character list are understood as literals, with the
exception of character classes, and the ^
and - metacharacters


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Regex Cheat Sheet (non-posix)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


Modifiers:
i case-insensitive pattern matching.

g global replace, or replace all

m Treat string as multiple lines. That is,
change ``^'' and ``$'' from matching at only
the very start or end of the string to the
start or end of any line anywhere within the string

s Treat string as single line. That is, change ``.'' to
match any character whatsoever, even a newline, which
it normally would not match.

x Extend your pattern's legibility by permitting
whitespace and comments.


Special Characters:
The following should be escaped if you are trying to
match that character:

\ ^ . $ | ( ) [ ]
* + ? { } ,


Special Character Definitions:
\ Quote the next metacharacter
^ Match the beginning of the line
. Match any character (except newline)
$ Match the end of the line (or before newline at the end)
| Alternation
() Grouping
[] Character class
* Match 0 or more times
+ Match 1 or more times
? Match 1 or 0 times
{n} Match exactly n times
{n,} Match at least n times
{n,m} Match at least n but not more than m times

More Special Characters:
\t tab (HT, TAB)
\n newline (LF, NL)
\r return (CR)
\f form feed (FF)
\a alarm (bell) (BEL)
\e escape (think troff) (ESC)
\033 octal char (think of a PDP-11)
\x1B hex char
\c[ control char
\l lowercase next char (think vi)
\u uppercase next char (think vi)
\L lowercase till \E (think vi)
\U uppercase till \E (think vi)
\E end case modification (think vi)
\Q quote (disable) pattern metacharacters till \E

\w Match a "word" character (alphanumeric plus "_")
\W Match a non-word character
\s Match a whitespace character
\S Match a non-whitespace character
\d Match a digit character
\D Match a non-digit character
\b Match a word boundary
\B Match a non-(word boundary)
\A Match only at beginning of string
\Z Match only at end of string, or before newline at the end
\z Match only at end of string
\G Match only where previous m//g left off (works only with /g)



SQL> select regexp_instr('WBBCDFFGT','B+C') from dual;

REGEXP_INSTR('WBBCDFFGT','B+C')
-------------------------------
2



Where one and more occurrence of b followed by C




select regexp_instr('WBBCDFFGT','B.C') cc from dual;



SQL> select regexp_instr('WBBCDFFGET bbc','(b+c)$') from dual;

REGEXP_INSTR('WBBCDFFGETBBC','(B+C)$')
--------------------------------------
12




if yes it occurrs at the end of line


SQL> select regexp_instr('AAAAAAAAAAAABBCFFGGR','B+C(G|F){4}') from dual;

REGEXP_INSTR('AAAAAAAAAAAABBCFFGGR','B+C(G|F){4}')
--------------------------------------------------
13


One ore more occurrencees of B followed by C follwed by four Occurrence og G or F begin


select regexp_instr('ABBCD HJHF SDFF GBBCFFGGR','[$F]') from dual;


SQL> select regexp_instr('ABBCD HJHF SDFF GBBCFFGGR','[$F]') from dual;

REGEXP_INSTR('ABBCDHJHFSDFFGBBCFFGGR','[$F]')
---------------------------------------------
10




SQL> select regexp_instr('ABBCD H123 1234B BCFF GBBCFFGGR','[[:digit:]]{4}') from dual ;

REGEXP_INSTR('ABBCDH1231234BBCFFGBBCFFGGR','[[:DIGIT:]]{4}')
------------------------------------------------------------
12








SELECT park_name,
SUBSTR(
description,
REGEXP_INSTR(description, '[^ ]+ acres|[^ ]+-acre',1,1,0,'i'), -- start
REGEXP_INSTR(description, '[^ ]+ acres|[^ ]+-acre',1,1,1,'i') -- minus
REGEXP_INSTR(description, '[^ ]+ acres|[^ ]+-acre',1,1,0,'i') -- nbr
) acres
FROM michigan_park
WHERE
REGEXP_LIKE(description, '[^ ]+ acres|[^ ]+-acre','i');

SELECT table_name,
index_name,
monitoring,
used,
start_monitoring,
end_monitoring
FROM v$object_usage
WHERE table_name = 'LOCATION_CODE' ;


Function Name Description
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
REGEXP_LIKE
Similar to the LIKE operator, but performs
regular expression matching instead of
simple pattern matching
REGEXP_INSTR
Searches for a given string for a regular
expression pattern and returns the position
were the match is found
REGEXP_REPLACE
Searches for a regular expression pattern and
replaces it with a replacement string
REGEXP_SUBSTR
Searches for a regular expression pattern
within a given string and returns the matched
substring
REGEXP_COUNT
Searches for a regular expression pattern and
returns the count


options: are as follows
'c': Use case-sensitive matching (default)
'i': Use case-insensitive matching
'n': Allow match-any-character operator
'm': Treat source string as multiple line


options: are as follows
'c': Use case-sensitive matching (default)
'i': Use case-insensitive matching
'n': Allow match-any-character operator
'm': Treat source string as multiple line

'c': Use case-sensitive matching (default)
'i': Use case-insensitive matching
'n': Allow match-any-character operator
'm': Treat source string as multiple line

'c': Use case-sensitive matching (default)
'i': Use case-insensitive matching
'n': Allow match-any-character operator
'm': Treat source string as multiple line

'c': case sensitive search/match
'i': case insensitive search/match
'm': parses the source string as individual lines
's': parses the source string as a single line
'n': allows a period (.) wild character to match a newline
'x': instructs parser to ignore whitespace characters

Character Class Description
^ Anchor the expression to the start of a line
$ Anchor the expression to the end of a line


Equivalence Classes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Character Class Description
= = Oracle supports the equivalence classes through
the POSIX '[==]' syntax. A base letter and all of
its accented versions constitute an equivalence
class. For example, the equivalence class '[=a=]'
matches ä and â. The equivalence classes are valid
only inside the bracketed expression


Match Options determine if the target is treated checked for
case-sensitivity and whether or not the target is evaluated
line by line or as a continuous string.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Character Class Description
c Case sensitive matching
i Case insensitive matching
m Treat source string as multi-line activating Anchor chars
n Allow the period (.) to match any newline character


Posix Characters tend to look very ugly but have the advantage
that also take into account the 'locale', that is, any variant
of the local language/coding system.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Character Class Description

[:digit:] Only the digits 0 to 9
[:alnum:] Any alphanumeric character 0 to 9 OR A to Z or a to z.
[:alpha:] Any alpha character A to Z or a to z.
[:blank:] Space and TAB characters only.
[:xdigit:] Hexadecimal notation 0-9, A-F, a-f.
[:punct:] Punctuation symbols
--------------------------------
% . , " ' ? ! : # $ & ( ) * ;
+ - / = @ [ ] \ ^ _ { } | ~
--------------------------------
[:print:] Any printable character.
[:space:] Any whitespace characters (space, tab, NL, FF, VT, CR).
Many system abbreviate as \s.
[:graph:] Exclude whitespace (SPACE, TAB). Many system abbreviate as \W.
[:upper:] Any alpha character A to Z.
[:lower:] Any alpha character a to z.
[:cntrl:] Control Characters NL CR LF TAB VT FF NUL SOH STX
EXT EOT ENQ ACK SO SI DLE DC1 DC2 DC3 DC4 NAK SYN
ETB CAN EM SUB ESC IS1 IS2 IS3 IS4 DEL.


Quantifier Characters control the number of times a character
or string is found in a search.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Character Class Description
* Match 0 or more times
? Match 0 or 1 time
+ Match 1 or more times
{m} Match exactly m times
{m,} Match at least m times
{m, n} Match at least m times but no more than n times
\n Cause the previous expression to be repeated n times


Alternative Matching And Grouping Characters
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Character Class Description
| Separates alternates, often used with grouping
operator ()

( ) Groups subexpression into a unit for alternations, for
quantifiers, or for backreferencing

[char] Indicates a character list; most metacharacters inside a
character list are understood as literals, with the
exception of character classes, and the ^
and - metacharacters


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Regex Cheat Sheet (non-posix)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


Modifiers:
i case-insensitive pattern matching.

g global replace, or replace all

m Treat string as multiple lines. That is,
change ``^'' and ``$'' from matching at only
the very start or end of the string to the
start or end of any line anywhere within the string

s Treat string as single line. That is, change ``.'' to
match any character whatsoever, even a newline, which
it normally would not match.

x Extend your pattern's legibility by permitting
whitespace and comments.


Special Characters:
The following should be escaped if you are trying to
match that character:

\ ^ . $ | ( ) [ ]
* + ? { } ,


Special Character Definitions:

\ Quote the next metacharacter
^ Match the beginning of the line
. Match any character (except newline)
$ Match the end of the line (or before newline at the end)
| Alternation
() Grouping
[] Character class
* Match 0 or more times
+ Match 1 or more times
? Match 1 or 0 times
{n} Match exactly n times
{n,} Match at least n times
{n,m} Match at least n but not more than m times

More Special Characters:

\t tab (HT, TAB)
\n newline (LF, NL)
\r return (CR)
\f form feed (FF)
\a alarm (bell) (BEL)
\e escape (think troff) (ESC)
\033 octal char (think of a PDP-11)
\x1B hex char
\c[ control char
\l lowercase next char (think vi)
\u uppercase next char (think vi)
\L lowercase till \E (think vi)
\U uppercase till \E (think vi)
\E end case modification (think vi)
\Q quote (disable) pattern metacharacters till \E

Even More Special Characters:
\w Match a "word" character (alphanumeric plus "_")
\W Match a non-word character
\s Match a whitespace character
\S Match a non-whitespace character
\d Match a digit character
\D Match a non-digit character
\b Match a word boundary
\B Match a non-(word boundary)
\A Match only at beginning of string
\Z Match only at end of string, or before newline at the end
\z Match only at end of string
\G Match only where previous m//g left off (works only with /g)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Labels: Sql Plus/ PLSQL

Posted by Sänjay at 6/15/2009



regexp_instr (string, pattern, position, occurence, return-option, parameters)

regexp_instr (
string,
pattern,
position,
occurrence,
return-option,
parameters)





parameters can be a combination of

* i: to match case insensitively
* c: to match case sensitively
* n: to make the dot (.) match new lines as well
* m: to make ^ and $ match beginning and end of a line in a multiline string
* x: to ignore white spaces.

* match 0 or more times
+ match 1 or more times
? match 0 or 1 time
^ start of the expression
$ end of the the expression
{m} match exactly m times
{m,} match at least m times
{m, n} match at least m times but no more than n times
| alternate operator
( ) group used for subexpression and backreferencing
[char] character List (can be used as literals except ^ ,- and character class)
\digit backslash followed by a digit between 1 and 9 ,used for backrerencing the respective subexpression.
[:alpha:] alphabetic characters
[:lower:] lowercase alphabetic characters
[:upper:] uppercase alphabetic characters
[:digit:] numeric digits
[:alnum:] alphanumeric characters
[:space:] nonprinting space characters e.g. carriage return, newline, vertical tab, and form feed
[:punct:] punctuation characters
[:cntrl:] nonprinting control characters
[:print:] printable characters



regexp_instr is an Oracle SQL function that enables regular expressions in queries.
It enhances the 'traditional' instr.




create table ADDRESSES(addr varchar2(50));

insert into ADDRESSES
values ('123 4TH sT.');

insert into ADDRESSES
values ('4 mAPLE $T.');

insert into ADDRESSES
values ('2167 GREENBRIER bLVD.');

insert into ADDRESSES
values ('33 tHIRD sT.');

insert into ADDRESSES
values ('oNE FIRST dRIVE');

insert into ADDRESSES
values ('1664 1/2 sPRINGHILL aVE');

insert into ADDRESSES
values ('2003 GEAUX iLLINI dR.');


select regexp_instr('Mark has a cold','a') position from dual;


SQL> select regexp_instr('Mark has a cold','a') position from dual;

REGEXP_INSTR('MARKHASACOLD','A')
--------------------------------
2




select regexp_instr('Mark has a cold','a',1) position from dual;


select regexp_instr('Mark has a cold','a',1,3) position from dual;



select regexp_instr('qqqqaa','a') position from dual;


SELECT REGEXP_INSTR('Joe Smith, 10045 Berry Lane, San Joseph, CA 91234','[[:digit:]]{5}$')
AS rx_instr FROM dual


select REGEXP_INSTR('Mary has a cold','a',3) position FROM dual




select regexp_instr('Mark has a cold','a',1,2) position from dual;

REGEXP_INSTR('MARKHASACOLD','A',1,2)
------------------------------------
7

select regexp_instr('Mark has a cold','a',1,1) position from dual;

REGEXP_INSTR('MARKHASACOLD','A',1,1)
------------------------------------
2

select regexp_instr('Mark has a cold','a',1,3) position from dual;

REGEXP_INSTR('MARKHASACOLD','A',1,3)
------------------------------------
10


SELECT REGEXP_INSTR('1234567890', '(123)(4(56)(78))', 1, 1, 0, 'i', 4) "REGEXP_INSTR" FROM DUAL;


SELECT REGEXP_INSTR('500 Oracle Parkway, Redwood Shores, CA','[ ]+', 1, 6)
"REGEXP_INSTR" FROM DUAL;


* '^' for the beginning of a string
* '$' for the end of string
* '.' for any character

* Ranges of characters, such as '[a-z]', for any ASCII lowercase letter,
which is equivalent to the character class: "[[:lower:]]""

* '?' allows a preceding character to match zero or one time
* '+' allows a preceding character to match one or more times
* '*' for zero or more times





SQL> select regexp_instr('AAAAAAAAAAAABBCFFGGR','B+C(G|F){4}') from dual;

REGEXP_INSTR('AAAAAAAAAAAABBCFFGGR','B+C(G|F){4}')
--------------------------------------------------
13


One ore more occurrencees of B followed by C follwed by four Occurrence og G or F begin


select regexp_instr('ABBCD HJHF SDFF GBBCFFGGR','[$F]') from dual;


SQL> select regexp_instr('ABBCD HJHF SDFF GBBCFFGGR','[$F]') from dual;

REGEXP_INSTR('ABBCDHJHFSDFFGBBCFFGGR','[$F]')
---------------------------------------------
10




SQL> select regexp_instr('ABBCD H123 1234B BCFF GBBCFFGGR','[[:digit:]]{4}') from dual ;

REGEXP_INSTR('ABBCDH1231234BBCFFGBBCFFGGR','[[:DIGIT:]]{4}')
------------------------------------------------------------
12




select regexp_instr('ABBCD HJHF SDFFB , BCFF GBBCFFGR, AA','[^ ]+',1,2) from dual;

select regexp_instr('ABBCD HJHF SDFFB , BCFF GBBCFFGR, AA','[ ]+',1,2) from dual;


select regexp_instr('ABBCD HJHF SDFFB , BCFF GBBCFFGR, AA','[ ]+',1,1) from dual;


select regexp_instr('ABBCD HJHF SDFFB , BCFF GBBCFFGR, AA','[ ]',1,1) from dual;

select regexp_instr(' ABBCD HJHF SDFFB , BCFF GBBCFFGR, AA','[ ]',1,1) from dual;

select regexp_instr('ABBCD HJHF SDFFB , BCFF GBBCFFGR, AA','[ ]',1,1) from dual;



SQL> select regexp_instr(' ABBCD HJHF SDFFB , BCFF GBBCFFGR, AA','[^ ]',1,1) from dual;



REGEXP_INSTR('ABBCDHJHFSDFFB,BCFFGBBCFFGR,AA','[^]',1,1)
--------------------------------------------------------
3


first Non black value



SQL> select regexp_instr('BBBBBBBCC','[^B]') from dual;

REGEXP_INSTR('BBBBBBBCC','[^B]')
--------------------------------
8



first non b char

SQL> select regexp_instr('ABBBRD HJHF ODFFB, BCFF RBBCFFGR, AA','[r|o][[:alpha:]]{4}',2,2,1,'i') from dual ;

REGEXP_INSTR('ABBBRDHJHFODFFB,BCFFRBBCFFGR,AA','[R|O][[:ALPHA:]]{4}',2,2,1,'I')
-------------------------------------------------------------------------------
30








create table history ( empno NUMBER(4)
, beginyear NUMBER(4)
, begindate DATE
, enddate DATE
, deptno NUMBER(2)
, msal NUMBER(6,2)
, comments VARCHAR2(60)
) ;


insert into history values (9,2000,date '2000-01-01',date '2002-01-02',40, 950,'history for 9');
insert into history values (8,2000,date '2000-01-02', NULL ,20, 800,'');
insert into history values (7,1988,date '2000-01-06',date '2002-01-07',30,1000,'');
insert into history values (6,1989,date '2000-01-07',date '2002-01-12',30,1300,'');
insert into history values (5,1993,date '2000-01-12',date '2002-01-10',30,1500,'history for 5');
insert into history values (4,1995,date '2000-01-10',date '2002-01-11',30,1700,'');
insert into history values (3,1999,date '2000-01-11', NULL ,30,1600,'');
insert into history values (2,1986,date '2000-01-10',date '2002-01-08',20,1000,'history for 2');
insert into history values (1,1987,date '2000-01-08',date '2002-01-01',30,1000,'history for 1');
insert into history values (7,1989,date '2000-01-01',date '2002-05-12',30,1150,'history for 7');
select comments from history where regexp_instr(comments, '[^ ]+', 1, 9) > 0;

SELECT REGEXP_SUBSTR('This is a sentence.','.*[^.!:]') FROM dual;


from esearch.ent_search_update_table

ESEARCH.ENT_SEARCH_UPDATE_VIEW




WITH t AS (SELECT 'abc' col1
FROM dual
UNION
SELECT '123'
FROM dual
UNION
SELECT 'a2'
FROM dual
UNION
SELECT '1b'
FROM dual
UNION
SELECT '!'
FROM dual
)
SELECT t.col1
, REGEXP_SUBSTR(t.col1, '[[:alpha:]][[:digit:]]|[[:digit:]][[:alpha:]]') check_cond
FROM t
;



col EX1 format a10
col EX2 format a10


with t as (
select 'ABCDEFG' col1 from dual union
select '123456ABCDEFG' col1 from dual union
select 'ZZZ123456ABCDEFG' col1 from dual union
select 'GFEDCBA123456' col1 from dual)
-- end of sample data
select regexp_replace(col1, '[[:digit:]]') ex1,
regexp_replace(col1, '\d') ex2



SQL> SELECT REGEXP_INSTR ('BCDEFG123456',
'[[:alpha:]]',
1,
1,
0,
'i'
) alpha_pos
FROM DUAL;

ALPHA_POS
----------
1




SQL> select substr (x,1,REGEXP_INSTR(x,'[[:alpha:]]')) Allpha,substr (x,REGEXP_INSTR(x,'[[:alpha:]]|[[:punct:]]')) "alphaapunct" ,x from test3
2 ;

ALLPHA
----------------------------------------
alphaapunct X
---------------------------------------- ----------
d
dd dd

d
dddd dddd

,d
,dddd ,dddd


SQL> col Allpha format a10
SQL> col alphaapunct format a10
SQL> /


SQL> create table test3 ( x varchar2(10));

Table created.

SQL> insert into test3 values (' dd');

1 row created.

SQL> insert into test3 values ('dddd');

1 row created.

SQL> commit;


SQL> insert into test3 values (' ,dddd');

1 row created.

SQL> commit;

Commit complete.








ALLPHA alphaapunc X
---------- ---------- ----------
d dd dd
d dddd dddd
,d ,dddd ,dddd





SQL> select * from test3;

X
----------
dd
dddd
,dddd


SQL> insert into test3 values (' ggg^M');

1 row created.

SQL> commit;

Commit complete.





SQL> select REGEXP_INSTR(x,'[[:cntrl:]]') from test3
2 /

REGEXP_INSTR(X,'[[:CNTRL:]]')
-----------------------------
0
0
0
5





SQL> --[:cntrl:] matches control characters.
SQL> SELECT description
2 FROM testTable
3 WHERE NOT REGEXP_LIKE(description,'[:cntrl]');



SQL> insert into test3 values ('ggg^M');

1 row created.


this is control vm

select REGEXP_INSTR(x,'[[:cntrl:]]+') from test3;

REGEXP_INSTR(X,'[[:CNTRL:]]+')
------------------------------
0
0
0
5
0
0
0
4

8 rows selected.



select REGEXP_INSTR(x,'[[:cntrl:]]+') from test3;

REGEXP_INSTR(X,'[[:CNTRL:]]+')
------------------------------
0
0
0
5
0
0
0
4

8 rows selected.

select REGEXP_INSTR(x,'[[:cntrl:]]+') from test3;

REGEXP_INSTR(X,'[[:CNTRL:]]+')
------------------------------
0
0
0
5
0
0
0
4

8 rows selected.

SQL> exec :val := 'karthick'

PL/SQL procedure successfully completed.

SQL> select decode(regexp_instr(:val,'[[:digit:]]'),0,'NO',decode(regexp_instr(:val,'[[:alpha:]]'),0,'NO','YES')) from dual
2 /

DEC
---
NO

SQL> exec :val := 'karthick123'

PL/SQL procedure successfully completed.

SQL> select decode(regexp_instr(:val,'[[:digit:]]'),0,'NO',decode(regexp_instr(:val,'[[:alpha:]]'),0,'NO','YES')) from dual
2 /

DEC
---
YES

SQL> exec :val := '123'

PL/SQL procedure successfully completed.

SQL> select decode(regexp_instr(:val,'[[:digit:]]'),0,'NO',decode(regexp_instr(:val,'[[:alpha:]]'),0,'NO','YES')) from dual
2 /

DEC
---
NO

SQL> exec :val := '1ds2d3'

PL/SQL procedure successfully completed.

SQL> select decode(regexp_instr(:val,'[[:digit:]]'),0,'NO',decode(regexp_instr(:val,'[[:alpha:]]'),0,'NO','YES')) from dual
2 /

DEC
---
YES





SQL> insert into t_product values (1,'10','Option1');
insert into t_product values (2,'20','Option2');
insert into t_product values (3,'30','Option3');
insert into t_product values (4,'40a','Option4');
insert into t_product values (5,'Z50','Option5');
1 row created.

SQL>
1 row created.

SQL>
1 row created.

SQL>
1 row created.

SQL>

1 row created.

SQL> select product_code from t_product
where regexp_like(product_code, '[^[:digit:]]'); 2

PRODUCT_CO
----------
40a
Z50

SQL> select product_code from t_product
2 where regexp_like(product_code, '[[:digit:]]');

PRODUCT_CO
----------
10
20
30
40a
Z50






SQL> SELECT REGEXP_SUBSTR('Do not' || CHR(10)|| 'Brighten the corner!','^.*$',1,2,'m') FROM dual;

REGEXP_SUBSTR('DONOT
--------------------
Brighten the corner!

SQL> SELECT REGEXP_SUBSTR('123789',
'[[:digit:]]*')
FROM dual;

123789 2 3
REGEXP
------
123789

SQL> SQL> SELECT REGEXP_SUBSTR('abc123789def','[[:digit:]]*') FROM dual;
SP2-0734: unknown command beginning "123789SELE..." - rest of line ignored.
SQL> SELECT REGEXP_SUBSTR('abc123789def','[[:digit:]]*') FROM dual;

R
-


SQL> SELECT REGEXP_SUBSTR('abc123789def','[[:digit:]]') FROM dual;

R
-
1

SQL> SELECT REGEXP_SUBSTR('abc123789def','[[:digit:]]*+') FROM dual;

R
-


SQL> SELECT REGEXP_SUBSTR('abc123789def','[[:digit:]]+') FROM dual;

REGEXP
------
123789

SQL> SELECT REGEXP_SUBSTR('abc123789def','[^[:digit:]]+') FROM dual;

REG
---
abc

SQL> SELECT REGEXP_SUBSTR('abc123789def','[^[:digit:]]$+') FROM dual;

R
-
f


Using the {m,n} form, you can specify a range of occurrences you are willing to accept. The following query uses {3,5} to match from three to five digits:
SELECT REGEXP_SUBSTR(
'1234567890','[[:digit:]]{3,5}')
FROM dual;

12345



Using {m,}, you can leave the upper end of a range unbounded:
SELECT REGEXP_SUBSTR(
'1234567890','[[:digit:]]{3,}')
FROM dual;

1234567890



Examples
Following is an example of a simple case, in which the string 'Mackinac', commonly misspelled 'Mackinaw', is located within a larger string:
SELECT REGEXP_INSTR(
'Fort Mackinac was built in 1870',
'Mackina.')
FROM dual;

6
If you're interested in the ending character position, actually one past the ending position, you can specify a value of 1 for return_option, which forces you to also specify values for position and occurrence:
SELECT REGEXP_INSTR(
'Fort Mackinac was built in 1870',
'Mackina.',1,1,1)
FROM dual;

14
The occurrence parameter enables you to locate an occurrence of a pattern other than the first:
SELECT REGEXP_INSTR(
'Fort Mackinac is near Mackinaw City',
'Mackina.',1,2)
FROM dual;

23
The following example uses position to skip the first 14 characters of the search string, beginning the search at character position 15:
SELECT REGEXP_INSTR(
'Fort Mackinac is near Mackinaw City',
'Mackina.',15)
FROM dual;



  • ^ - Beginning of String
  • [A-Z] - A Capital Letter
  • [0-9]{8} - Exactly 8 digit characters
  • $ - End of String

Here is a query validating certain use cases:

WITH test_data (text_value) AS
(
  SELECT 'A12345678' FROM DUAL UNION ALL
  SELECT 'a12345678' FROM DUAL UNION ALL
  SELECT 'A1234567' FROM DUAL UNION ALL
  SELECT 'A123456789' FROM DUAL UNION ALL
  SELECT '$12345678' FROM DUAL
)
SELECT td.text_value, 
       CASE WHEN REGEXP_LIKE(td.text_value, '^[A-Z][0-9]{8}$') THEN 'Y' ELSE 'N' END AS VALID
FROM test_data td



*******************************




Working !!

select  distinct substr(name, 1, instr(name, '/',-1)) PATH 
                       from  (
                       select name  from v$datafile
                       union all
                       select NAME  from v$controlfile
                       union all
                       select MEMBER  name from v$logfile
                       union all
                       select name from v$tempfile
) order by 1;                   

===========================================

not working with REGEXP_INSTR

getting error !!
REGEXP_INSTR  ORA-01428: argument '-1' is out of range


select distinct substr(name, 1, REGEXP_INSTR(name, '/',-1)) PATH
 from (
 select name from v$datafile
 union all
 select NAME from v$controlfile
 union all
 select MEMBER name from v$logfile
union all
 select name from v$tempfile
 ) order by 1;
 select distinct substr(name, 1, REGEXP_INSTR(name, '/',-1)) PATH
                                                       *
ERROR at line 1:
ORA-01428: argument '-1' is out of range




reverse search REGEXP_INSTR

with REGEXP_INSTR for windows and unix 

select distinct substr(name, 1, REGEXP_INSTR(name, '[^/|\]*$')-1 )PATH
from (
select name from v$datafile
union all
select NAME from v$controlfile
union all
select MEMBER name from v$logfile
union all
select name from v$tempfile
union all 
 select FILENAME from V$BLOCK_CHANGE_TRACKING
union all
Select NAME from v$flashback_database_logfile
 ) 
order by 1;
 
 


 
 
 
 with t as ( select 'abcab\cabc' foo from dual)
select regexp_instr(foo, '[^/|\]*$')-1 from t
/


with t as ( select 'abcabcabc' foo from dual)
select regexp_instr(foo, '[^b]*$')-1 from t
/

Oracle DBA

anuj blog Archive