Tuning (SQL Query has radically different Buffer GETS in each instance)

I have been noticing that on Node2 of my 10.2.0.3 RAC cluster CPU has been running 90% for the past couple of days and on Node1 we are at the normal 20-30%. I was comparing AWR for both instances and noticed that the same exact SQL was showing different GETS on each instance.
Both Instances are configured exactly the same. SGA 3GB, 2 dual core 1.5Ghz CPU on Solaris 10.
AWR For Node 1
SQL ordered by Gets
Resources reported for PL/SQL code includes the resources used by all SQL statements called by the code.
Total Buffer Gets: 8,199,224
Captured SQL account for 94.2% of Total
Buffer Gets  Executions  Gets per Exec  %Total CPU Time (s) Elapsed Time (s) SQL Id SQL Module SQL Text
4,834,470 16,465 293.62 58.96 442.34 459.42 cs3w0nz7uanhc    BEGIN HRW_EC_QUERY.CHECK_STUDE...
4,561,082 16,469 276.95 55.63 411.10 430.16 6vbpbvfburc4x    SELECT COUNT(SECURE_PROGRAMS.P... AWR For Node 2
Buffer Gets  Executions  Gets per Exec  %Total CPU Time (s) Elapsed Time (s) SQL Id SQL Module SQL Text
219,779,881 9,306 23,617.01 99.26 11791.62 32202.99 cs3w0nz7uanhc    BEGIN HRW_EC_QUERY.CHECK_STUDE...
219,320,634 9,302 23,577.79 99.05 11760.22 32137.23 6vbpbvfburc4x    SELECT COUNT(SECURE_PROGRAMS.P... Gets on Node 2 are about 45 times what they are on node 1. We are using bind variables in the SQL. The statements are completely identical. Anyone seen this before?
Thanks,
Brian

All parameters are the same between instances. Here is the result of the query.
PLAN_TABLE_OUTPUT                                                                                                                          
SQL_ID 6vbpbvfburc4x                                                                                                                       
SELECT COUNT(SECURE_PROGRAMS.PROG_ID) FROM SECURE_PROGRAMS,HRW_EC_ACTIVE_ITEM, (SELECT ACTIVE_ITEM_ID                                      
FROM TABLE(CAST(:B1 AS HRW_EC_ACTIVE_ITEM_ID_TABLE_T)) ) T WHERE HRW_EC_ACTIVE_ITEM.ACTIVE_ITEM_ID =                                       
T.ACTIVE_ITEM_ID AND HRW_EC_ACTIVE_ITEM.SPROG_ID = SECURE_PROGRAMS.PROG_ID AND                                                             
SECURE_PROGRAMS.STUDENT_RESOURCES_URL = :B2                                                                                                
Plan hash value: 25280318                                                                                                                  
| Id  | Operation                           | Name                      | Rows  | Bytes | Cost (%CPU)| Time     |                          
|   0 | SELECT STATEMENT                    |                           |       |       |   730 (100)|          |                          
|   1 |  SORT AGGREGATE                     |                           |     1 |    57 |            |          |                          
|   2 |   HASH JOIN                         |                           |   116 |  6612 |   730   (1)| 00:00:09 |                          
|   3 |    COLLECTION ITERATOR PICKLER FETCH|                           |       |       |            |          |                          
|   4 |    NESTED LOOPS                     |                           | 48596 |  2610K|   705   (1)| 00:00:09 |                          
|   5 |     INDEX RANGE SCAN                | SECURE_PROGRAMS_IDX_04    |     4 |    76 |     2   (0)| 00:00:01 |                          
|   6 |     INDEX RANGE SCAN                | HRW_EC_ACTIVE_ITEM_IDX_03 | 10984 |   386K|   176   (1)| 00:00:03 |                          
Query Block Name / Object Alias (identified by operation id):                                                                              
   1 - SEL$62A3881B                                                                                                                        
   5 - SEL$62A3881B / SECURE_PROGRAMS@SEL$1                                                                                                
   6 - SEL$62A3881B / HRW_EC_ACTIVE_ITEM@SEL$1                                                                                             
SQL_ID 6vbpbvfburc4x                                                                                                                       
SELECT COUNT(SECURE_PROGRAMS.PROG_ID) FROM SECURE_PROGRAMS,HRW_EC_ACTIVE_ITEM, (SELECT ACTIVE_ITEM_ID                                      
FROM TABLE(CAST(:B1 AS HRW_EC_ACTIVE_ITEM_ID_TABLE_T)) ) T WHERE HRW_EC_ACTIVE_ITEM.ACTIVE_ITEM_ID =                                       
T.ACTIVE_ITEM_ID AND HRW_EC_ACTIVE_ITEM.SPROG_ID = SECURE_PROGRAMS.PROG_ID AND                                                             
SECURE_PROGRAMS.STUDENT_RESOURCES_URL = :B2                                                                                                
Plan hash value: 219484150                                                                                                                 
| Id  | Operation                            | Name                      | Rows  | Bytes | Cost (%CPU)| Time     |                         
|   0 | SELECT STATEMENT                     |                           |       |       |  4845 (100)|          |                         
|   1 |  SORT AGGREGATE                      |                           |     1 |    57 |            |          |                         
|   2 |   HASH JOIN                          |                           |  2066 |   115K|  4845   (2)| 00:00:59 |                         
|   3 |    INDEX RANGE SCAN                  | SECURE_PROGRAMS_IDX_04    |    79 |  1501 |     2   (0)| 00:00:01 |                         
|   4 |    HASH JOIN                         |                           |  3284 |   121K|  4843   (2)| 00:00:59 |                         
|   5 |     COLLECTION ITERATOR PICKLER FETCH|                           |       |       |            |          |                         
|   6 |     INDEX FAST FULL SCAN             | HRW_EC_ACTIVE_ITEM_IDX_03 |  1373K|    47M|  4803   (2)| 00:00:58 |                         
Query Block Name / Object Alias (identified by operation id):                                                                              
   1 - SEL$62A3881B                                                                                                                        
   3 - SEL$62A3881B / SECURE_PROGRAMS@SEL$1                                                                                                
   6 - SEL$62A3881B / HRW_EC_ACTIVE_ITEM@SEL$1                                                                                             
Note                                                                                                                                       
   - SQL profile "SYS_SQLPROF_014414387fd00001" used for this statement                                                                    
SQL_ID 6vbpbvfburc4x                                                                                                                       
SELECT COUNT(SECURE_PROGRAMS.PROG_ID) FROM SECURE_PROGRAMS,HRW_EC_ACTIVE_ITEM, (SELECT ACTIVE_ITEM_ID                                      
FROM TABLE(CAST(:B1 AS HRW_EC_ACTIVE_ITEM_ID_TABLE_T)) ) T WHERE HRW_EC_ACTIVE_ITEM.ACTIVE_ITEM_ID =                                       
T.ACTIVE_ITEM_ID AND HRW_EC_ACTIVE_ITEM.SPROG_ID = SECURE_PROGRAMS.PROG_ID AND                                                             
SECURE_PROGRAMS.STUDENT_RESOURCES_URL = :B2                                                                                                
Plan hash value: 740005210                                                                                                                 
| Id  | Operation                           | Name                      | Rows  | Bytes | Cost (%CPU)| Time     |                          
|   0 | SELECT STATEMENT                    |                           |       |       |  4845 (100)|          |                          
|   1 |  SORT AGGREGATE                     |                           |     1 |    57 |            |          |                          
|   2 |   HASH JOIN                         |                           |     7 |   399 |  4845   (2)| 00:00:59 |                          
|   3 |    COLLECTION ITERATOR PICKLER FETCH|                           |       |       |            |          |                          
|   4 |    HASH JOIN                        |                           |  2992 |   160K|  4821   (2)| 00:00:58 |                          
|   5 |     INDEX RANGE SCAN                | SECURE_PROGRAMS_IDX_04    |    33 |   627 |     2   (0)| 00:00:01 |                          
|   6 |     INDEX FAST FULL SCAN            | HRW_EC_ACTIVE_ITEM_IDX_03 |  1373K|    47M|  4803   (2)| 00:00:58 |                          
Query Block Name / Object Alias (identified by operation id):                                                                              
   1 - SEL$62A3881B                                                                                                                        
   5 - SEL$62A3881B / SECURE_PROGRAMS@SEL$1                                                                                                
   6 - SEL$62A3881B / HRW_EC_ACTIVE_ITEM@SEL$1                                                                                             
Note                                                                                                                                       
   - SQL profile "SYS_SQLPROF_014414387fd00001" used for this statement                                                                    
SQL_ID 6vbpbvfburc4x                                                                                                                       
SELECT COUNT(SECURE_PROGRAMS.PROG_ID) FROM SECURE_PROGRAMS,HRW_EC_ACTIVE_ITEM, (SELECT ACTIVE_ITEM_ID                                      
FROM TABLE(CAST(:B1 AS HRW_EC_ACTIVE_ITEM_ID_TABLE_T)) ) T WHERE HRW_EC_ACTIVE_ITEM.ACTIVE_ITEM_ID =                                       
T.ACTIVE_ITEM_ID AND HRW_EC_ACTIVE_ITEM.SPROG_ID = SECURE_PROGRAMS.PROG_ID AND                                                             
SECURE_PROGRAMS.STUDENT_RESOURCES_URL = :B2                                                                                                
Plan hash value: 1418188916                                                                                                                
| Id  | Operation                           | Name                      | Rows  | Bytes | Cost (%CPU)| Time     |                          
|   0 | SELECT STATEMENT                    |                           |       |       |  2136 (100)|          |                          
|   1 |  SORT AGGREGATE                     |                           |     1 |    57 |            |          |                          
|   2 |   HASH JOIN                         |                           |     3 |   171 |  2136   (1)| 00:00:26 |                          
|   3 |    NESTED LOOPS                     |                           |  1103 | 60665 |  2111   (1)| 00:00:26 |                          
|   4 |     INDEX RANGE SCAN                | SECURE_PROGRAMS_IDX_04    |    12 |   228 |     2   (0)| 00:00:01 |                          
|   5 |     INDEX RANGE SCAN                | HRW_EC_ACTIVE_ITEM_IDX_03 | 10984 |   386K|   176   (1)| 00:00:03 |                          
|   6 |    COLLECTION ITERATOR PICKLER FETCH|                           |       |       |            |          |                          
Query Block Name / Object Alias (identified by operation id):                                                                              
   1 - SEL$62A3881B                                                                                                                        
   4 - SEL$62A3881B / SECURE_PROGRAMS@SEL$1                                                                                                
   5 - SEL$62A3881B / HRW_EC_ACTIVE_ITEM@SEL$1      Thanks,
Brian

Similar Messages

  • Executing the SQL query across 2 different databases of Oracle

    Hello All,
    In Microsoft SQL server we can execute following type of SQL query across 2 different databases:
    select * from TEST1.dbo.GENERIC_TABLE1 union select * from TEST2.dbo.GENERIC_TABLE2;
    Here TEST1 and TEST2 are 2 different databases.
    Can we do the same in Oracle?

    yes you can, but first one has to setup a database link
    Look up CREATE DATABASE LINK and then take things from there!
    P;

  • How to compare same SQL query performance in different DB servers.

    We have Production and Validation Environment of Oracle11g DB on two Solaris OSs.
    H/W and DB,etc configurations of two Oracle DBs are almost same in PROD and VAL.
    But we detected large SQL query performace difference in PROD DB and VAL DB in same SQL query.
    I would like to find and solve the cause of this situation.
    How could I do that ?
    I plan to compare SQL execution plan in PROD and VAL DB and index fragmentations.
    Before that I thought I need to keep same condition of DB statistics information in PROD and VAL DB.
    So, I plan to execute alter system FLUSH BUFFER_CACHE;
    But I am worring about bad effects of alter system FLUSH BUFFER_CACHE; to end users
    If we did alter system FLUSH BUFFER_CACHE; and got execution plan of that SQL query in the time end users do not use that system ,
    there is not large bad effect to end users after those operations?
    Could you please let me know the recomendation to compare SQL query performace ?

    Thank you.
    I got AWR report for only VAL DB server but it looks strange.
    Is there any thing wrong in DB or how to get AWR report ?
    Host Name
    Platform
    CPUs
    Cores
    Sockets
    Memory (GB)
    xxxx
    Solaris[tm] OE (64-bit)
    .00
    Snap Id
    Snap Time
    Sessions
    Cursors/Session
    Begin Snap:
    xxxx
    13-Apr-15 04:00:04
    End Snap:
    xxxx
    14-Apr-15 04:00:22
    Elapsed:
    1,440.30 (mins)
    DB Time:
    0.00 (mins)
    Report Summary
    Cache Sizes
    Begin
    End
    Buffer Cache:
    M
    M
    Std Block Size:
    K
    Shared Pool Size:
    0M
    0M
    Log Buffer:
    K
    Load Profile
    Per Second
    Per Transaction
    Per Exec
    Per Call
    DB Time(s):
    0.0
    0.0
    0.00
    0.00
    DB CPU(s):
    0.0
    0.0
    0.00
    0.00
    Redo size:
    Logical reads:
    0.0
    1.0
    Block changes:
    0.0
    1.0
    Physical reads:
    0.0
    1.0
    Physical writes:
    0.0
    1.0
    User calls:
    0.0
    1.0
    Parses:
    0.0
    1.0
    Hard parses:
    W/A MB processed:
    16.7
    1,442,472.0
    Logons:
    Executes:
    0.0
    1.0
    Rollbacks:
    Transactions:
    0.0
    Instance Efficiency Percentages (Target 100%)
    Buffer Nowait %:
    Redo NoWait %:
    Buffer Hit %:
    In-memory Sort %:
    Library Hit %:
    96.69
    Soft Parse %:
    Execute to Parse %:
    0.00
    Latch Hit %:
    Parse CPU to Parse Elapsd %:
    % Non-Parse CPU:
    Shared Pool Statistics
    Begin
    End
    Memory Usage %:
    % SQL with executions>1:
    34.82
    48.31
    % Memory for SQL w/exec>1:
    63.66
    73.05
    Top 5 Timed Foreground Events
    Event
    Waits
    Time(s)
    Avg wait (ms)
    % DB time
    Wait Class
    DB CPU
    0
    100.00
    Host CPU (CPUs: Cores: Sockets: )
    Load Average Begin
    Load Average End
    %User
    %System
    %WIO
    %Idle
    Instance CPU
    %Total CPU
    %Busy CPU
    %DB time waiting for CPU (Resource Manager)
    Memory Statistics
    Begin
    End
    Host Mem (MB):
    SGA use (MB):
    46,336.0
    46,336.0
    PGA use (MB):
    713.6
    662.6
    % Host Mem used for SGA+PGA:
    Time Model Statistics
    No data exists for this section of the report.
    Back to Wait Events Statistics
    Back to Top
    Operating System Statistics
    No data exists for this section of the report.
    Back to Wait Events Statistics
    Back to Top
    Operating System Statistics - Detail
    No data exists for this section of the report.
    Back to Wait Events Statistics
    Back to Top
    Foreground Wait Class
    s - second, ms - millisecond - 1000th of a second
    ordered by wait time desc, waits desc
    %Timeouts: value of 0 indicates value was < .5%. Value of null is truly 0
    Captured Time accounts for % of Total DB time .00 (s)
    Total FG Wait Time: (s) DB CPU time: .00 (s)
    Wait Class
    Waits
    %Time -outs
    Total Wait Time (s)
    Avg wait (ms)
    %DB time
    DB CPU
    0
    100.00
    Back to Wait Events Statistics
    Back to Top
    Foreground Wait Events
    No data exists for this section of the report.
    Back to Wait Events Statistics
    Back to Top
    Background Wait Events
    ordered by wait time desc, waits desc (idle events last)
    Only events with Total Wait Time (s) >= .001 are shown
    %Timeouts: value of 0 indicates value was < .5%. Value of null is truly 0
    Event
    Waits
    %Time -outs
    Total Wait Time (s)
    Avg wait (ms)
    Waits /txn
    % bg time
    log file parallel write
    527,034
    0
    2,209
    4
    527,034.00
    db file parallel write
    381,966
    0
    249
    1
    381,966.00
    os thread startup
    2,650
    0
    151
    57
    2,650.00
    latch: messages
    125,526
    0
    89
    1
    125,526.00
    control file sequential read
    148,662
    0
    54
    0
    148,662.00
    control file parallel write
    41,935
    0
    28
    1
    41,935.00
    Log archive I/O
    5,070
    0
    14
    3
    5,070.00
    Disk file operations I/O
    8,091
    0
    10
    1
    8,091.00
    log file sequential read
    3,024
    0
    6
    2
    3,024.00
    db file sequential read
    1,299
    0
    2
    2
    1,299.00
    latch: shared pool
    722
    0
    1
    1
    722.00
    enq: CF - contention
    4
    0
    1
    208
    4.00
    reliable message
    1,316
    0
    1
    1
    1,316.00
    log file sync
    71
    0
    1
    9
    71.00
    enq: CR - block range reuse ckpt
    36
    0
    0
    13
    36.00
    enq: JS - queue lock
    459
    0
    0
    1
    459.00
    log file single write
    414
    0
    0
    1
    414.00
    enq: PR - contention
    5
    0
    0
    57
    5.00
    asynch descriptor resize
    67,076
    100
    0
    0
    67,076.00
    LGWR wait for redo copy
    5,184
    0
    0
    0
    5,184.00
    rdbms ipc reply
    1,234
    0
    0
    0
    1,234.00
    ADR block file read
    384
    0
    0
    0
    384.00
    SQL*Net message to client
    189,490
    0
    0
    0
    189,490.00
    latch free
    559
    0
    0
    0
    559.00
    db file scattered read
    17
    0
    0
    6
    17.00
    resmgr:internal state change
    1
    100
    0
    100
    1.00
    direct path read
    301
    0
    0
    0
    301.00
    enq: RO - fast object reuse
    35
    0
    0
    2
    35.00
    direct path write
    122
    0
    0
    1
    122.00
    latch: cache buffers chains
    260
    0
    0
    0
    260.00
    db file parallel read
    1
    0
    0
    41
    1.00
    ADR file lock
    144
    0
    0
    0
    144.00
    latch: redo writing
    55
    0
    0
    1
    55.00
    ADR block file write
    120
    0
    0
    0
    120.00
    wait list latch free
    2
    0
    0
    10
    2.00
    latch: cache buffers lru chain
    44
    0
    0
    0
    44.00
    buffer busy waits
    3
    0
    0
    2
    3.00
    latch: call allocation
    57
    0
    0
    0
    57.00
    SQL*Net more data to client
    55
    0
    0
    0
    55.00
    ARCH wait for archivelog lock
    78
    0
    0
    0
    78.00
    rdbms ipc message
    3,157,653
    40
    4,058,370
    1285
    3,157,653.00
    Streams AQ: qmn slave idle wait
    11,826
    0
    172,828
    14614
    11,826.00
    DIAG idle wait
    170,978
    100
    172,681
    1010
    170,978.00
    dispatcher timer
    1,440
    100
    86,417
    60012
    1,440.00
    Streams AQ: qmn coordinator idle wait
    6,479
    48
    86,413
    13337
    6,479.00
    shared server idle wait
    2,879
    100
    86,401
    30011
    2,879.00
    Space Manager: slave idle wait
    17,258
    100
    86,324
    5002
    17,258.00
    pmon timer
    46,489
    62
    86,252
    1855
    46,489.00
    smon timer
    361
    66
    86,145
    238628
    361.00
    VKRM Idle
    1
    0
    14,401
    14400820
    1.00
    SQL*Net message from client
    253,909
    0
    419
    2
    253,909.00
    class slave wait
    379
    0
    0
    0
    379.00
    Back to Wait Events Statistics
    Back to Top
    Wait Event Histogram
    No data exists for this section of the report.
    Back to Wait Events Statistics
    Back to Top
    Wait Event Histogram Detail (64 msec to 2 sec)
    No data exists for this section of the report.
    Back to Wait Events Statistics
    Back to Top
    Wait Event Histogram Detail (4 sec to 2 min)
    No data exists for this section of the report.
    Back to Wait Events Statistics
    Back to Top
    Wait Event Histogram Detail (4 min to 1 hr)
    No data exists for this section of the report.
    Back to Wait Events Statistics
    Back to Top
    Service Statistics
    No data exists for this section of the report.
    Back to Wait Events Statistics
    Back to Top
    Service Wait Class Stats
    No data exists for this section of the report.
    Back to Wait Events Statistics
    Back to Top
    SQL Statistics
    SQL ordered by Elapsed Time
    SQL ordered by CPU Time
    SQL ordered by User I/O Wait Time
    SQL ordered by Gets
    SQL ordered by Reads
    SQL ordered by Physical Reads (UnOptimized)
    SQL ordered by Executions
    SQL ordered by Parse Calls
    SQL ordered by Sharable Memory
    SQL ordered by Version Count
    Complete List of SQL Text
    Back to Top
    SQL ordered by Elapsed Time
    No data exists for this section of the report.
    Back to SQL Statistics
    Back to Top
    SQL ordered by CPU Time
    No data exists for this section of the report.
    Back to SQL Statistics
    Back to Top
    SQL ordered by User I/O Wait Time
    No data exists for this section of the report.
    Back to SQL Statistics
    Back to Top
    SQL ordered by Gets
    No data exists for this section of the report.
    Back to SQL Statistics
    Back to Top
    SQL ordered by Reads
    No data exists for this section of the report.
    Back to SQL Statistics
    Back to Top
    SQL ordered by Physical Reads (UnOptimized)
    No data exists for this section of the report.
    Back to SQL Statistics
    Back to Top
    SQL ordered by Executions
    No data exists for this section of the report.
    Back to SQL Statistics
    Back to Top
    SQL ordered by Parse Calls
    No data exists for this section of the report.
    Back to SQL Statistics
    Back to Top
    SQL ordered by Sharable Memory
    No data exists for this section of the report.
    Back to SQL Statistics
    Back to Top
    SQL ordered by Version Count
    No data exists for this section of the report.
    Back to SQL Statistics
    Back to Top
    Complete List of SQL Text
    No data exists for this section of the report.
    Back to SQL Statistics
    Back to Top
    Instance Activity Statistics
    Instance Activity Stats
    Instance Activity Stats - Absolute Values
    Instance Activity Stats - Thread Activity
    Back to Top
    Instance Activity Stats
    No data exists for this section of the report.
    Back to Instance Activity Statistics
    Back to Top
    Instance Activity Stats - Absolute Values
    No data exists for this section of the report.
    Back to Instance Activity Statistics
    Back to Top
    Instance Activity Stats - Thread Activity
    Statistics identified by '(derived)' come from sources other than SYSSTAT
    Statistic
    Total
    per Hour
    log switches (derived)
    69
    2.87
    Back to Instance Activity Statistics
    Back to Top
    IO Stats
    IOStat by Function summary
    IOStat by Filetype summary
    IOStat by Function/Filetype summary
    Tablespace IO Stats
    File IO Stats
    Back to Top
    IOStat by Function summary
    'Data' columns suffixed with M,G,T,P are in multiples of 1024 other columns suffixed with K,M,G,T,P are in multiples of 1000
    ordered by (Data Read + Write) desc
    Function Name
    Reads: Data
    Reqs per sec
    Data per sec
    Writes: Data
    Reqs per sec
    Data per sec
    Waits: Count
    Avg Tm(ms)
    Others
    28.8G
    20.55
    .340727
    16.7G
    2.65
    .198442
    1803K
    0.01
    Direct Reads
    43.6G
    57.09
    .517021
    411M
    0.59
    .004755
    0
    LGWR
    19M
    0.02
    .000219
    41.9G
    21.87
    .496493
    2760
    0.08
    Direct Writes
    16M
    0.00
    .000185
    8.9G
    1.77
    .105927
    0
    DBWR
    0M
    0.00
    0M
    6.7G
    4.42
    .079670
    0
    Buffer Cache Reads
    3.1G
    3.67
    .037318
    0M
    0.00
    0M
    260.1K
    3.96
    TOTAL:
    75.6G
    81.33
    .895473
    74.7G
    31.31
    .885290
    2065.8K
    0.51
    Back to IO Stats
    Back to Top
    IOStat by Filetype summary
    'Data' columns suffixed with M,G,T,P are in multiples of 1024 other columns suffixed with K,M,G,T,P are in multiples of 1000
    Small Read and Large Read are average service times, in milliseconds
    Ordered by (Data Read + Write) desc
    Filetype Name
    Reads: Data
    Reqs per sec
    Data per sec
    Writes: Data
    Reqs per sec
    Data per sec
    Small Read
    Large Read
    Data File
    53.2G
    78.33
    .630701
    8.9G
    7.04
    .105197
    0.37
    21.51
    Log File
    13.9G
    0.18
    .164213
    41.9G
    21.85
    .496123
    0.02
    2.93
    Archive Log
    0M
    0.00
    0M
    13.9G
    0.16
    .164213
    Temp File
    5.6G
    0.67
    .066213
    8.1G
    0.80
    .096496
    5.33
    3713.27
    Control File
    2.9G
    2.16
    .034333
    2G
    1.46
    .023247
    0.05
    19.98

  • SQL query has strange behavior on sql server 2014

    Hi All,
    I have a very weird situation where a front end entity framework query (cannot be modified easily) made up of SQL views that are used in subquery format. It generally runs within few seconds but there are times in the day when query just keep on going and
    sometimes start spitting results very slowly and at other times no result but keep on executing. Sysprocesses table shows sos_scheduler_yield wait type when query is running and not returning results. This behavior started on the query since the database was
    upgraded (migrated) from sql 2005 clustered enterprise instance to a new 2014 Enterprise clustered instance on a very powerful server.  This query is used by a batch process and what I have found that if we rebuild indexes on the database (takes
    only 2 mins) , the query appears to be returning results as expected. No other solution is working at the moment. The query had no issue on older sql 2005 instance and I have tested it their a few times. I am assuming it is a SQL 2014 related issue and found
    a fix on CU 5 for sos_scheduler_yield but it has not fixed the issue. At this point SQL 2014 is on latest CU 6 as of last week and index rebuilt wis the only viable work around to get the query going without interruption.
    Has anyone faced this issue on SQl 2014 or have some suggestions I can try. I can reproduce this error on at least two instances on SQL 2014. I have even tried setting max dop at server level to 1 and at half the total processors cores but to no avail. There
    is a 750GB memory on the box.
    Thanks
    dba60
    dba60

    First of all, SOS_SCHEDULER_YIELD has nothing to do with the query as such. SQL Server has a co-operative operating system, which means that processes voluntary yields to permit other threads to executes. This sends them to the wait state SOS_SCHEDULER_YIELD.
    If there is no other process executing, they are directly back in the game.
    The problems with your query is most likely to be an issue with the query plan. It is not uncommon to see plan changes when you move from one version of SQL Server to another because of changes in the optimizer.
    As Satish says, SQL 2014 has a new cardinality estimator (CE), which certainly can change the game. Check the compatibility level of the database. If the compat level is 120, you are using the new CE, else you are using the old one.
    If the level is 120, the first check is to change it to 110 to see if this has any effect. 
    But in the end you will have to work more with the query. Analyse it to see if it can be improved by adding indexes. You say said that this query generated by Entity Framework. Unfortunately, this is an indiciation of that the query is not the best and could
    serve from a rewrite.
    The ultimate rescue would be to freeze the plan when it runs well. I have some text about this here:
    http://www.sommarskog.se/query-plan-mysteries.html#planguides
    Erland Sommarskog, SQL Server MVP, [email protected]

  • How to replace a dates on a SQL query on Visual Studio (and get the query to work in there in the first place)?

    Morning all,
    I've just been assigned a report-related project but I have not created much of anything in C# or .Net before!
    I was wondering if someone could help me get started. Here are the specifications:
    Basically, I am to create an automated report application. I have the query and I will include it further down
    in this post. The page is to have a couple blanks to specify the Start Date and End Date and replace those dates in the query, and generate the report. What I need some help on is how to make the SQL query work in the application which I will connect to the
    intended database to generate the report (basic I know, but I'm new at this) on Visual Studio 2010. I also need some help on programming the Start Date blank and End Date blank so that what the user types in for those blanks will replace the date fields in
    the SQL query, then generate the report with the new dates. 
    I appreciate the help!
    The SQL query and what the dates are replacing:
    select 
    PTH.INST_ID ,
    PTH.EMPLOYEE_ID,
    DBH.HR_DEDUCTION_AND_BENEFITS_CODE,
    replace(DB.DESCRIPTION,',',''),
    DB.WITHHOLDING_LIABILITY_ACCOUNT_MASK,
    DBH.HR_DEDUCTION_AND_BENEFITS_ID,
    DBH.CHECK_DATE,
    DBH.CHECK_NO,
    DBH.FIN_INST_ACCT_ID,
    replace(replace (DBH.COMMENT,CHAR(10),' '),CHAR(13),' '),
    DBH.HR_DEDUCTION_AND_BENEFIT_CYCLE_CODE,
    DBH.LENGTH,
    DBH.EMPLOYEE_COMPUTED_AMOUNT,
    DBH.EMPLOYEE_BANK_ROUTING_NUMBER,
    DBH.EMPLOYEE_ACCOUNT_TYPE,
    DBH.EMPLOYEE_ACCOUNT_NUMBER,
    DBH.EMPLOYER_COMPUTED_AMOUNT,
    DBH.EMPLOYEE_GROSS_AMOUNT,
    DBH.EMPLOYER_GROSS_AMOUNT,
    DBH.PAYROLL_EXCLUDE,
    PTH.VOID_DATE,
    PTH.BATCH_QUEUE_ID,
    B.BATCH_CODE,
    BQ.FY,
    BQ.END_DATE,
    BQ.COMMENTS,
    BQ.BATCH_CRITERIA_USED,
    BP.COLUMN_VALUE,
    PTH.REPLACEMENT,
    P.LAST_NAME,
    P.FIRST_NAME,
    P.MIDDLE_NAME
    from PY_EMPLOYEE_TAX_HISTORY PTH
    INNER JOIN PERSON_EMPLOYEE PE ON
    PE.INST_ID=PTH.INST_ID AND
    PE.EMPLOYEE_ID=PTH.EMPLOYEE_ID
    INNER JOIN PERSON P ON
    PE.INST_ID=P.INST_ID AND
    PE.PERSON_ID=P.PERSON_ID
    LEFT JOIN HR_EMPLOYEE_DEDUCTIONS_AND_BENEFITS_HISTORY DBH ON
    PTH.INST_ID=DBH.INST_ID AND
    PTH.CHECK_DATE=DBH.CHECK_DATE AND
    PTH.CHECK_NO=DBH.CHECK_NO AND
    PTH.EMPLOYEE_ID=DBH.EMPLOYEE_ID
    LEFT JOIN HR_DEDUCTION_AND_BENEFITS DB ON
    DB.INST_ID=DBH.INST_ID AND
    DB.HR_DEDUCTION_AND_BENEFITS_CODE=DBH.HR_DEDUCTION_AND_BENEFITS_CODE
    LEFT JOIN BATCH_QUEUE BQ ON
    PTH.BATCH_QUEUE_ID=BQ.BATCH_QUEUE_ID
    LEFT JOIN BATCH B ON
    B.BATCH_CODE=BQ.BATCH_CODE 
    LEFT JOIN BATCH_PARAMETER BP ON
    BQ.BATCH_QUEUE_ID=BP.BATCH_QUEUE_ID
    AND BP.COLUMN_NAME = 'SUPPRESS_DIRECT_DEPOSIT'
    ------Please change the WHERE condition for date range of the month you need to run this for.
    WHERE PTH.CHECK_DATE >='07/01/2013'
    AND PTH.CHECK_DATE <='07/31/2013'
    and BQ.BATCH_CODE='BAT_PY_PAYCALC'
    and bq.fy=2014
    ORDER BY PTH.INST_ID ,
    PTH.EMPLOYEE_ID,
    DBH.HR_DEDUCTION_AND_BENEFITS_CODE,
    DBH.CHECK_DATE

    Try this code.  The Server name will be the same name when you use SQL Server Management Studio (SSMS).  It is in the login window for SSMS.  I assume you are using SQLSTANDARD (not SQLEXPRESS) which is in the connection string in the code
    below. I also assume you have remote connection allowed in the database.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data;
    using System.Data.SqlClient;
    namespace ConsoleApplication1
    class Program
    const string DATABASE = "Enter Database Name Here";
    const string SERVER = "Enter Server Name Here";
    static void Main(string[] args)
    DateTime startDate = DateTime.Parse("07/01/2013");
    string startDateStr = startDate.ToString("MM/dd/yyyy");
    DateTime endDate = new DateTime(startDate.Year, startDate.Month + 1, 1).AddDays(-1);
    string endDateStr = endDate.ToString("MM/dd/yyyy");
    string connStr = string.Format("Server={0}\\SQLSTANDARD;Database={1};Trusted_Connection= True;", SERVER,DATABASE);
    string SQL = string.Format(
    "select\n" +
    " PTH.INST_ID\n" +
    ",PTH.EMPLOYEE_ID\n" +
    ",DBH.HR_DEDUCTION_AND_BENEFITS_CODE,\n" +
    ",replace(DB.DESCRIPTION,',','')\n" +
    ",DB.WITHHOLDING_LIABILITY_ACCOUNT_MASK\n" +
    ",DBH.HR_DEDUCTION_AND_BENEFITS_ID\n" +
    ",DBH.CHECK_DATE\n" +
    ",DBH.CHECK_NO\n" +
    ",DBH.FIN_INST_ACCT_ID\n" +
    ",replace(replace (DBH.COMMENT,CHAR(10),' '),CHAR(13),' ')\n" +
    ",DBH.HR_DEDUCTION_AND_BENEFIT_CYCLE_CODE\n" +
    ",DBH.LENGTH\n" +
    ",DBH.EMPLOYEE_COMPUTED_AMOUNT\n" +
    ",DBH.EMPLOYEE_BANK_ROUTING_NUMBER\n" +
    ",DBH.EMPLOYEE_ACCOUNT_TYPE\n" +
    ",DBH.EMPLOYEE_ACCOUNT_NUMBER\n" +
    ",DBH.EMPLOYER_COMPUTED_AMOUNT\n" +
    ",DBH.EMPLOYEE_GROSS_AMOUNT\n" +
    ",DBH.EMPLOYER_GROSS_AMOUNT\n" +
    ",DBH.PAYROLL_EXCLUDE\n" +
    ",PTH.VOID_DATE\n" +
    ",PTH.BATCH_QUEUE_ID\n" +
    ",B.BATCH_CODE\n" +
    ",BQ.FY\n" +
    ",BQ.END_DATE\n" +
    ",BQ.COMMENTS\n" +
    ",BQ.BATCH_CRITERIA_USED\n" +
    ",BP.COLUMN_VALUE\n" +
    ",PTH.REPLACEMENT\n" +
    ",P.LAST_NAME\n" +
    ",P.FIRST_NAME\n" +
    ",P.MIDDLE_NAME\n" +
    " from PY_EMPLOYEE_TAX_HISTORY PTH\n" +
    " INNER JOIN PERSON_EMPLOYEE PE ON\n" +
    " PE.INST_ID=PTH.INST_ID AND\n" +
    " PE.EMPLOYEE_ID=PTH.EMPLOYEE_ID\n" +
    " INNER JOIN PERSON P ON\n" +
    " PE.INST_ID=P.INST_ID AND\n" +
    " PE.PERSON_ID=P.PERSON_ID\n" +
    " LEFT JOIN HR_EMPLOYEE_DEDUCTIONS_AND_BENEFITS_HISTORY DBH ON\n" +
    " PTH.INST_ID=DBH.INST_ID AND\n" +
    " PTH.CHECK_DATE=DBH.CHECK_DATE AND\n" +
    " PTH.CHECK_NO=DBH.CHECK_NO AND\n" +
    " PTH.EMPLOYEE_ID=DBH.EMPLOYEE_ID\n" +
    " LEFT JOIN HR_DEDUCTION_AND_BENEFITS DB ON\n" +
    " DB.INST_ID=DBH.INST_ID AND\n" +
    " DB.HR_DEDUCTION_AND_BENEFITS_CODE=DBH.HR_DEDUCTION_AND_BENEFITS_CODE\n" +
    " LEFT JOIN BATCH_QUEUE BQ ON\n" +
    " PTH.BATCH_QUEUE_ID=BQ.BATCH_QUEUE_ID\n" +
    " LEFT JOIN BATCH B ON\n" +
    " B.BATCH_CODE=BQ.BATCH_CODE\n" +
    " LEFT JOIN BATCH_PARAMETER BP ON\n" +
    " BQ.BATCH_QUEUE_ID=BP.BATCH_QUEUE_ID\n" +
    " AND BP.COLUMN_NAME = 'SUPPRESS_DIRECT_DEPOSIT'\n" +
    " WHERE PTH.CHECK_DATE >='{0}'\n" +
    " AND PTH.CHECK_DATE <='{1}'\n" +
    " and BQ.BATCH_CODE='BAT_PY_PAYCALC'\n" +
    " and bq.fy=2014\n" +
    " ORDER BY PTH.INST_ID\n" +
    ",PTH.EMPLOYEE_ID\n" +
    ",DBH.HR_DEDUCTION_AND_BENEFITS_CODE\n" +
    ",DBH.CHECK_DATE", startDateStr, endDateStr);
    SqlDataAdapter adapter = new SqlDataAdapter(SQL, connStr);
    DataTable dt = new DataTable();
    adapter.Fill(dt);
    jdweng
    Could you elaborate more on what this code does in general?
    Does it generate a table with the data between specified dates? If so, where is the table shown? 
    Where does one enter in the specified start and end dates on the Web Application? Do I have to create start and end date blanks and link them to the code for it to work?
    Sorry for the inconvenience - I'm just really new at this. Thanks!

  • Tuning SQL query

    Please help me in tuning this query. This view has around 2 million of records
    SELECT * FROM employee_v
    WHERE status_id IN (SELECT MAX(v2.status_id)status_id
    FROM employee_v v2
    WHERE UPPER(v2.name) LIKE UPPER(:v_name)||'%'
    GROUP BY v2.emp_id, v2.project_id)
    ORDER BY status_type_id;
    Here:
    employees may work on one or more projects
    employee working on a given project may have one or more status_ids associated.
    for example:
    emp_id     project_id     status_id
    10     100     1
    10     100     2
    20     100     2
    20     200     3
    30     100     4
    30     200     5
    30     200     6
    40     200     6
    If you have any other suggestions , please let me know too. For example, I was thinking that the subquery should use actual tables instead of the view because view is based on 10 tables and the subquery can instead use two tables . Does it make sense?
    Thanks a lot for the help!
    Edited by: user5406804 on Apr 20, 2010 5:42 AM

    If you have any other suggestions , please let me know too. Wild shot in the dark, but maybe using EXISTS instead of IN speeds up your query:
    untested for obvious reasons
    select *
    from  employee_v v
    where  upper(v.name) like upper(:v_name)||'%'
    where not exists ( select null
                       from   employee_v v2
                       and    v2.status_id > v.status_id                  
                       and    v2.emp_id = v.emp_id -- assuming you have some emp_id PK column
                                                   -- if necessary, you need to change the name of this column ofcourse
    order by status_type_id;Do compare the resultsets, not sure this will give you the same/desired result, but it might give you an idea.
    For example, I was thinking that the subquery should use actual tables instead of the view because > view is based on 10 tables and the subquery can instead
    use two tables . Does it make sense?Sounds like worth a try to me, yes. Less data to plough through = faster response.
    As well as using a function based index on UPPER(name) might be worth a try.

  • Tricky SQL query... how to get all data in a single query?

    create table employee_definition (def_id number, def_name varchar(50));
    insert into employee_definition values (100, 'EMAIL');
    insert into employee_definition values (200, 'MOBILE_PHONE');
    insert into employee_definition values (300, 'HOME_PHONE');
    SQL> select * from employee_definition;
        DEF_ID DEF_NAME
           100 EMAIL
           200 MOBILE_PHONE
           300 HOME_PHONE
    create table employee_data (def_id number, def_value varchar(20), emp_id number);
    insert into employee_data values (100, '[email protected]', 123);
    insert into employee_data values (200, '01232222', 123);
    insert into employee_data values (300, '5555', 123);
    insert into employee_data values (100, '[email protected]', 666);
    insert into employee_data values (200, '888', 666);
    insert into employee_data values (300, '999', 666);
    insert into employee_data values (300, '444', 777);
    SQL> select * from employee_data;
        DEF_ID DEF_VALUE                EMP_ID
           100 [email protected]              123
           200 01232222                    123
           300 5555                        123
           100 [email protected]              666
           200 888                         666
           300 999                         666
           300 999                         777
    7 rows selected.I'm supposed to create a SQL that will return me the email, mobile_phone, and home_phone for a set of employees. The result will be something like this:
    EMPLOYEE ID | HOME_PHONE | MOBILE_PHONE | EMAIL
    123         |  5555  |    01232222      | [email protected]
    666         |  999  |    888      | [email protected]
    777         |  444  |    null     | nullThe thing I'm finding difficulty here is that the same column is used to store different values, based on the value in employee_definition table (something like a key/value pair). If I do:
    SQL> select emp_id, def_value as email from employee_data, employee_definition
      2  where employee_data.def_id = employee_definition.def_id
      3  and employee_definition.def_name = 'EMAIL';
        EMP_ID EMAIL
           123 [email protected]
           666 [email protected]'s partially ok.. I'm just getting the definition for 'EMAIL'. But how can I get all the values in a single query, knowing that the column stores different values based on def_name?

    Oh no, not again.
    Entity attribute models always seem like a great idea to people who have been in the profession for five minutes and lack any kind of fundamental knowledge.
    It staggers me that someone with 2,345 posts still believes "you need a 'detail table' for [storing multiple telephone numbers]"
    "A person can have multiple telephone numbers" is not an excuse to build a tired person_attribute table. Niether is the bizarre proposal by someone with over 4k posts who should know better in an earlier post that EAV models are necessary to support temporal fidelity.
    Taken to it's logical conclusion, EAV modelling leads to just two application tables. THINGS and THING_ATTRIBUTES. And when you consider that a THING_ATTRIBUTE is also a THING, why not roll those two tables up into one also? Hmmm, what does THINGS and THING_ATTRIBUTES look like? I know, TABLES and COLUMNS. Who would've guessed? SQL already provides the completely flexible extensible attribute model the advocates of EAV proscribe. But it also has data types, physical data independence, constraints and an efficient query language which EAV does not.
    EAV modelling errodes the semantics of the attributes which are bundled into the "attribute" table.
    There is no point in storing 12 different phone numbers with implied functional dependency to unconstrained and often repeating notional attributes like "MOBILE", "LANDLINE", "WORK", err, "WORK2", err, "MOBILE2", err, ... when this phone type attribute has no semantic value. When you want to call someone, you invariably want to retrive the prefered_phone_number which may depend on a time of day, or a call context.
    These things need to be modelled properly (i.e normalised to BCNF) within the context of the database.

  • Tuning SQL Query calling multiple views

    Dear All,
    I have a complex scenario in which I have created views in 3 levels for sales and Service separately so total no of views are 6.
    Level 2 calls view in Level 1 and Level 3 calls level 2 in sales as well as services.
    Finally Level 4 has the union of sales and Service Level 3 view.
    There are 5 tables used in total and all have been indexed for better performance.
    The cube processing for the above scenario has processing time of 6 mins.
    The goal is to bring it down to 2-3 mins.
    The amount of data currently we are looking at is not more than 2-3 GB.
    Can anybody help me fine tune this scenario?
    Thanks, Franco.

    Run the queries the cube is using in SSMS and turn on the Include Actual Execution Plan option. 
    https://msdn.microsoft.com/en-us/library/ms189562.aspx?f=255&MSPPError=-2147217396
    Straight up it may suggest missing indexes which you can test to see if they improve the query performance.  You can't take these suggestions as gospel - sometimes SQL Server gets it wrong - so you need to test them. 
    After that look in the query plan for any table scan operators.  Unless you are actually retrieving every row in a table you shouldn't have any of these and they can probably be removed by placing a properly considered index on the table. 
    After that look for any RID Lookups or Key Lookups.  These can generally be resolved fairly easily by adding the columns being looked up as "include" columns in the indexes.  
    Here are some links that might get you started.  
    Reading Execution Plans: http://www.mssqltips.com/sqlservertip/1873/how-to-read-sql-server-graphical-query-execution-plans/
    Resolving Table Scans http://blog.sqlauthority.com/2007/03/30/sql-server-index-seek-vs-index-scan-table-scan/
    Resolving Lookups: http://blog.sqlauthority.com/2009/11/09/sql-server-removing-key-lookup-seek-predicate-predicate-an-interesting-observation-related-to-datatypes/
    Those are the obvious things - and generally the easiest to achieve.  Performance tuning is a big area.  It may be that the database queries are already performing perfectly well and the time being spent is processing the cube itself so you need
    to establish where the time is going.  There is no point trying to tune the database queries if they are already working well.
    LucasF

  • Run sql query on a different thread

    Hello,
    I have a swing app that queries an MS SQL database and it works fine and everything happens in the same thread. However for improved performance and to avoid freeze ups, I want the SQL queries themselves to execute on a different thread as a different class, other than the swing app class. The query results (Result Set) I want them back to my swing app so I can present them on a JTable.
    Here is an example of what I am trying to accomplish:
    - Press button in my swing app.
    - Call class that implements Runnable
    - In the Run method of the new class do the following (this code will execute in a new thread):
    url = "jdbc:sqlserver://ServerName:1433;databaseName=Database;user=UserName;password=password";
    try{
         Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
         Connection con = DriverManager.getConnection(url);
         Statement stmt;
         ResultSet rs;
         stmt = con.createStatement();
         String queryString = "select * from databaseName";
         rs = stmt.executeQuery(queryString);
          con.close();
    catch(Exception em){
          em.printStackTrace();
         JOptionPane.showMessageDialog(null,em.toString());
    }- Get the ResultSet rs back from the class
    - Work with the results back in my swing app and present them in the JTable
    while(rs.next()){
                //do some stuff
         }Any help or hints are greatly appreciated.
    Thanks,
    Chris

    Two suggestions:
    -- Take a look at SwingWorker for taking care of the threading issues
    -- Keep all database handling code together. Collect the records into a Collection -- most likely ArrayList -- and return that. This way you can close the Connection and RecordSet within the same method that opens them.
    Just my 0.02.
    db

  • Question on Tuning SQL query

    We are converting from a 9i database to an 11g database.  The query defined works perfectly under 9i (about 1 second) but is taking 60-70 seconds to return in 11g.  The wierd thing is that it has an outer query and a subquery.  If I remove the where clause from the outer query it executes in less than a second.  Here is the query...
    SELECT period, biweek_start, biweek_end, pay_period_complete, worker_count
      FROM (SELECT to_char(en.start_date, 'yyyy/mm/dd') || ' to ' ||
                   to_char(en.start_date + 13, 'yyyy/mm/dd') period,
                   en.start_date biweek_start,
                   en.start_date + 13 biweek_end,
                   decode(sign(sysdate - en.start_date - 13),
                          -1,
                          'In Progress',
                          'Completed') pay_period_complete,
                   ta_mssauth_pkg.actual_endorser(en.start_date, '33811')  worker_count
              FROM (select worker_id,
                           default_endorser resolved_endorser,
                           effective_date,
                           expiration_date
                      from endorse_delegate_history_v
                     where default_endorser = '33811'
                    union
                    select worker_id,
                           temporary_delegate resolved_endorser,
                           effective_date,
                           expiration_date
                      from endorse_delegate_history_v
                     where temporary_delegate = '33811'
                       and temporary_delegate is not null ) de,
                   endorse_activity_v en
             WHERE en.worker_id = de.worker_id
               AND en.endorse_status = 'N'
               AND en.start_date <= de.expiration_date
               AND en.start_date + 13 >= de.effective_date
             GROUP BY en.start_date)
    WHERE worker_count > 0;
    The function that is used as part of the inner query to generate worker_counts is pretty complex.  But it runs subsecond if you run it manually.  And it works great when you run the query without the "where worker_count > 0" portion.
    So the where clause on the outer query seems to be causing the problem - it is based off a function that should have calculated a value FIRST then the outer query should run based on the result of the inner query.  Below are the explain plans for the two different versions:
    BAD QUERY - 60 - 70 Seconds
    Description Object Owner Object Name Cost Cardinality Bytes
    SELECT STATEMENT, GOAL = ALL_ROWS     617 1 41
    HASH GROUP BY     617 1 41
      NESTED LOOPS         
       NESTED LOOPS     616 1 41
        VIEW CA17062   58 186 4464
         SORT UNIQUE     58 186 5392
          UNION-ALL         
           TABLE ACCESS BY INDEX ROWID TAS_AUTH ENDORSE_DELEGATE_HISTORY_TBL 42 139 4170
            INDEX RANGE SCAN TAS_AUTH ENDORSE_DELEGATE_HIST_DEF_IDX 3 139 
           TABLE ACCESS BY INDEX ROWID TAS_AUTH ENDORSE_DELEGATE_HISTORY_TBL 14 47 1222
            INDEX RANGE SCAN TAS_AUTH ENDORSE_DELEGATE_HIST_TEMP_IDX 3 47 
        INDEX RANGE SCAN TAS_AUTH TA_SCLENDORSE_PK 2 1 
           TABLE ACCESS BY INDEX ROWID TAS_AUTH ENDORSE_ACTIVITY_TBL 3 1 17
    GOOD QUERY < 1 second
    Description Object Owner Object Name Cost Cardinality Bytes
    SELECT STATEMENT, GOAL = ALL_ROWS     617 25 1025
    HASH GROUP BY     617 25 1025
      NESTED LOOPS         
       NESTED LOOPS     616 25 1025
        VIEW CA17062   58 186 4464
         SORT UNIQUE     58 186 5392
          UNION-ALL         
           TABLE ACCESS BY INDEX ROWID TAS_AUTH ENDORSE_DELEGATE_HISTORY_TBL 42 139 4170
            INDEX RANGE SCAN TAS_AUTH ENDORSE_DELEGATE_HIST_DEF_IDX 3 139 
           TABLE ACCESS BY INDEX ROWID TAS_AUTH ENDORSE_DELEGATE_HISTORY_TBL 14 47 1222
            INDEX RANGE SCAN TAS_AUTH ENDORSE_DELEGATE_HIST_TEMP_IDX 3 47 
        INDEX RANGE SCAN TAS_AUTH TA_SCLENDORSE_PK 2 1 
       TABLE ACCESS BY INDEX ROWID TAS_AUTH ENDORSE_ACTIVITY_TBL 3 1 17
    So those expleain plans look pretty much identical to me - can anyone tell me why having the where clause on the outer query is causing so much trouble and how I can fix it?  I've tried using NO_MERGE and PUSH_SUBQ hints - but nothing that I have done has made the bad query any better.
    Thanks in advance!
    Cory

    I have traced the queries and attached the trace files here too...
    Here is the bad query...
    SQL ID: 0g07hqvjma217 Plan Hash: 0
    alter session set sql_trace = true
    call     count       cpu    elapsed       disk      query    current        rows
    Parse        0      0.00       0.00          0          0          0           0
    Execute      1      0.00       0.00          0          0          0           0
    Fetch        0      0.00       0.00          0          0          0           0
    total        1      0.00       0.00          0          0          0           0
    Misses in library cache during parse: 0
    Misses in library cache during execute: 1
    Optimizer mode: ALL_ROWS
    Parsing user id: 331  (CA17062)
    SQL ID: 9m7787camwh4m Plan Hash: 0
    begin :id := sys.dbms_transaction.local_transaction_id; end;
    call     count       cpu    elapsed       disk      query    current        rows
    Parse        3      0.00       0.00          0          0          0           0
    Execute      3      0.00       0.00          0          0          0           3
    Fetch        0      0.00       0.00          0          0          0           0
    total        6      0.00       0.00          0          0          0           3
    Misses in library cache during parse: 0
    Optimizer mode: ALL_ROWS
    Parsing user id: 331  (CA17062)
    SELECT period, biweek_start, biweek_end, pay_period_complete, worker_count
      FROM (SELECT to_char(en.start_date, 'yyyy/mm/dd') || ' to ' ||
                   to_char(en.start_date + 13, 'yyyy/mm/dd') period,
                   en.start_date biweek_start,
                   en.start_date + 13 biweek_end,
                   decode(sign(sysdate - en.start_date - 13),
                          -1,
                          'In Progress',
                          'Completed') pay_period_complete,
                   ta_mssauth_pkg.actual_endorser(en.start_date, '33811')  worker_count
              FROM (select worker_id,
                           default_endorser resolved_endorser,
                           effective_date,
                           expiration_date
                      from endorse_delegate_history_v
                     where default_endorser = '33811'
                    union
                    select worker_id,
                           temporary_delegate resolved_endorser,
                           effective_date,
                           expiration_date
                      from endorse_delegate_history_v
                     where temporary_delegate = '33811'
                       and temporary_delegate is not null ) de,
                   endorse_activity_v en
             WHERE en.worker_id = de.worker_id
               AND en.endorse_status = 'N'
               AND en.start_date <= de.expiration_date
               AND en.start_date + 13 >= de.effective_date
             GROUP BY en.start_date)
    WHERE worker_count > 0
    call     count       cpu    elapsed       disk      query    current        rows
    Parse        1      0.00       0.00          0          0          0           0
    Execute      1      0.00       0.00          0          0          0           0
    Fetch        1      6.11      14.77         38        455          0           6
    total        3      6.11      14.77         38        455          0           6
    Misses in library cache during parse: 0
    Optimizer mode: ALL_ROWS
    Parsing user id: 331  (CA17062)
    Number of plan statistics captured: 1
    Rows (1st) Rows (avg) Rows (max)  Row Source Operation
             6          6          6  HASH GROUP BY (cr=9330657 pr=826 pw=0 time=86392712 us cost=698 size=41 card=1)
            21         21         21   NESTED LOOPS  (cr=9330657 pr=826 pw=0 time=18442971 us)
            49         49         49    NESTED LOOPS  (cr=9330609 pr=826 pw=0 time=26482026 us cost=697 size=41 card=1)
           213        213        213     VIEW  (cr=32 pr=32 pw=0 time=851827 us cost=58 size=5112 card=213)
           213        213        213      SORT UNIQUE (cr=32 pr=32 pw=0 time=850864 us cost=58 size=5598 card=213)
           213        213        213       UNION-ALL  (cr=32 pr=32 pw=0 time=4390885 us)
            15         15         15        TABLE ACCESS BY INDEX ROWID ENDORSE_DELEGATE_HISTORY_TBL (cr=10 pr=10 pw=0 time=718114 us c)
            15         15         15         INDEX RANGE SCAN ENDORSE_DELEGATE_HIST_DEF_IDX (cr=3 pr=3 pw=0 time=119582 us cost=3 size=)
           198        198        198        TABLE ACCESS BY INDEX ROWID ENDORSE_DELEGATE_HISTORY_TBL (cr=22 pr=22 pw=0 time=7328583 us )
           198        198        198         INDEX RANGE SCAN ENDORSE_DELEGATE_HIST_TEMP_IDX (cr=3 pr=3 pw=0 time=107110 us cost=3 size)
            49         49         49     INDEX RANGE SCAN TA_SCLENDORSE_PK (cr=9330577 pr=794 pw=0 time=157121745 us cost=2 size=0 card)
            21         21         21    TABLE ACCESS BY INDEX ROWID ENDORSE_ACTIVITY_TBL (cr=48 pr=0 pw=0 time=493 us cost=3 size=17 ca)
    Rows     Execution Plan
          0  SELECT STATEMENT   MODE: ALL_ROWS
          6   HASH (GROUP BY)
         21    NESTED LOOPS
         49     NESTED LOOPS
        213      VIEW
        213       SORT (UNIQUE)
        213        UNION-ALL
         15         TABLE ACCESS   MODE: ANALYZED (BY INDEX ROWID) OF
                        'ENDORSE_DELEGATE_HISTORY_TBL' (TABLE)
         15          INDEX   MODE: ANALYZED (RANGE SCAN) OF
                         'ENDORSE_DELEGATE_HIST_DEF_IDX' (INDEX)
        198         TABLE ACCESS   MODE: ANALYZED (BY INDEX ROWID) OF
                        'ENDORSE_DELEGATE_HISTORY_TBL' (TABLE)
        198          INDEX   MODE: ANALYZED (RANGE SCAN) OF
                         'ENDORSE_DELEGATE_HIST_TEMP_IDX' (INDEX)
         49      INDEX   MODE: ANALYZED (RANGE SCAN) OF 'TA_SCLENDORSE_PK'
                     (INDEX (UNIQUE))
         21     TABLE ACCESS   MODE: ANALYZED (BY INDEX ROWID) OF
                    'ENDORSE_ACTIVITY_TBL' (TABLE)
    SQL ID: gwpkaabt9naxy Plan Hash: 2668568437
    SELECT DISTINCT DE.WORKER_ID
    FROM
    ENDORSE_DELEGATE_HISTORY_V DE , ENDORSE_ACTIVITY_V EN ,
      WORKER_ACTIVITY_AUTH_V EA WHERE DE.WORKER_ID = EN.WORKER_ID AND
      EN.WORKER_ID = EA.WORKER_ID AND EN.START_DATE = :B2 AND EN.ENDORSE_STATUS =
      'N' AND EA.ACTIVITY_DATE >= EN.START_DATE AND EA.ACTIVITY_DATE <=
      EN.START_DATE + 13 AND EN.START_DATE <= DE.EXPIRATION_DATE AND
      EN.START_DATE + 13 >= DE.EFFECTIVE_DATE AND (DE.DEFAULT_ENDORSER = :B1 OR
      DE.TEMPORARY_DELEGATE = :B1 ) ORDER BY DE.WORKER_ID
    call     count       cpu    elapsed       disk      query    current        rows
    Parse        1      0.00       0.00          0          0          0           0
    Execute  24015      0.97       1.50          0          0          0           0
    Fetch    24015     56.38     132.62        593    9318744          0         285
    total    48031     57.35     134.12        593    9318744          0         285
    Misses in library cache during parse: 0
    Optimizer mode: ALL_ROWS
    Parsing user id: 3054  (TAS_AUTH)   (recursive depth: 1)
    Number of plan statistics captured: 1
    Rows (1st) Rows (avg) Rows (max)  Row Source Operation
             0          0          0  SORT UNIQUE (cr=407 pr=43 pw=0 time=1057475 us cost=805 size=83 card=1)
             0          0          0   NESTED LOOPS  (cr=407 pr=43 pw=0 time=1057453 us cost=804 size=17347 card=209)
             0          0          0    HASH JOIN RIGHT ANTI (cr=407 pr=43 pw=0 time=1057442 us cost=804 size=16511 card=209)
            19         19         19     INDEX RANGE SCAN INDACC_02X (cr=1 pr=0 pw=0 time=78 us cost=1 size=114 card=19)(object id 5403)
             0          0          0     NESTED LOOPS  (cr=406 pr=43 pw=0 time=1055235 us)
             0          0          0      NESTED LOOPS  (cr=406 pr=43 pw=0 time=1055231 us cost=803 size=19856 card=272)
             0          0          0       NESTED LOOPS  (cr=406 pr=43 pw=0 time=1055226 us cost=431 size=350 card=7)
           186        186        186        TABLE ACCESS BY INDEX ROWID ENDORSE_DELEGATE_HISTORY_TBL (cr=32 pr=0 pw=0 time=4375 us cost)
           213        213        213         BITMAP CONVERSION TO ROWIDS (cr=6 pr=0 pw=0 time=759 us)
             1          1          1          BITMAP OR  (cr=6 pr=0 pw=0 time=533 us)
             1          1          1           BITMAP CONVERSION FROM ROWIDS (cr=3 pr=0 pw=0 time=178 us)
            15         15         15            SORT ORDER BY (cr=3 pr=0 pw=0 time=152 us)
            15         15         15             INDEX RANGE SCAN ENDORSE_DELEGATE_HIST_DEF_IDX (cr=3 pr=0 pw=0 time=62 us cost=3 size=)
             1          1          1           BITMAP CONVERSION FROM ROWIDS (cr=3 pr=0 pw=0 time=328 us)
           198        198        198            SORT ORDER BY (cr=3 pr=0 pw=0 time=319 us)
           198        198        198             INDEX RANGE SCAN ENDORSE_DELEGATE_HIST_TEMP_IDX (cr=3 pr=0 pw=0 time=214 us cost=3 siz)
             0          0          0        TABLE ACCESS BY INDEX ROWID ENDORSE_ACTIVITY_TBL (cr=374 pr=43 pw=0 time=1052137 us cost=2 )
             0          0          0         INDEX UNIQUE SCAN TA_SCLENDORSE_PK (cr=374 pr=43 pw=0 time=1051749 us cost=1 size=0 card=1)
             0          0          0       INDEX RANGE SCAN WORKER_ACTIVITY_WRKR_IX (cr=0 pr=0 pw=0 time=0 us cost=2 size=0 card=90)(ob)
             0          0          0      TABLE ACCESS BY INDEX ROWID WORKER_ACTIVITY_TBL (cr=0 pr=0 pw=0 time=0 us cost=53 size=943 ca)
             0          0          0    INDEX UNIQUE SCAN SCHEDULE_PK (cr=0 pr=0 pw=0 time=0 us cost=0 size=4 card=1)(object id 54342)
    Rows     Execution Plan
          0  SELECT STATEMENT   MODE: ALL_ROWS
          0   SORT (UNIQUE)
          0    CONCATENATION
          0     NESTED LOOPS (ANTI)
         19      NESTED LOOPS
          0       NESTED LOOPS
          0        NESTED LOOPS
          0         TABLE ACCESS   MODE: ANALYZED (BY INDEX ROWID) OF
                        'ENDORSE_DELEGATE_HISTORY_TBL' (TABLE)
        186          INDEX   MODE: ANALYZED (RANGE SCAN) OF
                         'ENDORSE_DELEGATE_HIST_TEMP_IDX' (INDEX)
        213         TABLE ACCESS   MODE: ANALYZED (BY INDEX ROWID) OF
                        'ENDORSE_ACTIVITY_TBL' (TABLE)
          1          INDEX   MODE: ANALYZED (UNIQUE SCAN) OF
                         'TA_SCLENDORSE_PK' (INDEX (UNIQUE))
          1        TABLE ACCESS   MODE: ANALYZED (BY INDEX ROWID) OF
                       'WORKER_ACTIVITY_TBL' (TABLE)
         15         INDEX   MODE: ANALYZED (RANGE SCAN) OF
                        'WORKER_ACTIVITY_WRKR_IX' (INDEX)
         15       INDEX   MODE: ANALYZED (UNIQUE SCAN) OF 'SCHEDULE_PK'
                      (INDEX (UNIQUE))
          1      INDEX   MODE: ANALYZED (RANGE SCAN) OF 'INDACC_02X' (INDEX)
        198     NESTED LOOPS (ANTI)
        198      NESTED LOOPS
          0       NESTED LOOPS
          0        NESTED LOOPS
          0         TABLE ACCESS   MODE: ANALYZED (BY INDEX ROWID) OF
                        'ENDORSE_DELEGATE_HISTORY_TBL' (TABLE)
          0          INDEX   MODE: ANALYZED (RANGE SCAN) OF
                         'ENDORSE_DELEGATE_HIST_DEF_IDX' (INDEX)
          0         TABLE ACCESS   MODE: ANALYZED (BY INDEX ROWID) OF
                        'ENDORSE_ACTIVITY_TBL' (TABLE)
          0          INDEX   MODE: ANALYZED (UNIQUE SCAN) OF
                         'TA_SCLENDORSE_PK' (INDEX (UNIQUE))
          0        TABLE ACCESS   MODE: ANALYZED (BY INDEX ROWID) OF
                       'WORKER_ACTIVITY_TBL' (TABLE)
          0         INDEX   MODE: ANALYZED (RANGE SCAN) OF
                        'WORKER_ACTIVITY_WRKR_IX' (INDEX)
          0       INDEX   MODE: ANALYZED (UNIQUE SCAN) OF 'SCHEDULE_PK'
                      (INDEX (UNIQUE))
          0      INDEX   MODE: ANALYZED (RANGE SCAN) OF 'INDACC_02X' (INDEX)
    SQL ID: 7v8ndut1y3b99 Plan Hash: 2002979989
    SELECT DEFAULT_ENDORSER
    FROM
    ( SELECT DEFAULT_ENDORSER FROM ENDORSE_DELEGATE_HISTORY_V WHERE WORKER_ID =
      :B3 AND TEMPORARY_DELEGATE IS NULL AND :B2 <= EXPIRATION_DATE AND :B1 >=
      EFFECTIVE_DATE ORDER BY EXPIRATION_DATE DESC ) WHERE ROWNUM = 1
    call     count       cpu    elapsed       disk      query    current        rows
    Parse        1      0.00       0.00          0          0          0           0
    Execute    285      0.00       0.01          0          0          0           0
    Fetch      285      0.11       3.24        195      13078          0         285
    total      571      0.11       3.26        195      13078          0         285
    Misses in library cache during parse: 0
    Optimizer mode: ALL_ROWS
    Parsing user id: 3054  (TAS_AUTH)   (recursive depth: 1)
    Number of plan statistics captured: 1
    Rows (1st) Rows (avg) Rows (max)  Row Source Operation
             1          1          1  COUNT STOPKEY (cr=22 pr=20 pw=0 time=576320 us)
             1          1          1   VIEW  (cr=22 pr=20 pw=0 time=576285 us cost=23 size=72 card=12)
             1          1          1    SORT ORDER BY STOPKEY (cr=22 pr=20 pw=0 time=576273 us cost=23 size=396 card=12)
             2          2          2     TABLE ACCESS BY INDEX ROWID ENDORSE_DELEGATE_HISTORY_TBL (cr=22 pr=20 pw=0 time=576205 us cost)
            20         20         20      INDEX RANGE SCAN ENDORSE_DELEGATE_HIST_PK (cr=3 pr=3 pw=0 time=197569 us cost=3 size=0 card=1)
    Rows     Execution Plan
          0  SELECT STATEMENT   MODE: ALL_ROWS
          1   COUNT (STOPKEY)
          1    VIEW
          1     SORT (ORDER BY STOPKEY)
          2      TABLE ACCESS   MODE: ANALYZED (BY INDEX ROWID) OF
                     'ENDORSE_DELEGATE_HISTORY_TBL' (TABLE)
         20       INDEX   MODE: ANALYZED (RANGE SCAN) OF
                      'ENDORSE_DELEGATE_HIST_PK' (INDEX (UNIQUE))
    SQL ID: cf06fwacdmgfk Plan Hash: 1546270724
    select 'x'
    from
    dual
    call     count       cpu    elapsed       disk      query    current        rows
    Parse        1      0.00       0.00          0          0          0           0
    Execute      1      0.00       0.00          0          0          0           0
    Fetch        1      0.00       0.00          0          0          0           1
    total        3      0.00       0.00          0          0          0           1
    Misses in library cache during parse: 0
    Optimizer mode: ALL_ROWS
    Parsing user id: 331  (CA17062)
    Number of plan statistics captured: 1
    Rows (1st) Rows (avg) Rows (max)  Row Source Operation
             1          1          1  FAST DUAL  (cr=0 pr=0 pw=0 time=6 us cost=2 size=0 card=1)
    Rows     Execution Plan
          0  SELECT STATEMENT   MODE: ALL_ROWS
          1   FAST DUAL
    OVERALL TOTALS FOR ALL NON-RECURSIVE STATEMENTS
    call     count       cpu    elapsed       disk      query    current        rows
    Parse        5      0.00       0.00          0          0          0           0
    Execute      6      0.00       0.00          0          0          0           3
    Fetch        2      6.11      14.77         38        455          0           7
    total       13      6.11      14.77         38        455          0          10
    Misses in library cache during parse: 0
    Misses in library cache during execute: 1
    OVERALL TOTALS FOR ALL RECURSIVE STATEMENTS
    call     count       cpu    elapsed       disk      query    current        rows
    Parse        2      0.00       0.00          0          0          0           0
    Execute  24300      0.97       1.51          0          0          0           0
    Fetch    24300     56.49     135.87        788    9331822          0         570
    total    48602     57.46     137.39        788    9331822          0         570
    Misses in library cache during parse: 0
        6  user  SQL statements in session.
        0  internal SQL statements in session.
        6  SQL statements in session.
        4  statements EXPLAINed in this session.
    Trace file: TAST_ora_26885.trc
    Trace file compatibility: 11.1.0.7
    Sort options: default
           1  session in tracefile.
           6  user  SQL statements in trace file.
           0  internal SQL statements in trace file.
           6  SQL statements in trace file.
           6  unique SQL statements in trace file.
           4  SQL statements EXPLAINed using schema:
               dbo.plan_table
                 Schema was specified.
                 Existing table was used.
       73341  lines in trace file.
         178  elapsed seconds in trace file.
    Here is the good query
    SQL ID: 0g07hqvjma217 Plan Hash: 0
    alter session set sql_trace = true
    call     count       cpu    elapsed       disk      query    current        rows
    Parse        0      0.00       0.00          0          0          0           0
    Execute      1      0.00       0.00          0          0          0           0
    Fetch        0      0.00       0.00          0          0          0           0
    total        1      0.00       0.00          0          0          0           0
    Misses in library cache during parse: 0
    Misses in library cache during execute: 1
    Optimizer mode: ALL_ROWS
    Parsing user id: 331  (CA17062)
    SQL ID: 9m7787camwh4m Plan Hash: 0
    begin :id := sys.dbms_transaction.local_transaction_id; end;
    call     count       cpu    elapsed       disk      query    current        rows
    Parse        3      0.00       0.00          0          0          0           0
    Execute      3      0.00       0.00          0          0          0           3
    Fetch        0      0.00       0.00          0          0          0           0
    total        6      0.00       0.00          0          0          0           3
    Misses in library cache during parse: 0
    Optimizer mode: ALL_ROWS
    Parsing user id: 331  (CA17062)
    SELECT period, biweek_start, biweek_end, pay_period_complete, worker_count
      FROM (SELECT to_char(en.start_date, 'yyyy/mm/dd') || ' to ' ||
                   to_char(en.start_date + 13, 'yyyy/mm/dd') period,
                   en.start_date biweek_start,
                   en.start_date + 13 biweek_end,
                   decode(sign(sysdate - en.start_date - 13),
                          -1,
                          'In Progress',
                          'Completed') pay_period_complete,
                   ta_mssauth_pkg.actual_endorser(en.start_date, '33811')  worker_count
              FROM (select worker_id,
                           default_endorser resolved_endorser,
                           effective_date,
                           expiration_date
                      from endorse_delegate_history_v
                     where default_endorser = '33811'
                    union
                    select worker_id,
                           temporary_delegate resolved_endorser,
                           effective_date,
                           expiration_date
                      from endorse_delegate_history_v
                     where temporary_delegate = '33811'
                       and temporary_delegate is not null ) de,
                   endorse_activity_v en
             WHERE en.worker_id = de.worker_id
               AND en.endorse_status = 'N'
               AND en.start_date <= de.expiration_date
               AND en.start_date + 13 >= de.effective_date
             GROUP BY en.start_date)
    -- WHERE worker_count > 0
    call     count       cpu    elapsed       disk      query    current        rows
    Parse        1      0.02       0.03          0          0          0           0
    Execute      1      0.00       0.00          0          0          0           0
    Fetch        1      0.02       0.13          0        841          0           6
    total        3      0.04       0.16          0        841          0           6
    Misses in library cache during parse: 1
    Optimizer mode: ALL_ROWS
    Parsing user id: 331  (CA17062)
    Number of plan statistics captured: 1
    Rows (1st) Rows (avg) Rows (max)  Row Source Operation
             6          6          6  HASH GROUP BY (cr=841 pr=0 pw=0 time=79927 us cost=617 size=1025 card=25)
            21         21         21   NESTED LOOPS  (cr=841 pr=0 pw=0 time=15116 us)
           451        451        451    NESTED LOOPS  (cr=409 pr=0 pw=0 time=33039 us cost=616 size=1025 card=25)
           213        213        213     VIEW  (cr=32 pr=0 pw=0 time=12117 us cost=58 size=4464 card=186)
           213        213        213      SORT UNIQUE (cr=32 pr=0 pw=0 time=12005 us cost=58 size=5392 card=186)
           213        213        213       UNION-ALL  (cr=32 pr=0 pw=0 time=1313 us)
            15         15         15        TABLE ACCESS BY INDEX ROWID ENDORSE_DELEGATE_HISTORY_TBL (cr=10 pr=0 pw=0 time=245 us cost=4
    2 size=4170 card=139)
            15         15         15         INDEX RANGE SCAN ENDORSE_DELEGATE_HIST_DEF_IDX (cr=3 pr=0 pw=0 time=122 us cost=3 size=0 ca
    rd=139)(object id 54559)
           198        198        198        TABLE ACCESS BY INDEX ROWID ENDORSE_DELEGATE_HISTORY_TBL (cr=22 pr=0 pw=0 time=427 us cost=1
    4 size=1222 card=47)
           198        198        198         INDEX RANGE SCAN ENDORSE_DELEGATE_HIST_TEMP_IDX (cr=3 pr=0 pw=0 time=222 us cost=3 size=0 c
    ard=47)(object id 54560)
           451        451        451     INDEX RANGE SCAN TA_SCLENDORSE_PK (cr=377 pr=0 pw=0 time=63328 us cost=2 size=0 card=1)(object
    id 54553)
            21         21         21    TABLE ACCESS BY INDEX ROWID ENDORSE_ACTIVITY_TBL (cr=432 pr=0 pw=0 time=2185 us cost=3 size=17 c
    ard=1)
    Rows     Execution Plan
          0  SELECT STATEMENT   MODE: ALL_ROWS
          6   HASH (GROUP BY)
         21    NESTED LOOPS
        451     NESTED LOOPS
        213      VIEW
        213       SORT (UNIQUE)
        213        UNION-ALL
         15         TABLE ACCESS   MODE: ANALYZED (BY INDEX ROWID) OF
                        'ENDORSE_DELEGATE_HISTORY_TBL' (TABLE)
         15          INDEX   MODE: ANALYZED (RANGE SCAN) OF
                         'ENDORSE_DELEGATE_HIST_DEF_IDX' (INDEX)
        198         TABLE ACCESS   MODE: ANALYZED (BY INDEX ROWID) OF
                        'ENDORSE_DELEGATE_HISTORY_TBL' (TABLE)
        198          INDEX   MODE: ANALYZED (RANGE SCAN) OF
                         'ENDORSE_DELEGATE_HIST_TEMP_IDX' (INDEX)
        451      INDEX   MODE: ANALYZED (RANGE SCAN) OF 'TA_SCLENDORSE_PK'
                     (INDEX (UNIQUE))
         21     TABLE ACCESS   MODE: ANALYZED (BY INDEX ROWID) OF
                    'ENDORSE_ACTIVITY_TBL' (TABLE)
    SQL ID: gwpkaabt9naxy Plan Hash: 2668568437
    SELECT DISTINCT DE.WORKER_ID
    FROM
    ENDORSE_DELEGATE_HISTORY_V DE , ENDORSE_ACTIVITY_V EN ,
      WORKER_ACTIVITY_AUTH_V EA WHERE DE.WORKER_ID = EN.WORKER_ID AND
      EN.WORKER_ID = EA.WORKER_ID AND EN.START_DATE = :B2 AND EN.ENDORSE_STATUS =
      'N' AND EA.ACTIVITY_DATE >= EN.START_DATE AND EA.ACTIVITY_DATE <=
      EN.START_DATE + 13 AND EN.START_DATE <= DE.EXPIRATION_DATE AND
      EN.START_DATE + 13 >= DE.EFFECTIVE_DATE AND (DE.DEFAULT_ENDORSER = :B1 OR
      DE.TEMPORARY_DELEGATE = :B1 ) ORDER BY DE.WORKER_ID
    call     count       cpu    elapsed       disk      query    current        rows
    Parse        1      0.00       0.00          0          0          0           0
    Execute      6      0.01       0.00          0          0          0           0
    Fetch        6      0.01       0.01          0        700      

  • Same query has vastly different run times on different DBs

    I have a query that is run on two different Oracle DBs (located on separate computers). One finishes in about 45 minutes; the other takes over two hours (how much longer, I can't tell you, as Linux keeps dropping the connection at the two-hour mark, but that's another story).
    The tables on each space have identical data; the only significant difference is, one uses tables, while the other uses materialized views. The one with the tables is the faster one.
    Both databases are running 11.2.0.2.0 Enterprise Edition 64-bit.
    I ran an Explain Plan on the queries, and noticed that the faster one had an additional couple of lines in its plan.
    Here is the query:
    select pay_plan
         , case when salary < 10000
                then 0
                when salary >= 150000
                then 15
                else floor(salary / 10000)
           end as salary_group
         , pay_grade
         , pay_step
         , fy
         , count(employee_id) as employee_count
    from
        select dcps.yr + 1 as fy
             , dcps.employee_id
             , dcpds.pay_plan
             , dcpds.pay_grade
             , dcpds.pay_step
             , sum(dcps.salary) as salary
        from
          select /*+ index(dcps dcps_location) */
                 employee_id
               , extract(year from pay_date) as yr
               , sum(
                      case when grc like 'O%'
                           then 0
                           else amt_eec * 26
                      end
                    ) as salary
          from dcps
          where location like 'W%'
          and   to_number(to_char(pay_date, 'MMDD')) between 1014 and 1027
          and   substr(grc, 1, 1) IN ('B', 'C', 'D', 'E', 'F', 'H', 'L', 'O', 'R', 'S', 'T')
          group by employee_id, extract(year from pay_date)
        ) dcps
        join
          select employee_id
               , pay_plan
               , pay_grade
               , pay_step
               , file_date
          from
            select /*+ index(dcpds dcpds_location) */
                   employee_id
                 , pay_plan
                 , pay_grade
                 , decode(pay_plan, 'YA', 0, pay_step) as pay_step
                 , file_date
                 , max(file_date)
                   over (partition by extract(year from (file_date + 61)))
                   as last_file_date
            from dcpds
            where location like 'W%'
            and   pay_plan in ('GS', 'YA')
          where file_date = last_file_date
        ) dcpds
        on (
             dcpds.employee_id = dcps.employee_id
             and dcps.yr = extract(year from dcpds.file_date)
        group by dcps.yr, dcps.employee_id, dcpds.pay_plan, dcpds.pay_grade, dcpds.pay_step
    group by pay_plan
        , case when salary < 10000
               then 0
               when salary >= 150000
               then 15
               else floor(salary / 10000)
          end
        , pay_grade
        , pay_step
        , fy;Here is the "faster" plan:
    (sorry about the formatting - it's taken from an XML version generated in Toad)
    id="0" operation="SELECT STATEMENT" optimizer="ALL_ROWS" cost="10,604,695" cardinality="46" bytes="2,346" cpu_cost="369,545,379,847" io_cost="10,595,408" time="148,466"
        id="1" operation="HASH" option="GROUP BY" cost="10,604,695" cardinality="46" bytes="2,346" cpu_cost="369,545,379,847" io_cost="10,595,408" qblock_name="SEL$1" time="148,466"
            id="2" operation="VIEW" object_owner="DDELGRANDE_DBA" object_instance="1" cost="10,604,694" cardinality="41,337" bytes="2,108,187" cpu_cost="369,477,028,079" io_cost="10,595,408" qblock_name="SEL$103D06FF" time="148,466"
                id="3" operation="HASH" option="GROUP BY" cost="10,604,694" cardinality="41,337" bytes="3,348,297" cpu_cost="369,477,028,079" io_cost="10,595,408" temp_space="4,178,000" qblock_name="SEL$103D06FF" time="148,466"
                    id="4" operation="HASH JOIN" cost="10,604,203" cardinality="41,337" bytes="3,348,297" cpu_cost="369,396,215,555" io_cost="10,594,919" temp_space="4,211,000" access_predicates="&quot;EMPLOYEE_ID&quot;=&quot;ITEM_2&quot; AND &quot;ITEM_1&quot;=EXTRACT(YEAR FROM INTERNAL_FUNCTION(&quot;FILE_DATE&quot;))" time="148,459"
                        object_ID="0" id="5" operation="VIEW" object_owner="SYS" object_name="VW_GBC_6" object_type="VIEW" object_instance="39" cost="2,195,131" cardinality="87,663" bytes="3,155,868" cpu_cost="241,010,751,843" io_cost="2,189,074" qblock_name="SEL$2EE98332" time="30,732"
                            id="6" operation="HASH" option="GROUP BY" cost="2,195,131" cardinality="87,663" bytes="3,155,868" cpu_cost="241,010,751,843" io_cost="2,189,074" temp_space="4,424,000" qblock_name="SEL$2EE98332" time="30,732"
                                id="7" operation="VIEW" object_owner="DDELGRANDE_DBA" object_instance="2" cost="2,194,600" cardinality="91,299" bytes="3,286,764" cpu_cost="240,889,683,025" io_cost="2,188,546" qblock_name="SEL$3" time="30,725"
                                    id="8" operation="HASH" option="GROUP BY" cost="2,194,600" cardinality="91,299" bytes="3,012,867" cpu_cost="240,889,683,025" io_cost="2,188,546" temp_space="4,424,000" qblock_name="SEL$3" time="30,725"
                                        object_ID="1" id="9" operation="TABLE ACCESS" option="BY INDEX ROWID" optimizer="ANALYZED" object_owner="CORP_FIN" object_name="DCPS" object_type="TABLE" object_instance="3" cost="2,194,088" cardinality="91,299" bytes="3,012,867" cpu_cost="240,769,155,979" io_cost="2,188,037" qblock_name="SEL$3" filter_predicates="TO_NUMBER(TO_CHAR(INTERNAL_FUNCTION(&quot;DTE_PPE_END&quot;),'MMDD'))&gt;=1014 AND TO_NUMBER(TO_CHAR(INTERNAL_FUNCTION(&quot;DTE_PPE_END&quot;),'MMDD'))&lt;=1027 AND (SUBSTR(&quot;GRC&quot;,1,1)='B' OR SUBSTR(&quot;GRC&quot;,1,1)='C' OR SUBSTR(&quot;GRC&quot;,1,1)='D' OR SUBSTR(&quot;GRC&quot;,1,1)='E' OR SUBSTR(&quot;GRC&quot;,1,1)='F' OR SUBSTR(&quot;GRC&quot;,1,1)='H' OR SUBSTR(&quot;GRC&quot;,1,1)='L' OR SUBSTR(&quot;GRC&quot;,1,1)='O' OR SUBSTR(&quot;GRC&quot;,1,1)='R' OR SUBSTR(&quot;GRC&quot;,1,1)='S' OR SUBSTR(&quot;GRC&quot;,1,1)='T')" time="30,718"
                                            object_ID="2" id="10" operation="INDEX" option="RANGE SCAN" optimizer="ANALYZED" object_owner="CORP_FIN" object_name="DCPS_LOCATION" object_type="INDEX" search_columns="1" cost="153,659" cardinality="348,929,550" cpu_cost="22,427,363,111" io_cost="153,095" qblock_name="SEL$3" access_predicates="&quot;LOCATION&quot; LIKE 'W%'" filter_predicates="&quot;LOCATION&quot; LIKE 'W%'" time="2,152"/
                        id="11" operation="VIEW" object_owner="DDELGRANDE_DBA" object_instance="5" cost="8,354,912" cardinality="23,219,146" bytes="1,044,861,570" cpu_cost="123,043,653,827" io_cost="8,351,820" qblock_name="SEL$5" filter_predicates="&quot;FILE_DATE&quot;=&quot;LAST_FILE_DATE&quot;" time="116,969"
                            id="12" operation="WINDOW" option="SORT" cost="8,354,912" cardinality="23,219,146" bytes="766,231,818" cpu_cost="123,043,653,827" io_cost="8,351,820" temp_space="1,211,565,000" qblock_name="SEL$5" time="116,969"
                                object_ID="3" id="13" operation="TABLE ACCESS" option="BY INDEX ROWID" optimizer="ANALYZED" object_owner="CORP_FIN" object_name="DCPDS" object_type="TABLE" object_instance="6" cost="8,225,535" cardinality="23,219,146" bytes="766,231,818" cpu_cost="94,120,935,947" io_cost="8,223,170" qblock_name="SEL$5" filter_predicates="&quot;PAY_PLAN&quot;='GS' OR &quot;PAY_PLAN&quot;='YA'" time="115,158"
                                    object_ID="4" id="14" operation="INDEX" option="RANGE SCAN" optimizer="ANALYZED" object_owner="DDELGRANDE_DBA" object_name="DCPDS_LOCATION" object_type="INDEX" search_columns="1" cost="19,848" cardinality="44,080,322" cpu_cost="2,837,503,343" io_cost="19,777" qblock_name="SEL$5" access_predicates="&quot;LOCATION&quot; LIKE 'W%'" filter_predicates="&quot;LOCATION&quot; LIKE 'W%'" time="278"/Here is the "slower" one:
    id="0" operation="SELECT STATEMENT" optimizer="ALL_ROWS" cost="28,025,223" cardinality="104,755" bytes="5,552,015" cpu_cost="806,125,131,535" io_cost="27,983,186" time="392,354"
        id="1" operation="HASH" option="GROUP BY" cost="28,025,223" cardinality="104,755" bytes="5,552,015" cpu_cost="806,125,131,535" io_cost="27,983,186" qblock_name="SEL$1" time="392,354"
            id="2" operation="VIEW" object_owner="DDELGRANDE_DBA" object_instance="1" cost="28,025,218" cardinality="104,755" bytes="5,552,015" cpu_cost="806,027,246,428" io_cost="27,983,186" qblock_name="SEL$1D90FC22" time="392,354"
                id="3" operation="HASH" option="GROUP BY" cost="28,025,218" cardinality="104,755" bytes="8,275,645" cpu_cost="806,027,246,428" io_cost="27,983,186" qblock_name="SEL$1D90FC22" time="392,354"
                    id="4" operation="HASH JOIN" cost="28,025,213" cardinality="104,755" bytes="8,275,645" cpu_cost="805,929,361,321" io_cost="27,983,186" temp_space="481,887,000" access_predicates="&quot;EMPLOYEE_ID&quot;=&quot;DCPS&quot;.&quot;EMPLOYEE_ID&quot; AND &quot;DCPS&quot;.&quot;YR&quot;=EXTRACT(YEAR FROM INTERNAL_FUNCTION(&quot;FILE_DATE&quot;))" time="392,353"
                        id="5" operation="VIEW" object_owner="DDELGRANDE_DBA" object_instance="2" cost="2,823,626" cardinality="10,475,527" bytes="356,167,918" cpu_cost="487,845,223,357" io_cost="2,798,186" qblock_name="SEL$3" time="39,531"
                            id="6" operation="HASH" option="GROUP BY" cost="2,823,626" cardinality="10,475,527" bytes="398,070,026" cpu_cost="487,845,223,357" io_cost="2,798,186" qblock_name="SEL$3" time="39,531"
                                object_ID="0" id="7" operation="MAT_VIEW ACCESS" option="BY INDEX ROWID" object_owner="ARMYMP" object_name="DCPS" object_type="MAT_VIEW" object_instance="3" cost="2,823,051" cardinality="10,475,527" bytes="398,070,026" cpu_cost="476,819,453,647" io_cost="2,798,186" qblock_name="SEL$3" filter_predicates="TO_NUMBER(TO_CHAR(INTERNAL_FUNCTION(&quot;DTE_PPE_END&quot;),'MMDD'))&gt;=1014 AND TO_NUMBER(TO_CHAR(INTERNAL_FUNCTION(&quot;DTE_PPE_END&quot;),'MMDD'))&lt;=1027 AND (SUBSTR(&quot;GRC&quot;,1,1)='B' OR SUBSTR(&quot;GRC&quot;,1,1)='C' OR SUBSTR(&quot;GRC&quot;,1,1)='D' OR SUBSTR(&quot;GRC&quot;,1,1)='E' OR SUBSTR(&quot;GRC&quot;,1,1)='F' OR SUBSTR(&quot;GRC&quot;,1,1)='H' OR SUBSTR(&quot;GRC&quot;,1,1)='L' OR SUBSTR(&quot;GRC&quot;,1,1)='O' OR SUBSTR(&quot;GRC&quot;,1,1)='R' OR SUBSTR(&quot;GRC&quot;,1,1)='S' OR SUBSTR(&quot;GRC&quot;,1,1)='T')" time="39,523"
                                    object_ID="1" id="8" operation="INDEX" option="RANGE SCAN" optimizer="ANALYZED" object_owner="ARMYMP" object_name="DCPS_LOCATION" object_type="INDEX" search_columns="1" cost="281,465" cardinality="215,251,937" cpu_cost="46,870,067,520" io_cost="279,021" qblock_name="SEL$3" access_predicates="&quot;LOCATION&quot; LIKE 'W%'" filter_predicates="&quot;LOCATION&quot; LIKE 'W%'" time="3,941"/
                        id="9" operation="VIEW" object_owner="DDELGRANDE_DBA" object_instance="5" cost="25,134,240" cardinality="20,437,108" bytes="919,669,860" cpu_cost="311,591,056,432" io_cost="25,117,991" qblock_name="SEL$5" filter_predicates="&quot;FILE_DATE&quot;=&quot;LAST_FILE_DATE&quot;" time="351,880"
                            id="10" operation="WINDOW" option="SORT" cost="25,134,240" cardinality="20,437,108" bytes="633,550,348" cpu_cost="311,591,056,432" io_cost="25,117,991" temp_space="984,859,000" qblock_name="SEL$5" time="351,880"
                                object_ID="2" id="11" operation="MAT_VIEW ACCESS" option="BY INDEX ROWID" object_owner="ARMYMP" object_name="DCPDS" object_type="MAT_VIEW" object_instance="6" cost="25,024,511" cardinality="20,437,108" bytes="633,550,348" cpu_cost="286,442,201,519" io_cost="25,009,574" qblock_name="SEL$5" filter_predicates="&quot;PAY_PLAN&quot;='GS' OR &quot;PAY_PLAN&quot;='YA'" time="350,344"
                                    object_ID="3" id="12" operation="INDEX" option="RANGE SCAN" optimizer="ANALYZED" object_owner="ARMYMP" object_name="DCPDS_LOCATION" object_type="INDEX" search_columns="1" cost="52,686" cardinality="34,054,388" cpu_cost="8,896,424,679" io_cost="52,222" qblock_name="SEL$5" access_predicates="&quot;LOCATION&quot; LIKE 'W%'" filter_predicates="&quot;LOCATION&quot; LIKE 'W%'" time="738"/Notice the faster one has two extra lines in it; it is creating a SYS-based view with an additional "Group By" hash.
    Also, the faster one's Table Access By Rowid lines are marked as "Analyzed", while the slower one's Materialized View Access By Index Rowid lines are not.
    Any idea why this would happen?
    (And yes, I do notice that the cpu_cost values for the slower one tend to be 2-4x as high as for the faster one.)

    Also, the faster one's Table Access By Rowid lines are marked as "Analyzed", while the slower one's Materialized View Access By Index Rowid lines are not.Have you gathered stats on MVs table?

  • SQL Query taking the different time in Production and Development Env.

    Hi All,
    Following is the query which is hitting mainly two tables. SA_ORDER & AC_INVOICE.
    My Production and Development both has same amount of data. But in Development env. it is just taking 5 secs. to execute but in Production Env. its handing.
    I have also execution plans of both env. The difference is in development env. it is showing some view i.e. SYS.VW_NSO_1 which is not getting used in Production env.
    And one more input is in Production Env, I don't have DBA privileges.
    What setting will I have to make to resolve this performance problem in Production Env. ?
    Here is the QUERY:------------
    SELECT distinct A.GL_COMPANY_ID,
    A.CUSTOMER_GROUP_ID,
    A.CUSTOMER_GROUP_NAME,
    A.INVOICE_ID,
    A.ORDER_ID,
    B.ORDER_NAME,
    A.CUSTOMER_ID,
    A.CUSTOMER_NAME,
    c.order_name parent_order_name,
    A.INVOICE_DATE,
    A.DUE_DATE,
    A.TOTAL_INVOICED_AMOUNT,
    A.TOTAL_PAID_AMOUNT,
    A.CREDITED_AMOUNT,
    H.write_off
    from ac_invoice a,
    sa_order b,
    (select parent_invoice_id, sum(total_invoiced_amount) write_off
    from ac_invoice
    where invoice_type_id = 3
    group by parent_invoice_id) H,
    (select order_id, order_name from sa_order where order_type_id in (3)) c
    WHERE a.order_id = b.order_id and a.invoice_id = H.parent_invoice_id(+) and
    b.parent_order_id = c.order_id(+) and
    a.invoice_id NOT IN
    ((SELECT invoice_id
    FROM ac_invoice
    WHERE parent_invoice_id IS NOT NULL AND invoice_type_id != 3)
    UNION
    (SELECT parent_invoice_id
    FROM ac_invoice
    WHERE parent_invoice_id IS NOT NULL AND invoice_type_id != 3)) and
    A.GL_COMPANY_ID = 1 and UPPER(A.customer_name) like upper('%KTLA%')
    and
    invoice_type_id in (1, 3, 4, 5, 2) and a.invoice_status_id = 1
    ORDER BY A.INVOICE_ID

    Please follow the advice in [url http://forums.oracle.com/forums/thread.jspa?threadID=501834&tstart=15]this thread for both your development and production environment.
    Regards,
    Rob.

  • RSRT Performance Display SQL - Query has variables

    I have a query with mandatory variables on Year and Period, which are built into my RKF's.  I am trying to run the query via RSRT to see the SQL, but I keep getting error, variables must have values.....I tried creating variant in RSRT, but it goes to some odd screen.

    I do not get a prompt screen.  I go to RSRT,  Enter Query Name, next I Select Performance Info tab, then hit "Display SQL" button.  I get a message:  Specify a value for variable Posting Period (Single Value Entry, Mandatory)
    I never get a prompt.  I am on BI 7.

  • WRH$** tables, Need to know by which user SQL Query has been executed

    Hi,
    From the AWR data (WRH$) tables , I need to know how many sql code is using some specific indexes, I found that information by using the mentioned code. but I need to find out by which user this code has been executed ( not the PARSING_SCHEMA_NAME). Can someone please help me, how can I get that info?
    select a.operation,a.OBJECT_OWNER,a.OBJECT_NAME ,dbms_lob.substr(b.SQL_TEXT,4000,1) from WRH$_SQL_PLAN a,WRH$_SQLTEXT b
    where a.operation='INDEX' and a.SNAP_ID=b.SNAP_ID and a.SQL_ID=b.SQL_ID and a.OBJECT_NAME in (
    'I_CUSTORDER_STAT_CHG_DTM',
    'I_LINE_ITEM_STAT_CHG_DTM',
    'I_SHOPCART_MODIFIEDDTM',
    'I_VISITOR_CART_UPDATED_DTM',
    'R_ORDER_LOG_EVENT_DTM',
    'I_LI_STATUS_HISTORY_EVENT_DTM',
    'I_SHOPPING_CART_CREATEDDTM',
    'I_VISITOR_CART_CREATED_DTM',
    'I_LINE_ITEM_CREATED_DTM_FTM')

    872903 wrote:
    Hi,
    From the AWR data (WRH$) tables , I need to know how many sql code is using some specific indexes, I found that information by using the mentioned code. but I need to find out by which user this code has been executed ( not the PARSING_SCHEMA_NAME). Can someone please help me, how can I get that info?
    select a.operation,a.OBJECT_OWNER,a.OBJECT_NAME ,dbms_lob.substr(b.SQL_TEXT,4000,1) from WRH$_SQL_PLAN a,WRH$_SQLTEXT b
    where a.operation='INDEX' and a.SNAP_ID=b.SNAP_ID and a.SQL_ID=b.SQL_ID and a.OBJECT_NAME in (
    'I_CUSTORDER_STAT_CHG_DTM',
    'I_LINE_ITEM_STAT_CHG_DTM',
    'I_SHOPCART_MODIFIEDDTM',
    'I_VISITOR_CART_UPDATED_DTM',
    'R_ORDER_LOG_EVENT_DTM',
    'I_LI_STATUS_HISTORY_EVENT_DTM',
    'I_SHOPPING_CART_CREATEDDTM',
    'I_VISITOR_CART_CREATED_DTM',
    'I_LINE_ITEM_CREATED_DTM_FTM')consider enabling AUDIT SELECT FROM TABLE upon which INDEX is based.

  • Tuning SQL query with similar subqueries for select columns

    Hi all,
    My query is something like below:
    1> SELECT
    2> A.COL1,
    3> SUM(CASE WHEN A.flag=100 AND NVL(B.flag,0)=0 AND
    4> EXISTS (
    5> SELECT 'ROW_EXISTS'
    6> FROM A A0
    7> WHERE A0.COL2=100 AND NVL(A0.flag,0)=0 AND 0.DIRN<>A.DIRN)
    8> THEN 1
    9> ELSE 0
    10> END) SUM_COLUMN1,
    11>SUM(CASE WHEN A.flag=100 AND
    12> EXISTS (
    13> SELECT 'ROW_EXISTS'
    14> FROM A A0
    15> WHERE A0.COL2=100 AND A0.DIRN<>A.DIRN)
    16> THEN 1
    17> ELSE 0
    18>END) SUM_COLUMN2
    19>FROM A,B
    20>WHERE A.COL=B.KEY_COL
    21>GROUP BY A.COL1
    My problem is that I need to index scan the tables A aliased as A0 in the two exist queries. Lines: 5-7 and 13-15.
    The major performance degradation i see with the query is that it has to scan A0 twice to compute SUM_COLUMN1 and SUM_COLUMN2.
    Is there any way by which i can use the same subquery to scan the table just once to compute the columns.
    The table A has more than a 100million records. So i need to improve performance of this query though it is a small issue.
    Please feel free to ask me more if i'm not clear with the example.
    Thanks in advance,
    Raj

    Also you could use analytic functions:
    SQL> select deptno, sum(case when e.mgr is not null and
      2  exists (select 1 from emp e1 where e1.empno <> e.empno
      3  and e1.deptno = 10 and e1.sal >= 1500)
      4  then 1 else 0 end) sum1,
      5  sum(case when e.mgr is not null and e.sal >= 1200 and
      6  exists (select 1 from emp e1 where e1.empno <> e.empno and e1.deptno = 10)
      7  then 1 else 0 end) sum2
      8  from emp e
      9  group by deptno
    10  /
        DEPTNO       SUM1       SUM2
            10          2          2
            20          5          3
            30          6          5
    SQL> select deptno, sum(case when mgr is not null and
      2  (d12 != empno or empno !=d11) then 1 else 0 end) sum1,
      3  sum(case when mgr is not null and (d21 != empno or empno !=d22)
      4  and sal >= 1200 then 1 else 0 end) sum2
      5  from (
      6  select deptno, empno, mgr, sal,
      7  min(case when deptno = 10 and sal >= 1500
      8  then empno else -1 end) over(order by null) d11,
      9  max(case when deptno = 10 and sal >= 1500
    10  then empno else -1 end) over(order by null) d12,
    11  min(case when deptno = 10 then empno else -1 end) over(order by null) d21,
    12  max(case when deptno = 10 then empno else -1 end) over(order by null) d22
    13  from emp e
    14  )
    15  group by deptno
    16  /
        DEPTNO       SUM1       SUM2
            10          2          2
            20          5          3
            30          6          5In your case it could be something like
    SELECT COL1,
    SUM( CASE WHEN a_flag = 100 and nvl(b_flag,0)=0 and
    (DIRN != MIN_A OR DIRN != MAX_A) THEN 1 ELSE 0 END) SUM_COLUMN1,
    SUM( CASE WHEN a_flag = 100 and
    (DIRN != MIN_B OR DIRN != MAX_B) THEN 1 ELSE 0 END) SUM_COLUMN2
    FROM (
    SELECT A.COL1, A.FLAG A_FLAG, B.FLAG B_FLAG, A.DIRN,
    MIN(CASE WHEN A.COL2=100 and NVL(A.flag,0) = 0 THEN A.DIRN ELSE null END) OVER(order by null) MIN_A,
    MAX(CASE WHEN A.COL2=100 and NVL(A.flag,0) = 0 THEN A.DIRN ELSE null END) OVER(order by null) MAX_A,
    MIN(CASE WHEN A.COL2=100 THEN A.DIRN ELSE null END) OVER(order by null) MIN_B,
    MAX(CASE WHEN A.COL2=100 THEN A.DIRN ELSE null END) OVER(order by null) MAX_B
    FROM A,B
    WHERE A.COL=B.KEY_COL
    GROUP BY COL1
    Rgds.

Maybe you are looking for