Improve Efficiency of SQL Query (reducing Hash Match cost)

I have the following SQL query that only takes 6 seconds to run, but I am trying to get it down to around 3 seconds if possible. I've noticed that there are 3 places in the Execution Plan that have pretty high costs. 1: Hash Match (partial aggregate) - 12%.
2: Hash Match (inner join) - 36%. 3: Index Scan - 15%.
I've been researching Hash Match for a couple days now, but I just don't seem to be getting it. I can't seem to figure out how to decrease the cost. I've read that OUTER APPLY is really inefficient and I have two of those in my query, but I haven't been
able to figure out a way to get the results I need without them. 
I am fairly new to SQL so I am hoping I can get some help with this.
SELECT wi.WorkItemID,
wi.WorkQueueID as WorkQueueID,
wi.WorkItemTypeID,
wi.WorkItemIdentifier,
wi.DisplayIdentifier,
wi.WorkItemStatusID,
wi.SiteID,
wi.AdditionalIdentifier,
wi.WorkQueueDescription,
wi.WorkItemTypeDescription,
wi.WorkQueueCategoryDescription,
wi.Active,
wi.CheckedOutOn,
wi.CheckedOutBy_UserID,
wi.CheckedOutBy_UserName,
wi.CheckedOutBy_FirstName,
wi.CheckedOutBy_LastName,
wi.CheckedOutBy_FullName,
wi.CheckedOutBy_Alias,
b.[Description] as BatchDescription,
bt.[Description] as BatchType,
bs.[Description] as PaymentBatchStatus,
b.PostingDate AS PostingDate,
b.DepositDate,
b.BatchDate,
b.Amount as BatchTotal,
PostedAmount = ISNULL(PostedPayments.PostedAmount, 0),
TotalPayments = ISNULL(PostedPayments.PostedAmount, 0), --Supporting legacy views
TotalVariance = b.Amount - ISNULL(PostedPayments.PostedAmount, 0), -- ISNULL(Payments.TotalPayments, 0),
PaymentsCount = ISNULL(Payments.PaymentsCount, 0),
ISNULL(b.ReferenceNumber, '') AS PaymentBatchReferenceNumber,
b.CreatedOn,
b.CreatedBy_UserID,
cbu.FirstName AS CreatedBy_FirstName,
cbu.LastName AS CreatedBy_LastName,
cbu.DisplayName AS CreatedBy_DisplayName,
cbu.Alias AS CreatedBy_Alias,
cbu.UserName AS CreatedBy_UserName,
b.LastModifiedOn,
b.LastModifiedBy_UserID,
lmbu.FirstName AS LastModifiedBy_FirstName,
lmbu.LastName AS LastModifiedBy_LastName,
lmbu.DisplayName AS LastModifiedBy_DisplayName,
lmbu.Alias AS LastModifiedBy_Alias,
lmbu.UserName AS LastModifiedBy_UserName,
0 AS VisitID, --Payment work items are not associated with VisitID, but it is a PK field on all the Work Queue view models...for now...
0 AS RCMPatientID, --Payment work items are not associated with RCMPatientID, but it is a PK field on all the Work Queue view models...for now...
0 AS PatientID
FROM Account.PaymentBatch AS b (NOLOCK)
INNER JOIN ViewManager.WorkItems AS wi (NOLOCK)
ON wi.WorkitemIdentifier = b.PaymentBatchID
AND wi.WorkItemTypeID = 3
INNER JOIN Account.PaymentBatchStatus AS bs (NOLOCK)
ON b.PaymentBatchStatusID = bs.PaymentBatchStatusID
LEFT JOIN Account.PaymentBatchType bt (NOLOCK)
ON b.PaymentBatchTypeID = bt.PaymentBatchTypeID
INNER JOIN ViewManager.[User] AS cbu (NOLOCK)
ON b.CreatedBy_UserID = cbu.UserID
INNER JOIN ViewManager.[User] AS lmbu (NOLOCK)
ON b.LastModifiedBy_UserID = lmbu.UserID
LEFT JOIN (
SELECT p.PaymentBatchID
, SUM(p.Amount) AS TotalPayments
, COUNT(0) AS PaymentsCount
FROM Account.Payment AS p (NOLOCK)
WHERE p.PaymentTypeID = 1
AND ISNULL(p.Voided, 0) = 0
GROUP BY p.PaymentBatchID
) AS Payments ON b.PaymentBatchID = Payments.PaymentBatchID
LEFT JOIN (
SELECT p.PaymentBatchID
, SUM(pa.Amount) AS PostedAmount
FROM Account.Payment AS p (NOLOCK)
INNER JOIN Account.PaymentAllocation AS PA (NOLOCK)
ON p.PaymentID = pa.PaymentID
AND (pa.AllocationTypeID = 101 OR pa.AllocationTypeID = 111)
WHERE p.PaymentTypeID = 1
AND ISNULL(p.Voided, 0) = 0
GROUP BY p.PaymentBatchID
) AS PostedPayments ON b.PaymentBatchID = PostedPayments.PaymentBatchID
OUTER APPLY (
SELECT
P.PaymentBatchID,
SUM(CASE WHEN P.PaymentTypeID = 1 THEN 1 ELSE 0 END) as PaymentsCount --only count regular payments not adjustments
FROM
Account.Payment p (NOLOCK)
WHERE
p.PaymentBatchID = b.PaymentBatchID
AND p.PaymentTypeID IN (1,2) AND ISNULL(p.Voided, 0)= 0
GROUP BY
P.PaymentBatchID
) payments
OUTER APPLY (
SELECT
P.PaymentBatchID,
SUM(pa.Amount) as PostedAmount
FROM
Account.PaymentAllocation pa (NOLOCK)
INNER JOIN
Account.Payment p (NOLOCK) ON pa.PaymentID = p.PaymentID
INNER JOIN
Account.AllocationType t (NOLOCK) ON pa.AllocationTypeID = t.AllocationTypeID
WHERE
p.PaymentBatchID = b.PaymentBatchID
AND p.PaymentTypeID IN (1,2)
AND ISNULL(p.Voided, 0)= 0
--AND (t.Credit = 0
--OR (t.Credit <> 0 And Offset_PaymentAllocationID IS NULL AND (SELECT COUNT(1) FROM Account.paymentAllocation pa2 (NOLOCK)
-- WHERE pa2.PaymentID = pa.PaymentID AND pa2.AllocationTypeID IN (101, 111)
-- AND pa2.Offset_PaymentAllocationID IS NULL) > 0))
GROUP BY
P.PaymentBatchID
) PostedPayments

The percentages you see are only estimates and may not necessarily not reflect where the real bottleneck is. Particularly, if it is due to a misestimate somewhere.
To be able to help you improve the performance, we need to see the CREATE TABLE and CREATE INDEX statements for the tables. We also need to see the actual query plan. (In XML format, not a screen shot.) Posting all this here is not practical, but you could
upload it somewhere. (Dropbox, Google Drive etc.)
Be very careful with the NOLOCK hint. Using the NOLOCK hint casually lead to transient erratic behaviour which is very difficult to understand. Using it consistenly through a query like you do, is definitely bad practice.
Erland Sommarskog, SQL Server MVP, [email protected]

Similar Messages

  • SQL Query - The number of columns specified in "SQL Query" does not match t

    I am creating new UDM for tablespace alert, below is my query,however its failing with error
    SQL Query - The number of columns specified in "SQL Query" does not match the value specified in "SQL Query Output"
    I selected Metric type is number
    SQL Query Format : Two columns
    Query:
    SELECT d.tablespace_name,round(((a.bytes - NVL(f.bytes,0))*100/a.maxbytes),2)
    used_pct FROM sys.dba_tablespaces d,(select tablespace_name, sum(bytes) bytes, sum(greatest(maxbytes,bytes)) maxbytes from sys.dba_data_files group by tablespace_name) a,(select tablespace_name, sum(bytes) bytes from sys.dba_free_space group by tablespace_name) f
    WHERE d.tablespace_name = a.tablespace_name(+) AND d.tablespace_name = f.tablespace_name(+)
    AND NOT (d.extent_management = 'LOCAL' AND d.contents = 'TEMPORARY');
    Any clues why i am getting error.

    SQL> SELECT d.tablespace_name,round(((a.bytes - NVL(f.bytes,0))*100/a.maxbytes),2) used_pct
    2 FROM sys.dba_tablespaces d,(select tablespace_name, sum(bytes) bytes, sum(greatest(maxbytes,bytes)) maxbytes from sys.dba_data_files group by tablespace_name) a,(select tablespace_name, sum(bytes) bytes from sys.dba_free_space group by tablespace_name) f
    3 WHERE d.tablespace_name = a.tablespace_name(+) AND d.tablespace_name = f.tablespace_name(+)
    4 AND NOT (d.extent_management = 'LOCAL' AND d.contents = 'TEMPORARY');
    TABLESPACE_NAME USED_PCT
    MGMT_TABLESPACE .82
    SYSAUX 1.52
    UNDOTBS1 .32
    RMAN .02
    CORRUPT_TS 10.63
    USERS 0
    SYSTEM 2.26
    MGMT_ECM_DEPOT_TS .04
    MGMT_AD4J_TS 0

  • SQL Query to get match string from table

    Hi Experts,
    BANNER                                                                         
    Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - Production         
    PL/SQL Release 11.1.0.7.0 - Production                                         
    CORE     11.1.0.7.0     Production                                                     
    TNS for 32-bit Windows: Version 11.1.0.7.0 - Production                        
    NLSRTL Version 11.1.0.7.0 - Production                                         
    5 rows selected.
    WITH T AS
    SELECT 'JOHN' FIRSTNAME,'PLAYER' LASTNAME FROM DUAL UNION ALL
    SELECT 'MICHEAL','SMITH' LASTNAME FROM DUAL UNION ALL
    SELECT 'SCOTT','MANAGER' LASTNAME FROM DUAL UNION ALL
    SELECT 'FIRST NAME','LAST NAME' LASTNAME FROM DUAL
    )SELECT * FROM T;
    Input String to my Query will be "JOHN NAME SMITH"
    I need to match the input string to provide result based on Firstname OR Lastname from table.
    How can i acheive this?
    Thanks,

    what the problem in constructing??
    you can use something like this....
    declare
    vStrng varchar2(100) := 'JOHN NAME SMITH';
    v_temp varchar2(1000):= 'SELECT  DISTINCT  firstname,lastname FROM employees,
      (SELECT regexp_substr('''||vStrng||''',''[[:alpha:]]+'',1,level) parsedstr
         FROM dual
        CONNECT BY level<=LENGTH(regexp_replace('''||vStrng||''',''[[:alpha:]]'',''''))+1
      ) WHERE instr(firstname,parsedstr)>0 OR instr(lastname,parsedstr)      >0';
    vSQL varchar2(1000):= 'SELECT ENAME,EMPNO,DEPT.DEPTNO FROM EMP,DEPT WHERE EMP.DEPTNO=DEPT.DEPTNO AND (firstname,lastname) in ('||v_temp||')';
    begin
    --rest of your code....
    end;edit: In the same way...you can use any of the above mentioned solutions..
    Ravi Kumar
    Edited by: ravikumar.sv on Apr 6, 2010 4:12 PM

  • How to find sql query using hash value

    Hi,
    DBVERSION: 9.2.0.8
    I generated statspack report and i want to see total query and i have hash_value here.
    in v$sql am not able to see all the querys ...pls suggest me other ways..
    Thanks,
    Srini...

    Srini wrote:
    Thanks Nikolay,
    But that views are not available in 9i , my DB is in 9.2.0.8...Use v$SQLAREA
    SQL> desc v$sqlarea
    Name                                      Null?    Type
    SQL_TEXT                                           VARCHAR2(1000)
    SQL_FULLTEXT                                       CLOB
    SQL_ID                                             VARCHAR2(13)
    SHARABLE_MEM                                       NUMBER
    PERSISTENT_MEM                                     NUMBER
    RUNTIME_MEM                                        NUMBER
    SORTS                                              NUMBER
    VERSION_COUNT                                      NUMBER
    LOADED_VERSIONS                                    NUMBER
    OPEN_VERSIONS                                      NUMBER
    USERS_OPENING                                      NUMBER
    FETCHES                                            NUMBER
    EXECUTIONS                                         NUMBER
    PX_SERVERS_EXECUTIONS                              NUMBER
    END_OF_FETCH_COUNT                                 NUMBER
    USERS_EXECUTING                                    NUMBER
    LOADS                                              NUMBER
    FIRST_LOAD_TIME                                    VARCHAR2(19)
    INVALIDATIONS                                      NUMBER
    PARSE_CALLS                                        NUMBER
    DISK_READS                                         NUMBER
    DIRECT_WRITES                                      NUMBER
    BUFFER_GETS                                        NUMBER
    APPLICATION_WAIT_TIME                              NUMBER
    CONCURRENCY_WAIT_TIME                              NUMBER
    CLUSTER_WAIT_TIME                                  NUMBER
    USER_IO_WAIT_TIME                                  NUMBER
    PLSQL_EXEC_TIME                                    NUMBER
    JAVA_EXEC_TIME                                     NUMBER
    ROWS_PROCESSED                                     NUMBER
    COMMAND_TYPE                                       NUMBER
    OPTIMIZER_MODE                                     VARCHAR2(10)
    OPTIMIZER_COST                                     NUMBER
    OPTIMIZER_ENV                                      RAW(2000)
    OPTIMIZER_ENV_HASH_VALUE                           NUMBER
    PARSING_USER_ID                                    NUMBER
    PARSING_SCHEMA_ID                                  NUMBER
    PARSING_SCHEMA_NAME                                VARCHAR2(30)
    KEPT_VERSIONS                                      NUMBER
    ADDRESS                                            RAW(4)
    HASH_VALUE                                         NUMBER
    OLD_HASH_VALUE                                     NUMBER
    PLAN_HASH_VALUE                                    NUMBER
    MODULE                                             VARCHAR2(64)
    MODULE_HASH                                        NUMBER
    ACTION                                             VARCHAR2(64)
    ACTION_HASH                                        NUMBER
    SERIALIZABLE_ABORTS                                NUMBER
    OUTLINE_CATEGORY                                   VARCHAR2(64)
    CPU_TIME                                           NUMBER
    ELAPSED_TIME                                       NUMBER
    OUTLINE_SID                                        VARCHAR2(40)
    LAST_ACTIVE_CHILD_ADDRESS                          RAW(4)
    REMOTE                                             VARCHAR2(1)
    OBJECT_STATUS                                      VARCHAR2(19)
    LITERAL_HASH_VALUE                                 NUMBER
    LAST_LOAD_TIME                                     DATE
    IS_OBSOLETE                                        VARCHAR2(1)
    IS_BIND_SENSITIVE                                  VARCHAR2(1)
    IS_BIND_AWARE                                      VARCHAR2(1)
    CHILD_LATCH                                        NUMBER
    SQL_PROFILE                                        VARCHAR2(64)
    SQL_PATCH                                          VARCHAR2(30)
    SQL_PLAN_BASELINE                                  VARCHAR2(30)
    PROGRAM_ID                                         NUMBER
    PROGRAM_LINE#                                      NUMBER
    EXACT_MATCHING_SIGNATURE                           NUMBER
    FORCE_MATCHING_SIGNATURE                           NUMBER
    LAST_ACTIVE_TIME                                   DATE
    BIND_DATA                                          RAW(2000)
    TYPECHECK_MEM                                      NUMBER
    IO_CELL_OFFLOAD_ELIGIBLE_BYTES                     NUMBER
    IO_INTERCONNECT_BYTES                              NUMBER
    PHYSICAL_READ_REQUESTS                             NUMBER
    PHYSICAL_READ_BYTES                                NUMBER
    PHYSICAL_WRITE_REQUESTS                            NUMBER
    PHYSICAL_WRITE_BYTES                               NUMBER
    OPTIMIZED_PHY_READ_REQUESTS                        NUMBER
    LOCKED_TOTAL                                       NUMBER
    PINNED_TOTAL                                       NUMBER
    IO_CELL_UNCOMPRESSED_BYTES                         NUMBER
    IO_CELL_OFFLOAD_RETURNED_BYTES                     NUMBERYou have HASH_VALUE and SQL_FULLTEXT to identify your query. Remember if query is long then you needt to set proper parameters like
    set long 80000
    set pagesize 200
    set linessize 200
    Was that helpful?

  • In  a SQL query whihc has join, How to reduce Multiple instance of a table

    in a SQL query which has join, How to reduce Multiple instance of a table
    Here is an example: I am using Oracle 9i
    is there a way to reduce no.of Person instances from the following query? or can I optimize this query further?
    TABLES:
    mail_table
    mail_id, from_person_id, to_person_id, cc_person_id, subject, body
    person_table
    person_id, name, email
    QUERY:
    SELECT p_from.name from, p_to.name to, p_cc.name cc, subject
    FROM mail, person p_from, person p_to, person p_cc
    WHERE from_person_id = p_from.person_id
    AND to_person_id = p_to.person_id
    AND cc_person_id = p_cc.person_id
    Thnanks in advance,
    Babu.

    SQL> select * from mail;
            ID          F          T         CC
             1          1          2          3
    SQL> select * from person;
           PID NAME
             1 a
             2 b
             3 c
    --Query with only ne Instance of PERSON Table
    SQL> select m.id,max(decode(m.f,p.pid,p.name)) frm_name,
      2         max(decode(m.t,p.pid,p.name)) to_name,
      3         max(decode(m.cc,p.pid,p.name)) cc_name
      4  from mail m,person p
      5  where m.f = p.pid
      6  or m.t = p.pid
      7  or m.cc = p.pid
      8  group by m.id;
            ID FRM_NAME   TO_NAME    CC_NAME
             1 a          b          c
    --Expalin plan for "One instance" Query
    SQL> explain plan for
      2  select m.id,max(decode(m.f,p.pid,p.name)) frm_name,
      3         max(decode(m.t,p.pid,p.name)) to_name,
      4         max(decode(m.cc,p.pid,p.name)) cc_name
      5  from mail m,person p
      6  where m.f = p.pid
      7  or m.t = p.pid
      8  or m.cc = p.pid
      9  group by m.id;
    Explained.
    SQL> select * from table(dbms_xplan.display);
    PLAN_TABLE_OUTPUT
    Plan hash value: 902563036
    | Id  | Operation           | Name   | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT    |        |     3 |   216 |     7  (15)| 00:00:01 |
    |   1 |  HASH GROUP BY      |        |     3 |   216 |     7  (15)| 00:00:01 |
    |   2 |   NESTED LOOPS      |        |     3 |   216 |     6   (0)| 00:00:01 |
    |   3 |    TABLE ACCESS FULL| MAIL   |     1 |    52 |     3   (0)| 00:00:01 |
    |*  4 |    TABLE ACCESS FULL| PERSON |     3 |    60 |     3   (0)| 00:00:01 |
    PLAN_TABLE_OUTPUT
    Predicate Information (identified by operation id):
       4 - filter("M"."F"="P"."PID" OR "M"."T"="P"."PID" OR
                  "M"."CC"="P"."PID")
    Note
       - dynamic sampling used for this statement
    --Explain plan for "Normal" query
    SQL> explain plan for
      2  select m.id,pf.name fname,pt.name tname,pcc.name ccname
      3  from mail m,person pf,person pt,person pcc
      4  where m.f = pf.pid
      5  and m.t = pt.pid
      6  and m.cc = pcc.pid;
    Explained.
    SQL> select * from table(dbms_xplan.display);
    PLAN_TABLE_OUTPUT
    Plan hash value: 4145845855
    | Id  | Operation            | Name   | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT     |        |     1 |   112 |    14  (15)| 00:00:01 |
    |*  1 |  HASH JOIN           |        |     1 |   112 |    14  (15)| 00:00:01 |
    |*  2 |   HASH JOIN          |        |     1 |    92 |    10  (10)| 00:00:01 |
    |*  3 |    HASH JOIN         |        |     1 |    72 |     7  (15)| 00:00:01 |
    |   4 |     TABLE ACCESS FULL| MAIL   |     1 |    52 |     3   (0)| 00:00:01 |
    |   5 |     TABLE ACCESS FULL| PERSON |     3 |    60 |     3   (0)| 00:00:01 |
    PLAN_TABLE_OUTPUT
    |   6 |    TABLE ACCESS FULL | PERSON |     3 |    60 |     3   (0)| 00:00:01 |
    |   7 |   TABLE ACCESS FULL  | PERSON |     3 |    60 |     3   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       1 - access("M"."CC"="PCC"."PID")
       2 - access("M"."T"="PT"."PID")
       3 - access("M"."F"="PF"."PID")
    PLAN_TABLE_OUTPUT
    Note
       - dynamic sampling used for this statement
    25 rows selected.
    Message was edited by:
            jeneesh
    No indexes created...                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • What Indexes should be created for improve performance of the sql query

    Hello Admins
    One of my user is facing slow performance issue while running the below query. Can someone, please guide me for the same. I want to know, what indexes should be created to improve the performance of this query. Also what else can be done to achieve the same.
    SQL Query:-
    SELECT UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.PO_NUMBER))),
    CGSBI_SHIP_DIST_S_EXTRACT.PO_LINE_NUMBER,
    CGSBI_SHIP_DIST_S_EXTRACT.PO_SHIPMENT_NUMBER,
    CGSBI_SHIP_DIST_S_EXTRACT.PO_LINE_SHIP_DIST_NUMBER,
    CGSBI_SHIP_DIST_S_EXTRACT.DISTRIBUTION_DATE,
    UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.PO_LINE_SHIP_DIST_LINE_ID))),
    UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.PROJECT_ID))),
    UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.ACCOUNT_DISTRIBUTION_CODE))),
    UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.ORACLE_ACCOUNT_NUMBER))),
    UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.COMPONENT_CODE))),
    UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.TRANSACTION_CURRENCY_CODE))),
    CGSBI_SHIP_DIST_S_EXTRACT.ORDER_QUANTITY, UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.ORDER_UOM))),
    CGSBI_SHIP_DIST_S_EXTRACT.UNIT_PRICE_TRX_CURRENCY,
    UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.EXPENSE_TYPE_INDICATOR))),
    CGSBI_SHIP_DIST_S_EXTRACT.SOR_ID,
    UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.PO_LINE_ITEM_CODE))),
    UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.PO_LINE_ITEM_DESC))),
    CGSBI_SHIP_DIST_S_EXTRACT.PO_LINE_ITEM_LEAD_TIME,
    UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.UNSPSC_CODE))),
    UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.BUYER_ID))),
    UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.REQUESTOR_ID))),
    UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.APPROVER_ID))),
    UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.SUPPLIER_SITE_ID))),
    UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.SUPPLIER_GSL_NUMBER))),
    UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.SHIP_TO_LOCATION_CODE))),
    UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.TASK_ID))),
    (LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.PO_RELEASE_ID)))
    FROM
    CGSBI_SHIP_DIST_S_EXTRACT
    WHERE PO_NUMBER IS NOT NULL;
    I generated the explain plan for this query and found the following:-
    Explain Plan:-
    SQL> explain plan for SELECT UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.PO_NUMBER))),
    2 CGSBI_SHIP_DIST_S_EXTRACT.PO_LINE_NUMBER,
    3 CGSBI_SHIP_DIST_S_EXTRACT.PO_SHIPMENT_NUMBER,
    4 CGSBI_SHIP_DIST_S_EXTRACT.PO_LINE_SHIP_DIST_NUMBER,
    5 CGSBI_SHIP_DIST_S_EXTRACT.DISTRIBUTION_DATE,
    6 UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.PO_LINE_SHIP_DIST_LINE_ID))),
    7 UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.PROJECT_ID))),
    8 UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.ACCOUNT_DISTRIBUTION_CODE))),
    9 UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.ORACLE_ACCOUNT_NUMBER))),
    10 UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.COMPONENT_CODE))),
    11 UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.TRANSACTION_CURRENCY_CODE))),
    12 CGSBI_SHIP_DIST_S_EXTRACT.ORDER_QUANTITY, UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.ORDER_UOM))),
    13 CGSBI_SHIP_DIST_S_EXTRACT.UNIT_PRICE_TRX_CURRENCY,
    14 UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.EXPENSE_TYPE_INDICATOR))),
    15 CGSBI_SHIP_DIST_S_EXTRACT.SOR_ID,
    16 UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.PO_LINE_ITEM_CODE))),
    17 UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.PO_LINE_ITEM_DESC))),
    18 CGSBI_SHIP_DIST_S_EXTRACT.PO_LINE_ITEM_LEAD_TIME,
    19 UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.UNSPSC_CODE))),
    20 UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.BUYER_ID))),
    21 UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.REQUESTOR_ID))),
    22 UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.APPROVER_ID))),
    23 UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.SUPPLIER_SITE_ID))),
    24 UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.SUPPLIER_GSL_NUMBER))),
    25 UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.SHIP_TO_LOCATION_CODE))),
    26 UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.TASK_ID))),
    27 (LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.PO_RELEASE_ID)))
    28 FROM
    29 CGSBI_SHIP_DIST_S_EXTRACT
    30 WHERE PO_NUMBER IS NOT NULL;
    Explained.
    SQL>
    SQL>
    SQL> SELECT * FROM TABLE(dbms_xplan.display);
    PLAN_TABLE_OUTPUT
    Plan hash value: 3891180274
    | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
    | 0 | SELECT STATEMENT | | 77647 | 39M| 2006 (1)| 00:00:25 |
    |* 1 | TABLE ACCESS FULL| CGSBI_SHIP_DIST_S_EXTRACT | 77647 | 39M| 2006 (1)| 00:00:25 |
    Predicate Information (identified by operation id):
    1 - filter("PO_NUMBER" IS NOT NULL)
    13 rows selected.
    SQL>
    SQL>
    Kindly suggest on this...
    Thanks & Regards
    -Naveen Gangil
    Oracle DBA

    Rafi is correct. Since po_number is the filter column, the only chance you have for using an index to access the table is on that column. However, if there are few (or none) rows with null po_number, you will always have FTS. Does the table have a PK ( which probably consists of at least po_number, line_number )? If that is the case po_number could never be null and in which case you are dumping the whole table and no indexing scheme is going to improve the queri's performance. You might, repeat might, see performance improvement if you cleanse the data in the table ( to eliminate the need for UPPER(LTRIM)RTRIM())) ) before querying it so the the data does not have to be massaged before returning it.

  • Using a SQL Query in an Alert and Matching a String

    I've created an alert in 12.0.4 using a SQL Query and the field that I'm trying to match is a string.  Originally the query returned multiple rows but when the alert still didn't fire, I modified the query WHERE clause to return only one row:
    NAME                                RESPONSE
    Are area lights working?            No
    My expression in the metric is RESPONSE.  In the Monitor I'm matching a string equal to No.  (Do I need double quotes around the matchvalue?  Single quotes?  No quotes?)  The metric is in the 15min scan group, the role is xMII Developers and I'm in that role. The monitor alert string is ' =  '.  Both metric and monitor are active and I've subscribed to the monitor.  Other alerts in the 15min scan group (all based on tag queries) are firing off properly.
    Why is nothing showing up in the Alert Log?
    David Macindoe

    David,
    Did you figure out the answer?  If not, I will try to find someone to address your question.
    Mike

  • Need help in improving the performance for the sql query

    Thanks in advance for helping me.
    I was trying to improve the performance of the below query. I tried the following methods used merge instead of update, used bulk collect / Forall update, used ordered hint, created a temp table and upadated the target table using the same. The methods which I used did not improve any performance. The data count which is updated in the target table is 2 million records and the target table has 15 million records.
    Any suggestions or solutions for improving performance are appreciated
    SQL query:
    update targettable tt
    set mnop = 'G',
    where ( x,y,z ) in
    select a.x, a.y,a.z
    from table1 a
    where (a.x, a.y,a.z) not in (
    select b.x,b.y,b.z
    from table2 b
    where 'O' = b.defg
    and mnop = 'P'
    and hijkl = 'UVW';

    987981 wrote:
    I was trying to improve the performance of the below query. I tried the following methods used merge instead of update, used bulk collect / Forall update, used ordered hint, created a temp table and upadated the target table using the same. The methods which I used did not improve any performance. And that meant what? Surely if you spend all that time and effort to try various approaches, it should mean something? Failures are as important teachers as successes. You need to learn from failures too. :-)
    The data count which is updated in the target table is 2 million records and the target table has 15 million records.Tables have rows btw, not records. Database people tend to get upset when rows are called records, as records exist in files and a database is not a mere collection of records and files.
    The failure to find a single faster method with the approaches you tried, points to that you do not know what the actual performance problem is. And without knowing the problem, you still went ahead, guns blazing.
    The very first step in dealing with any software engineering problem, is to identify the problem. Seeing the symptoms (slow performance) is still a long way from problem identification.
    Part of identifying the performance problem, is understanding the workload. Just what does the code task the database to do?
    From your comments, it needs to find 2 million rows from 15 million rows. Change these rows. And then write 2 million rows back to disk.
    That is not a small workload. Simple example. Let's say that the 2 million row find is 1ms/row and the 2 million row write is also 1ms/row. This means a 66 minute workload. Due to the number of rows, an increase in time/row either way, will potentially have 2 million fold impact.
    So where is the performance problem? Time spend finding the 2 million rows (where other tables need to be read, indexes used, etc)? Time spend writing the 2 million rows (where triggers and indexes need to be fired and maintained)? Both?

  • Sql query to get union of matching rows

    I want to write a sql query that shows union f all the [Type] for each [Key] if [Key] has atleast one [Type] in common and for non matched [Key]s it will return the row as it is.
    For example In the sql table below [Key] '1' and '2' has [Type] 'B' in common and [Key] '1' and '4' has [Type] 'A' in common. In this case [Key] '1', '2' and '4' are related so result will be union of [Type]s in [Key]s '1', '2' and '4' which are 'A', 'B', 'C'
    and 'E' for each [Key]. And [Key] '3' has no [Type] in common so it will return itself.
    Input:
    declare @categories table ([Key] int, [Type] Char(1))
    insert into @categories ([Key], [Type]) values (1, 'A')
    insert into @categories ([Key], [Type]) values (1, 'B')
    insert into @categories ([Key], [Type]) values (2, 'B')
    insert into @categories ([Key], [Type]) values (2, 'C')
    insert into @categories ([Key], [Type]) values (3, 'D')
    insert into @categories ([Key], [Type]) values (4, 'E')
    insert into @categories ([Key], [Type]) values (4, 'A')
    insert into @categories ([Key], [Type]) values (5, 'F')
    insert into @categories ([Key], [Type]) values (5, 'G')
    insert into @categories ([Key], [Type]) values (6, 'G')
    insert into @categories ([Key], [Type]) values (6, 'H')
    Desired output:
    Key Type
    1 A
    1 B
    1 C
    1 E
    2 A
    2 B
    2 C
    3 D
    4 A
    4 B
    4 E
    5 F
    5 G
    5 H
    6 F
    6 G
    6 H

      
    The data element names are wrong. KEY is a reserved word; “Categories" and "type" are called attribute properties in ISO-11179 rules. Matthias Kläy is right; this is a graph problem in disguise, but you can do it with set theory to get  what are called
    equivalence classes. 
    An edge in a graph has two nodes. Some authors allow a single node to count as a edge, but a better way is to put the same node on both ends of the edge. Here is the graph in a table with all the needed constraints. This is why you should post DDL and not be
    so rude.  
    DROP TABLE Graph;
    CREATE TABLE Graph
    (edge INTEGER NOT NULL,
     node_1 CHAR(1) NOT NULL,
     node_2 CHAR(1) NOT NULL,
     CHECK (node_1 <= node_2),
     PRIMARY KEY (node_1, node_2));
    Here is your data in the correct format. 
    INSERT INTO Graph 
    VALUES 
     (1, 'A', 'B'),
     (2, 'B', 'C'),
     (3, 'D', 'D'), -- orphan node
     (4, 'A', 'E'),
     (5, 'F', 'G'),
     (6, 'G', 'H');
    Now Google Warshall's Algorithm. It uses three nested loops and an adjacency array. This is very clean and fast in a procedural language. Not so much in SQL. Let us do this in steps:
    WITH X1 (edge, node1_1, node1_2, node2_1, node2_2 )
    AS
    (SELECT CASE WHEN G1.edge <> G2.edge 
           THEN G1.edge ELSE G2.edge END,
           G1.node_1, G1.node_2, 
           G2.node_1, G2.node_2       
      FROM Graph AS G1, Graph AS G2
     WHERE G1.node_1 IN (G2.node_1, G2.node_2) 
       AND G1.edge <> G2.edge),
    X2 (edge, node_1, node_2)
    AS
    (SELECT edge, 
    CASE WHEN node1_1 IN (node2_1, node2_2) THEN node1_2 ELSE node1_1 END,
    CASE WHEN node2_1 IN (node1_1, node1_2) THEN node2_2 ELSE node2_1 END
    FROM X1)
    SELECT DISTINCT edge,
           CASE WHEN node_1 < node_2 THEN node_1 ELSE node_2 END,
           CASE WHEN node_2 < node_1 THEN node_1 ELSE node_2 END
     FROM X2;
    The X1 subquery gets the paths of length two. The X2 subquery removes the middle node and creates a new sorted edge. Insert these new rows into Graphs, if they are not there. Repeat the process until no more rows are added. 
    DROP TABLE Graph;
    CREATE TABLE Graph
    (edge INTEGER NOT NULL,
     node_1 CHAR(1) NOT NULL,
     node_2 CHAR(1) NOT NULL,
     CHECK (node_1 <= node_2),
     PRIMARY KEY (node_1, node_2));
    INSERT INTO Graph 
    VALUES 
     (1, 'A', 'B'),
     (2, 'B', 'C'),
     (3, 'D', 'D'), -- orphan node
     (4, 'A', 'E'),
     (5, 'F', 'G'),
     (6, 'G', 'H');
    Here is the monster rolled up into a single statement. 
    INSERT INTO Graph
    SELECT DISTINCT edge,
           CASE WHEN node_1 < node_2 THEN node_1 ELSE node_2 END,
           CASE WHEN node_2 < node_1 THEN node_1 ELSE node_2 END
     FROM (SELECT edge, 
    CASE WHEN node1_1 IN (node2_1, node2_2) THEN node1_2 ELSE node1_1 END,
    CASE WHEN node2_1 IN (node1_1, node1_2) THEN node2_2 ELSE node2_1 END
    FROM 
    (SELECT CASE WHEN G1.edge < G2.edge 
           THEN G1.edge ELSE G2.edge END,
           G1.node_1, G1.node_2, 
           G2.node_1, G2.node_2       
      FROM Graph AS G1, Graph AS G2
     WHERE G1.node_1 IN (G2.node_1, G2.node_2) 
       AND G1.edge <> G2.edge) AS X1(edge,node1_1, node1_2, node2_1, node2_2) )
        AS X2(edge, node_1, node_2)
    EXCEPT 
     SELECT * FROM Graph;
     SELECT * FROM Graph ORDER BY edge, node_1, node_2;
    1 A B
    1 A C
    1 B E
    1 C E
    2 B C
    3 D D
    4 A E
    5 F G
    5 F H
    6 G H
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • Efficient SQL Query

    Hi,
    I need to write an efficient query because the query involves 4 checks to be performed on rows before returning a single row. Here is a sample query script for creating the table:
    CREATE TABLE "myschema"."Complaint"
         "Compalint_ID" NUMBER(20,0),
         "ReplyTime" NUMBER, -- this would be in minutes
         "CREATION_TIME" TIMESTAMP (6),
    "STATUS" NUMBER,
         "TYPE" NUMBER,
         CONSTRAINT "CH_PKRTBL_Complaint_ID" PRIMARY KEY ("Compalint_ID")
    USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
    STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
    PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT)
    TABLESPACE "myspace" ENABLE
    ) PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING
    STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
    PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT)
    TABLESPACE "myspace" ;
    CREATE UNIQUE INDEX "myschema"."CH_PKRTBL_Complaint_ID" ON "myschema"."Complaint" ("Compalint_ID")
    PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
    STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
    PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT)
    TABLESPACE "myspace" ;
    ALTER TABLE "myschema"."Complaint" ADD CONSTRAINT "CH_PKRTBL_TKTID" PRIMARY KEY ("Compalint_ID")
    USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
    STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
    PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT)
    TABLESPACE "myspace" ENABLE;
    I want to write an efficient sql/pl-sql query with least time to return a row based on following four checks/priorities in order spcified below:
    1. Retun any row which has TYPE = 11
    2. If no row found for 1st check then
         calculate a time difference for all rows as: time_difference (CREATION_TIME - ReplyTime)
         and return the row which has largest differene in -ve (that is the row which has expired first)
    3. If now row found for check 2 then
         return row where SATUS = 22
    4. If no row found for check 3 then
         calculate a time difference for all rows as: time_difference (CREATION_TIME - ReplyTime)
         and return the row which has smallest differene in +ve (that is the row which is going to expire next)
    Kindly help me in achieving this task.
    Thanks.

    Just an idea (not sure about the definitions first expired and next to expire )
    select complaint_id,reply_time,creation_time,complaint_status,complaint_type,
      from (select complaint_id,reply_time,creation_time,complaint_status,complaint_type,
                   case complaint_type when 11 then 11 end check1,
                   systimestamp - (creation_time + reply_time / 60/24) check2,
                   case complaint_type when 22 then 22 end check3,
                   systimestamp - (creation_time + reply_time / 60/24) check4,
                   max(case complaint_type when 11 then 11 end) over
                      (order by null rows between unbounded preceding and unbounded following) check1_max,
                   min(case when systimestamp - (creation_time + reply_time / 60/24) < 0
                            then systimestamp - (creation_time + reply_time / 60/24)
                       end
                      ) over
                      (order by null rows between unbounded preceding and unbounded following) check2_max,
                   max(case complaint_type when 22 then 22 end) over
                      (order by null rows between unbounded preceding and unbounded following) check3_max,
                   min(case when systimestamp - (creation_time + reply_time / 60/24) > 0
                            then systimestamp - (creation_time + reply_time / 60/24)
                       end
                      ) over
                      (order by null rows between unbounded preceding and unbounded following) check4_min
              from complaint
    where coalesce(check1,check2,check3,check4) = coalesce(check1_max,check2_max,check3_max,check4_min)Regards
    Etbin

  • Need SQL query for PO that do NOT have 3-way match.

    The question is -- have any PO"s been generated with other then 3-way match selected - which means they overrode the set-ups in purchasing , to see if there are an PO that do NOT have 3-way match.
    Thanks
    Mohan.

    1)Generally when ever we will do Supplier setup we will select in the Receiving tab Match approval level we will select either 3-way ,2-way,4-way or we will keep that as blank.
    for that we do not have any direct column in the back end ,so we will use the following conditions.
    '2WAY' inspection_required_flag = 'N'
    receipt_required_flag = 'N'
    '3WAY' inspection_required_flag = 'N'
    receipt_required_flag = 'Y'
    '4WAY' inspection_required_flag = 'Y'
    receipt_required_flag = 'Y'
    2)When ever we will create a PO in the shipments level what ever the Match approval level,
    we defined in the supplier will automatically reflects in the shipments-More tab.
    3)Here i wants to know all the PO's whihc are having Match approval level differences between supplier definiton and PO's match approval level.
    (i.e If i will select a supplier for a PO , automatically we will get one Match approvallevel from supplier setup .if i will change that match approval level manually in the PO shipments -More tab i wants to know all that PO by using a SQL query.
    4)But for some PO's i am getting receipt_required_flag and inspection_required_flag as null.But in the Supplier setup it may be one of the Matching approval.
    Thanks
    Mohan.

  • Sql query performance need to get improved

    hi all..
    i got performnace issue with my sp where i used 3 cte's.. i'm posting my code.please help me how can i improve the performance of query
    i created non-clustered indexes for tables based on the keys with which the tables are joined..
    USE [OPTM]
    GO
    /****** Object: StoredProcedure [dbo].[GetSample] Script Date: 01/07/2014 10:29:32 ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    ALTER PROCEDURE [dbo].[GetSample]
    @StartDate DateTime,
    @EndDate DateTime,
    @Portfolio int,
    @Program int,
    @Project int
    AS
    Date Author Purpose
    06/11/2012 Ajeesh.C To get the Workitem details for the Scope Workitem Green chart Report.
    06/11/2012 Shinoj.P T-SQL re-structuring.
    Testing :
    exec [dbo].[GetSample] '01/01/2013','12/31/2013',-1,-1,-1
    exec [dbo].[GetSample] '01/01/2013','12/31/2013',16,24,199
    exec [dbo].[GetSample] '11/01/2013','12/31/2013',-1,-1,703
    exec [dbo].[GetSample] '11/01/2012','11/30/2012',8,-1,-1
    select * from tb_Portfolio
    BEGIN
    DECLARE @Scope nvarchar(250),@ScopeID int,@ProjectID int,@WorkItem nvarchar(250),@ProgramID int, @PortfolioID int;
    -------Added 3 columns(StatusID,Status,TaskID)--------
    CREATE TABLE #GrnChartTempTable
    AllocationDate datetime NULL,
    Division nvarchar(50) NULL,
    DivisionID int NULL,
    ResourceName nvarchar(250) NULL,
    ResourceEmailID nvarchar(max) NULL,
    ResourceID int NULL,
    Project nvarchar(250) NULL,
    ProjectID int NULL,
    Scope nvarchar(MAX) NULL,
    ScopeID int NULL,
    WorkItem nvarchar(MAX) NULL,
    TaskStartDate datetime NULL,
    TaskEndDate datetime NULL,
    ProgramID int NULL,
    Program nvarchar(250) NULL,
    PortfolioID int NULL,
    Portfolio nvarchar(250) NULL,
    StatusID int NULL,
    Status nvarchar(50) NULL,
    TaskID int null,
    EstimateHrs nvarchar(250) NULL,
    ScopeEstimateHrs int NULL,
    Allocated int NOT NULL
    WITH Datematrix(AllocationDate)
    As
    SELECT @StartDate AS AllocationDate
    UNION ALL
    SELECT DATEADD(D,1,AllocationDate) AS AllocationDate
    FROM Datematrix WHERE AllocationDate<@EndDate
    Allocation (Division,DivisionID,ResourceName,ResourceEmailID,ResourceID,Project
    ,ProjectID,Scope,ScopeID,WorkItem,TaskStartDate,TaskEndDate
    ,ProgramID ,Program,PortfolioID ,Portfolio,StatusID,Status,TaskID,EstimateHrs,ScopeEstimateHrs)
    AS
    SELECT
    DIV.Division
    ,RES.DivisionID
    ,RES.ResourceName
    ,ResourceEmailID = STUFF((
    SELECT COALESCE( ', ' + CONVERT(VARCHAR,RES.Email1), '')
    FROM dbo.TasksResource TSKRES WITH(NOLOCK) LEFT OUTER JOIN
    dbo.tb_Resource RES WITH(NOLOCK) ON RES.UID = TSKRES.ResourceID
    WHERE TSKRES.TaskID = TSK.TaskID
    FOR XML PATH('')), 1, 1, '')
    ,RES.UID ResourceID
    ,PRJ.Project + ' (' + CONVERT(VARCHAR(15),PRJ.StartDate,101) +' - ' + CONVERT(VARCHAR(15),PRJ.EndDate,101) + ')' as Project
    ,PRJ.UID ProjectID
    ,SCP.Title Scope
    ,SCP.ScopeID
    ,TSK.Title WorkItem
    ,TSK.StartDate TaskStartDate
    ,TSK.EndDate TaskEndDate
    ,PRJ.ProgramID
    ,PR.Program
    ,PR.PortfolioID
    ,PF.Portfolio
    ,TSK.StatusID
    ,ST.Status
    ,TSK.TaskID
    ,TSK.EstimateHrs
    ,(isnull(SCP.EstimateARCH,0) + isnull(SCP.EstimateBA,0) + isnull(SCP.EstimateDev,0) + isnull(SCP.EstimatePM,0) + isnull(SCP.EstimateQA,0) + isnull(SCP.EstimateRM,0)) as ScopeEstimateHrs
    --SCP.EstimateARCH + SCP.EstimateBA +SCP.EstimateDev +SCP.EstimatePM +SCP.EstimateQA +SCP.EstimateRM as ScopeEstimateHrs
    FROM Tasks TSK WITH(NOLOCK)
    INNER JOIN dbo.Scope SCP WITH(NOLOCK) ON TSK.ScopeID = SCP.ScopeID
    INNER JOIN dbo.tb_Project PRJ WITH(NOLOCK)ON TSK.ProjectID = PRJ.UID
    INNER JOIN dbo.tb_Program PR WITH(NOLOCK) ON PR.UID=PRJ.ProgramID
    INNER JOIN dbo.tb_Portfolio PF WITH(NOLOCK)ON PF.UID=PR.PortfolioID
    LEFT OUTER JOIN dbo.TasksResource TSKRES WITH(NOLOCK)ON TSKRES.TaskID = TSK.TaskID
    LEFT OUTER JOIN dbo.tb_Resource RES WITH(NOLOCK) ON RES.UID = TSKRES.ResourceID
    LEFT JOIN dbo.tb_Division DIV WITH(NOLOCK) ON RES.DivisionID = DIV.UID
    LEFT JOIN dbo.tb_Status ST WITH(NOLOCK) ON TSK.StatusID=ST.UID /*relating with the high level work items */
    WHERE (PRJ.UID = @Project OR @Project = -1)
    AND (PRJ.ProgramID = @Program OR @Program = -1)
    AND (PRJ.PortfolioID =@Portfolio OR @Portfolio = -1)
    MainData (AllocationDate,Division,DivisionID,ResourceName,ResourceEmailID,ResourceID,Project,ProjectID
    ,Scope,ScopeID,WorkItem,TaskStartDate,TaskEndDate
    ,ProgramID ,Program,PortfolioID ,Portfolio,StatusID,Status,TaskID,EstimateHrs,ScopeEstimateHrs,Allocated)
    AS
    ( SELECT
    Datematrix.*
    ,Allocation.*
    ,CASE WHEN ISDATE(TaskStartDate)=1 THEN 1 ELSE 0 END AS Allocated
    FROM Datematrix FULL OUTER JOIN Allocation
    ON ( Datematrix.AllocationDate>= Allocation.TaskStartDate
    AND Datematrix.AllocationDate<=Allocation.TaskEndDate
    INSERT INTO #GrnChartTempTable
    SELECT * FROM MainData
    OPTION (MAXRECURSION 0);
    SELECT TOP 1 @Scope=Scope,@ScopeID=ScopeID, @ProjectID=ProjectID
    ,@WorkItem=WorkItem,@ProgramID=ProgramID,@PortfolioID=PortfolioID
    FROM #GrnChartTempTable WHERE Scope IS NOT NULL AND ISDATE(AllocationDate)=1 ORDER BY Scope ;
    SELECT AllocationDate,Division,DivisionID
    ,ResourceName,ResourceEmailID,ResourceID,Project
    ,ISNULL(ProjectID,@ProjectID) ProjectID
    ,ISNULL(Scope,@Scope) Scope
    ,ISNULL(ScopeID,@ScopeID) ScopeID
    ,ISNULL(WorkItem,@WorkItem) WorkItem
    ,TaskStartDate,TaskEndDate
    ,ISNULL(ProgramID ,@ProgramID) ProgramID
    ,Program
    ,ISNULL(PortfolioID,@PortfolioID) PortfolioID
    ,Portfolio,StatusID,Status,TaskID,EstimateHrs,isnull(ScopeEstimateHrs,0)ScopeEstimateHrs,Allocated
    FROM #GrnChartTempTable MainData
    WHERE ISDATE(MainData.AllocationDate)=1
    AND ISNULL(Scope,@Scope) IS NOT NULL
    --WHERE FinalData.Scope IS NOT NULL
    END
    this is my code pls help..
    lucky

    You need to focus on optimizing your code by looking at the logic and removing any extraneous rows that you do not need - stop depending on the optimizer to do your work. 
    You have the following in multiple lines:   ISDATE(AllocationDate)=1
    Look at your final resultset.  You do not want any other rows (where isdate() <> 1) so stop selecting them in the first place. In addition, you are using a full outer join in the first query that uses this logic.  Since you do not qualify
    your columns with the tablename (or alias - which is a best practice), I cannot say if the isdate logic negates the full outer join - but I suspect it might.  I also question the logic behind the assignment of the local variables and their use in the
    final query.  You could remove the separate assignment query (and the variables) by simply moving that query into a derived table (or cte) of the final query.  That might not be a significant improvement (you did not give any indications about the size
    of the various queries) but I think it is simpler, more resilient, more obvious.  I also question the reasoning behind the use of a full outer join.
    Why do you left join to dbo.tb_Status?  Does not every task have a status?
    You join to the TaskResource and tb_Resource tables multiple times (in the Allocation cte) - and it appears that there is a 1/m relationship between task and this joined resultset.  Yet the primary query of the Allocation cte does no aggregation. 
    That is concerning, but I don't know your data so perhaps this is correct.  OTH, perhaps it depends on an assumption and your existing data has not yet violated that assumption. 
    But these are only guesses.  As Erland indicates, optimzing requires knowledge of the tables, the data, your business logic, etc. 

  • XML Generation using a sql query in an efficient way -Help needed urgently

    Hi
    I am facing the following issue while generating xml using an sql query. I get the below given table using a query.
         CODE      ID      MARK
    ==================================
    1 4 2331 809
    2 4 1772 802
    3 4 2331 845
    4 5 2331 804
    5 5 2331 800
    6 5 2210 801
    I need to generate the below given xml using a query
    <data>
    <CODE>4</CODE>
    <IDS>
    <ID>2331</ID>
    <ID>1772</ID>
    </IDS>
    <MARKS>
    <MARK>809</MARK>
    <MARK>802</MARK>
    <MARK>845</MARK>
    </MARKS>
    </data>
    <data>
    <CODE>5</CODE>
    <IDS>
    <ID>2331</ID>
    <ID>2210</ID>
    </IDS>
    <MARKS>
    <MARK>804</MARK>
    <MARK>800</MARK>
    <MARK>801</MARK>
    </MARKS>
    </data>
    Can anyone help me with some idea to generate the above given CLOB message

    not sure if this is the right way to do it but
    /* Formatted on 10/12/2011 12:52:28 PM (QP5 v5.149.1003.31008) */
    WITH data AS (SELECT 4 code, 2331 id, 809 mark FROM DUAL
                  UNION
                  SELECT 4, 1772, 802 FROM DUAL
                  UNION
                  SELECT 4, 2331, 845 FROM DUAL
                  UNION
                  SELECT 5, 2331, 804 FROM DUAL
                  UNION
                  SELECT 5, 2331, 800 FROM DUAL
                  UNION
                  SELECT 5, 2210, 801 FROM DUAL)
    SELECT TO_CLOB (
                 '<DATA>'
              || listagg (xml, '</DATA><DATA>') WITHIN GROUP (ORDER BY xml)
              || '</DATA>')
              xml
      FROM (  SELECT    '<CODE>'
                     || code
                     || '</CODE><IDS><ID>'
                     || LISTAGG (id, '</ID><ID>') WITHIN GROUP (ORDER BY id)
                     || '</ID><IDS><MARKS><MARK>'
                     || LISTAGG (mark, '</MARK><MARK>') WITHIN GROUP (ORDER BY id)
                     || '</MARK></MARKS>'
                        xml
                FROM data
            GROUP BY code)

  • Looking for and SQL query to match CTI OS agent login ID with the Directory Number (instrument)

    Hi All,
    I am looking for an SQL query to request the HDS database to find out which Directory Number / instrument  was associated with a specific CTI OS agent login ID.
    Has anyone done such a query before ?
    Thanks and Regards
    Nick

    Hi,
    this should work in 8.0 and 8.5:
    SELECT
    ag.PeripheralNumber AS [LoginID],
    al.Extension,
    al.LogoutDateTime
    FROM [instance]_hds.dbo.Agent_Logout al
    JOIN [instance]_awdb.dbo.Agent ag ON al.SkillTargetID = ag.SkillTargetID
    Of course, replace [instance] with the ICM instance.
    The query returns a table with three columns, first is the login ID aka PeripheralNumber, Extension is... well, the agent's extension, and LogoutDateTime is the timestamp when the agent logged out.
    G.

  • SQL query issue, how to improve it?

    Hello all, I want to create a query with with result in the following result. Every first person of an department starts with the letter A and goes up like this:
    Name department
    A Person1 3
    B Person2 3
    C Person3 3
    D Person4 3
    E Person10 3
    A Person6 10
    B Person7 10
    C Person8 10
    A Person4 13
    B Person9 13
    It has to be a SQL query, unfortunately no PL/SQL
    I was able to create this query, but its lacking. Department_id will be a variable, a person can choose one department or several departments, so the query varies in size.
    select chr(64+rownum), name, department_id
    from ( select name, department_id
    from employees
    where department_id = 3
    order by id_but, naam
    union
    select chr(64+rownum), name, department_id
    from ( select name, department_id
    from employees
    where department_id = 10
    order by id_but, naam
    union
    select chr(64+rownum), name, department_id
    from ( select name, department_id
    from employees
    where department_id = 13
    order by id_but, naam
    order by id_but, naam
    The employees table has the following columns:
    id, name, department_id
    Can anyone help me make this query better? parhaps with the With clause?

    Use analytic function ROW_NUMBER:
    with t as (
               select 'A' name,3 department from dual union all
               select 'B',3 from dual union all
               select 'C',3 from dual union all
               select 'D',3 from dual union all
               select 'E',3 from dual union all
               select 'A',10 from dual union all
               select 'B',10 from dual union all
               select 'C',10 from dual union all
               select 'A',13 from dual union all
               select 'B',13 from dual
    select  name,
            'Person' || row_number() over(partition by department order by name) person,
            department
      from  t
      order by 3,
               3
    NAME                           PERSON                                         DEPARTMENT
    A                              Person1                                                 3
    B                              Person2                                                 3
    C                              Person3                                                 3
    D                              Person4                                                 3
    E                              Person5                                                 3
    A                              Person1                                                10
    B                              Person2                                                10
    C                              Person3                                                10
    A                              Person1                                                13
    B                              Person2                                                13
    10 rows selected.
    SQL> SY.

Maybe you are looking for