Query Plan 'group-by' clause

In evaluating several query plans, I've discovered several sqlstop messages that read:
<groupBy preclustered="true" sqlstop="Cannot generate SQL for the 'group-by' clause because it is not equivalent to the relational GROUP BY clause" stable="true">
I've examined the XQuery code and find no group clause and I can't find a reference to this message in the documentation or by googling the text. I assume that the grouping is being done implicitly by ODSI since it is not in the XQuery source. I have tried restructuring the code to no avail.
My question is -- is this causing me a performance problem since the sql is not generated, and if so, what steps must I take in the xquery structure to avoid this issue.
Many thanks to anyone who can provide some insight into this.
Regards,
PB

is this causing me a performance problem since the sql is not generatedMy question is - why are you asking this question? :) Do you have a performance problem? The "Best Practices" posted as an announcement in this forum might help. Otherwise engage customer support.
To answer your question - your xquery likely generates nested/hierarchical xml - and looks something like below - which can be implemented with a sql left-outer-join ordered by CUSTOMER_ID of the customer-table, and taking the rows returned and ... grouping by CUSTOMER_ID to eliminate the duplicate customer information. So there's your group-by. But you cannot write sql that has a left-outer join, and then a group-by on the left-hand side. So the group by is done in the engine. Since the results are already sorted, the group-by in the engine simply skips over the duplicates (i.e. it's basically free).
for $c in CUSTOMER()
where $c/LAST_NAME = $lastname
return
<CUSTOMER>
... $c/CUSTOMER_ID ... (: in a left-outer-join, the CUSTOMER_ID is duplicated for every ORDER :)
{ for $o in ORDER()
where $o/CUSTOMER_ID eq $c/CUSTOMER_ID
return
</CUSTOMER>

Similar Messages

  • Problem with the query in group by clause

    hi, i have problem with group by clause, can some one please help me.
    select
    header_id,
    (select sum(nvl(dr,0) - nvl(cr ,0)) from temp_tab a1
    where
    a1.country=a.country
    and a1.source='AP'
    and a1.header_id=a.header_id) WHT,
    sum(dr),
    sum(cr) from temp_tab a
    group by header_id,
    (select sum(nvl(dr,0) - nvl(cr ,0)) from temp_tab a1
    where
    a1.country=a.country
    and a1.source='AP'
    and a1.header_id=a.header_id)
    select * from temp_tab
    drop table temp_tab
    create table temp_tab(header_id number ,line_num number, country varchar2(2),
    source varchar2(2), dr number, cr number,primary key(header_id,line_num));
    insert into temp_tab(header_id, line_num,country, source, dr,cr) values(1, 1,'NL','AP',100,20);
    insert into temp_tab(header_id, line_num,country, source, dr,cr) values(1, 2,'PO','AP',20,20);
    insert into temp_tab(header_id, line_num,country, source, dr,cr) values(1, 3,'NL','AP',70,20);
    insert into temp_tab(header_id, line_num,country, source, dr,cr) values(2, 1,'NL','PA',100,20);
    insert into temp_tab(header_id, line_num,country, source, dr,cr) values(2, 2,'NL','PA',100,20);
    insert into temp_tab(header_id, line_num,country, source, dr,cr) values(3, 1,'KR','PO',100,20);
    commit;
    Appreciate your help.
    Thanks,

    select header_id,
             (select sum(nvl(dr,0) - nvl(cr ,0)) from temp_tab a1
             where a1.country=a.country
             and a1.source='AP'
             and a1.header_id=a.header_id) WHT,
             sum(dr),
             sum(cr)
      from temp_tab a
    group by header_id
    ,countryIt's kinda hard to follow what your query does... maybe because I'm only at my second coffee..
    Edited by: Alex Nuijten on Oct 2, 2009 8:07 AM

  • Strange behavior in inner query with group by clause

    Hi All,
    I found a very strange behaviour with Inner query having a group by clause.
    Please look the sample code
    Select b,c,qty from (select a,b,c,sum(d) qty from tab_xyz group by b,c);
    This query gives output by summing b,c wise. But when i run the inner query it gives error as "not a group by expression "
    My question is - though the inner query is wrong, how is it possible that this query gives output.
    it behaves like -
    Select b,c,qty from (select b,c,sum(d) qty from tab_xyz group by b,c);
    Is it a normal behaviour ?
    If it is a normal behaviour, then how group by behaves inside a inner query.
    Thanks !!

    This case I have tested already and it throws error.
    But why the initial posted query is not throwing
    error even the inner query is wrong.
    In what way oracle behaves for the initial posted
    query?what is the scenario that throws the error? is it at the time when you only run the inner query or the whole query?

  • Adding subquery to query w/ Group By clause crashes

    Hello all! I am trying to add in the subquery to the statement below. The query works fine before I add in the subquery, but after adding the subquery it will time out. If I comment out the MIN(table1.EOD_DATE) and the Group By clause, the query works fine.
    I do not want to do this I need those two items. What am I missing here? Any ideas are appreciated, thanks!
    SELECT table1.FUND,
    table1.DEPT,
    table1.ORG,
    table1.ACCT,
    LPAD(table1.FUND,3,0)||LPAD(table1.DEPT,2,0)||LPAD(table1.ORG,4,0)||SUBSTR(table1.ACCT,1,2) acct_no,
    LPAD(table1.FUND,3,0)||LPAD(table1.DEPT,2,0)||LPAD(table1.ORG,4,0)||table1.ACCT acct_no1,
    table2.FUND,
    table2.DEPT,
    table2.ORG,
    table2.ACCT
    MIN(table1.EOD_DATE)
    FROM table1,
    table2
    WHERE table1.fund BETWEEN substr(:P_ACCT_FROM,0,3) AND substr(:P_ACCT_TO,0,3)
    ANDtable1.dept BETWEEN substr(:P_ACCT_FROM,4,2) AND substr(:P_ACCT_TO,4,2)
    ANDtable1.org BETWEEN substr(:P_ACCT_FROM,6,4) AND substr(:P_ACCT_TO,6,4)
    ANDtable1.acct BETWEEN substr(:P_ACCT_FROM,10,5) AND substr(:P_ACCT_TO,10,5)
    AND floor(table1.acct/10000) in (6,8)
    AND SUBSTR(table1.acct,3) != '000'
    ANDtable1.eod_date BETWEEN :p_from_date AND :p_to_date
    AND table2.fund (+)=table1.fund
    AND table2.dept (+)=table1.dept
    AND table2.org (+)=table1.org
    AND table2.acct (+)=table1.acct
    AND table2.type IN( 'PI','JE','PR','VD','VU','AC','AD')
    AND table2.po_no IN
    SELECT trans.po_no
    FROM table2 trans LEFT OUTER JOIN req ON trans.po_no = req.po_no
    WHERE (trans.po_no IS NULL OR (TO_CHAR(req.open_date,'YYYY')) = (TO_CHAR(:p_year,'FM9999')))
    GROUP BY table1.fund,
    table1.dept,
    table1.org,
    table1.acct,
    table2.fund,
    table2.dept,
    table2.org,
    table2.acct
    ORDER BY LPAD(table1.FUND,3,0)||LPAD(table1.DEPT,2,0)||LPAD(table1.ORG,4,0)||SUBSTR(table1.ACCT,1,2),
    LPAD(table1.FUND,3,0)||LPAD(table1.DEPT,2,0)||LPAD(table1.ORG,4,0)||table1.ACCT

    Some untested comments;
    AND floor(table1.acct/10000) in (6,8)
    AND SUBSTR(table1.acct,3) != '000'Can these two conditions be combined, ie is this the same as;
    AND (table1.acct LIKE '0006%' OR table1.acct LIKE '0008%')Ignoring the hard coded dates (assumed they where used for testing) you should avoid using implicit conversions and two digit years;
    AND trans.activity_date BETWEEN TO_CHAR('01-jan-2007', 'dd-mon-yyyy') AND TO_CHAR('01-feb-2007', 'dd-mon-yyyy')You can convert your parameters once rather than converting every row by making hte parameter match the column data type;
    AND (   trans.po_no IS NULL
         OR req.open_date BETWEEN TO_DATE('01-JAN-' || TO_CHAR(:p_year,'9999') || ' 00:00:00' ,'DD-MON-YYYY HH24:MI:SS')
                              AND TO_DATE('31-DEC-' || TO_CHAR(:p_year,'9999') || ' 23:59:59' ,'DD-MON-YYYY HH24:MI:SS')
        )

  • Incorrect warning when parsing query with group by clause

    I am using SQL Developer 4.0.0.13.80 with JDK 1.7.0_51 x64 on Windows 8.1
    I have the following SQL, which works perfectly:
    select substr(to_char(tot_amount), 0, 1) as digit, count(*)
    from transactions
    where tot_amount <> 0
    group by substr(to_char(tot_amount), 0, 1)
    order by digit;
    However, SQL Developer is yellow-underlining the first line, telling me that:
    SELECT list is inconsistent with GROUP BY; amend GROUP BY clause to: substr(to_char(rep_tot_amount), 0, 1), substr(to_char(rep_tot_amount),
    which is clearly wrong.
    Message was edited by: JamHan
    Added code formatting.

    Hello,
    I also have found the same issue with the GROUP BY hint. Another problem I found is that the hint suggests to amend the GROUP BY members to add also constant values that are included in the SELECTed columns and whenever those constants include strings with spaces, it generates an invalid query. Normally, constant values won't affect grouping functions and as such they can be omitted from the GROUP BY members, but it seems SQL Dev thinks it differently.
    For example, if you try the following query:
    SELECT d.DNAME, sum(e.sal) amt, 'Total salary' report_title, 100 report_nr
    FROM scott.emp e, scott.dept d
    WHERE e.DEPTNO = d.DEPTNO
    GROUP BY d.DNAME;
    when you hover the mouse pointer on the yellow hint, a popup will show the following message:
    SELECT list inconsistent with GROUP BY; amend GROUP BY clause to:
    d.DNAME, 'Total, 100
    If you click on the hint, it will amend the group by members to become:
    GROUP BY d.DNAME, 'Total, 100;
    that is clearly incorrect syntax. You may notice that after the change the yellow hint is still there, suggesting to amend further the GROUP BY members. If you click again on the hint, you will end with the following:
    GROUP BY d.DNAME, 'Total, 100;
    , 'Total, 100
    and so on.
    I am not sure if this behaviour was already known (Vadim??), but it would be nice if somebody could file a bug against it.
    Finally when writing big queries with complex functions and constant columns, those yellow lines extend all over the select list and they are visually annoying, so I wonder if there is a way to disable the GROUP BY hint until it gets fixed.
    Thanks for any suggestion,
    Paolo

  • Query with group by clause

    Hi all,
    I am struggling with one query.So Just i am giving the example..
    CREATE TABLE test(num NUMBER,val NUMBER,description VARCHAR2(100))
    table having the following data
    num val description
    1 100 first
    1 200 second
    1 300 third
    Now i want to take the sum and discription based on num field..
    i should get like ==> 1 600 first
    my query is...
    SELECT SUM(val),description
    FROM test
    GROUP BY description
    But it's giving all records.because description field is there in select statement..
    I tried two cursors for this case..its o.k
    But Is there any way instead of using two cursors.
    Thanks,

    Not sure what you are trying to achieve here. For the same value of NUM (say 1), you have 3 different values of VAL & DESCRIPTION. Do you want to sum up the VAL values for a particular value of NUM? In that case, what will be the corresponding DESCRIPTION?
    How did you arrive at the result --- 1 600 first
    -- whereas the DESCRIPTION is different for the 3 VAL values?

  • Why is the GROUP BY clause not working in my Query?

    Dear All,
    Below is the Query for a Summary Debtors Aged Analysis.
    The GROUP BY clause does not seem to be working.
    The Query returns all the unpaid invoices, instead of a single total row for each Customer.
    If a Customer X has 10 unpaid invoices, 10 rows are displayed - one for each invoice.
    I was expecting only 1 row for Customer X, 1 for Customer Y, etc.
    This is what GROUP BY is supposed to do, but it is not doing its work.
    What has gone wrong?
    Thanks
    Leon Lai
    Here's my Query:
    declare @taxdt datetime
    set @taxdt
    /*select 1 from jdt1 t0 where t0.TaxDate*/ = [%1]
    SELECT
    CASE
                 WHEN T0.Account = 1220101 THEN 'Prim Cust'
                 WHEN T0.Account = 1220102 THEN 'Fgn Cust'
                 WHEN T0.Account = 1220103 THEN 'Local Cust'
                 WHEN T0.Account = 1220104 THEN 'Staff Loan' 
                 WHEN T0.Account = 1220105 THEN 'Dep with TP'
                 WHEN T0.Account = 1220106 THEN 'Adv to Cust'
                 WHEN T0.Account = 1220108 THEN 'Sund Drs'
                 ELSE 'Error ! ! !'
    END AS 'Control A/c',
    T1.CardCode AS 'BP Code',
    T2.Notes2 AS 'BP Name',
    SUM ((T0.Debit - T0.Credit)) AS 'Orig. Rs',       
    SUM ((T0.BalDueDeb - T0.BalDueCred)) AS 'Bal. Rs',     
    ((SELECT SUM(T0.BalDueDeb) - Sum(T0.BalDueCred)
        WHERE DateDiff(mm, T0.TaxDate, @taxdt) = 1))    
        AS '1 Mth Ago' 
    /* Similarly for other age brackets*/
    FROM JDT1 T0
    INNER JOIN OCRD T1 ON T0.ShortName = T1.CardCode
    LEFT OUTER JOIN OCPR T2 ON T1.CardCode = T2.Cardcode
    LEFT OUTER JOIN OJDT T3 ON T0.TransID = T3.TransID
    LEFT OUTER JOIN OINV  T4 ON T3.TransID = T4.TransID
    LEFT OUTER JOIN ORIN  T5 ON T3.TransID = T5.TransID
    WHERE
    T1.CardType = 'C'
    and (Balance) != 0
    and (T0.BalDueDeb - T0.BalDueCred) != 0
    GROUP BY T0.Account, T1.CardCode, T2.Notes2, T0.TaxDate

    Dear Neetu,
    Thanks for your reply.
    This Query is a modification of the Query you posted in SAP B1 SQL TIPS & TRICKS
    http://wiki.sdn.sap.com/wiki/display/B1/SAPB1SQLB-FNDebtorsAgingReportbydate
    So, maybe instead of referring to my Query, let's refer to yours. It may be easier for you to understand me.
    Once I understand the problem, I can adapt your query to suit my requirements
    So, let's start with a clean slate:
    The Query you have posted is for a DETAILED Debtors Aging Report.
    This lists all outstanding invoices, and ages them in the Age Brackets.
    What I want is a SUMMARY Debtors Aging Report.
    This will give the total amount owed by each Customer, and this amount is broken down in the Age Bracket Columns
    There will be a single row listed for each customer, something like this:
    Customer     Total Due     Current      1 Mth          2 Mth         3 Mth  etc
    Alfred       500,000       300,000       200,000
    Charles      800,000                     100,000       300,000       400,000
    How can you modify your query to make it become a Summary Report (1 line for each customer even if he has many invoices)?
    Thanks
    Leon Lai
    Here's your code
    SELECT T1.CardCode, T1.CardName, T1.CreditLine, T0.RefDate, T0.Ref1 'Document Number',
         CASE  WHEN T0.TransType=13 THEN 'Invoice'
              WHEN T0.TransType=14 THEN 'Credit Note'
              WHEN T0.TransType=30 THEN 'Journal'
              WHEN T0.TransType=24 THEN 'Receipt'
              END AS 'Document Type',
         T0.DueDate, (T0.Debit- T0.Credit) 'Balance'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')<=-1),0) 'Future'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>=0 and DateDiff(day, T0.DueDate,'[%1]')<=30),0) 'Current'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>30 and DateDiff(day, T0.DueDate,'[%1]')<=60),0) '31-60 Days'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>60 and DateDiff(day, T0.DueDate,'[%1]')<=90),0) '61-90 Days'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>90 and DateDiff(day, T0.DueDate,'[%1]')<=120),0) '91-120 Days'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>=121),0) '121+ Days'
    FROM JDT1 T0 INNER JOIN OCRD T1 ON T0.ShortName = T1.CardCode
    WHERE (T0.MthDate IS NULL OR T0.MthDate > [%1]) AND T0.RefDate <= [%1] AND T1.CardType = 'C'
    ORDER BY T1.CardCode, T0.DueDate, T0.Ref1

  • How to write a SQL Query without using group by clause

    Hi,
    Can anyone help me to find out if there is a approach to build a SQL Query without using group by clause.
    Please site an example if is it so,
    Regards

    I hope this example could illuminate danepc on is problem.
    CREATE or replace TYPE MY_ARRAY AS TABLE OF INTEGER
    CREATE OR REPLACE FUNCTION GET_ARR return my_array
    as
         arr my_array;
    begin
         arr := my_array();
         for i in 1..10 loop
              arr.extend;
              arr(i) := i mod 7;
         end loop;
         return arr;
    end;
    select column_value
    from table(get_arr)
    order by column_value;
    select column_value,count(*) occurences
    from table(get_arr)
    group by column_value
    order by column_value;And the output should be something like this:
    SQL> CREATE or replace TYPE MY_ARRAY AS TABLE OF INTEGER
      2  /
    Tipo creato.
    SQL>
    SQL> CREATE OR REPLACE FUNCTION GET_ARR return my_array
      2  as
      3   arr my_array;
      4  begin
      5   arr := my_array();
      6   for i in 1..10 loop
      7    arr.extend;
      8    arr(i) := i mod 7;
      9   end loop;
    10   return arr;
    11  end;
    12  /
    Funzione creata.
    SQL>
    SQL>
    SQL> select column_value
      2  from table(get_arr)
      3  order by column_value;
    COLUMN_VALUE
               0
               1
               1
               2
               2
               3
               3
               4
               5
               6
    Selezionate 10 righe.
    SQL>
    SQL> select column_value,count(*) occurences
      2  from table(get_arr)
      3  group by column_value
      4  order by column_value;
    COLUMN_VALUE OCCURENCES
               0          1
               1          2
               2          2
               3          2
               4          1
               5          1
               6          1
    Selezionate 7 righe.
    SQL> Bye Alessandro

  • Can u write the following query without using group by clause

    select sp.sid, p.pid, p.name from product p, supp_prod sp
    where sp.pid= p.pid and
    sp.sid = ( select sid from supp_prod group by sid
    having count(*) =(select count(*) from product));
    thru this, we retrieving all the products delivered by the supplier.
    Can you write the following query without using the group by clause

      select sp.sid, p.pid, p.name
        from product p, supp_prod sp
       where sp.pid= p.pid the above query will still retrieve all the products supplied by the supplier. sub-query is not necessary.
    maybe if you can post some sample data and output will help us understand what you want to achieve.

  • Changing DEFAULT_WHERE of a FROM CLAUSE Query (with group by)

    I have a Data Block of type FROM CLAUSE Query.
    The Data Source Name is
    SELECT A2.NAME,A2.EMPLOYEEID,A1.ORGID,A1.FSCLYEARID,A1.STATUS,COUNT(*) AS COUNTER
    FROM S_PLC10300 A1,S_PLC50200 A2
    WHERE A1.EMPLOYEEID=A2.EMPLOYEEID
    GROUP BY A1.ORGID,A1.FSCLYEARID,A1.STATUS,A1.EMPLOYEEID,A2.NAME,A2.EMPLOYEEID
    I have a Query Area with text items which i use to change the DEFAULT_WHERE Property.
    My problem is that i can' t put in the DEFAULT_WHERE a field that doesn't belong to the SELECT Clause. Is there a way to achieve this?
    Maybe changing the whole Data Source Name at runtime ?
    Thanks

    As I said i have a block with FROM clause query:
    SELECT A1.ORGID,A1.FSCLYEARID,A1.STATUS, A1.EMPLOYEEID, A2.NAME,A2.EMPLOYEEID
    FROM S_PLC10300 A1,S_PLC50200 A2
    WHERE A1.EMPLOYEEID=A2.EMPLOYEEID
    GROUP BY A1.ORGID,A1.FSCLYEARID,A1.STATUS,A1.EMPLOYEEID,A2.NAME,A2.EMPLOYEEID
    i use the following code:
    set_block_property(BLOCK,DEFAULT_WHERE,'A1.TRNSDATE>=:QUERY_BLOCK.TRNDATE);
    What i think the code will do is change the FROM Clause Query to:
    SELECT ... WHERE A1.EMPLOYEEID=A2.EMPLOYEEID AND A1.TRNSDATE>=:QUERY_BLOCK.TRNDATE
    GROUP BY ...
    A1.TRNSDATE is a valid field of table A1.
    I can' t add TRNSDATE to my SELECT clause because i will have to add it to the GROUP BY clause.
    Hope i made more sense this time.
    Thanks

  • Can i use an analytic function instead of a group by clause?

    Can i use an analytic function instead of a group by clause? Will this help in any performance improvement?

    analytic can sometimes avoid scanning the table more than once :
    SQL> select ename,  sal, (select sum(sal) from emp where deptno=e.deptno) sum from emp e;
    ENAME             SAL        SUM
    SMITH             800      10875
    ALLEN            1600       9400
    WARD             1250       9400
    JONES            2975      10875
    MARTIN           1250       9400
    BLAKE            2850       9400
    CLARK            2450       8750
    SCOTT            3000      10875
    KING             5000       8750
    TURNER           1500       9400
    ADAMS            1100      10875
    JAMES             950       9400
    FORD             3000      10875
    MILLER           1300       8750
    14 rows selected.
    Execution Plan
    Plan hash value: 3189885365
    | Id  | Operation          | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT   |      |    14 |   182 |     3   (0)| 00:00:01 |
    |   1 |  SORT AGGREGATE    |      |     1 |     7 |            |          |
    |*  2 |   TABLE ACCESS FULL| EMP  |     5 |    35 |     3   (0)| 00:00:01 |
    |   3 |  TABLE ACCESS FULL | EMP  |    14 |   182 |     3   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       2 - filter("DEPTNO"=:B1)which could be rewritten as
    SQL> select ename, sal, sum(sal) over (partition by deptno) sum from emp e;
    ENAME             SAL        SUM
    CLARK            2450       8750
    KING             5000       8750
    MILLER           1300       8750
    JONES            2975      10875
    FORD             3000      10875
    ADAMS            1100      10875
    SMITH             800      10875
    SCOTT            3000      10875
    WARD             1250       9400
    TURNER           1500       9400
    ALLEN            1600       9400
    JAMES             950       9400
    BLAKE            2850       9400
    MARTIN           1250       9400
    14 rows selected.
    Execution Plan
    Plan hash value: 1776581816
    | Id  | Operation          | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT   |      |    14 |   182 |     4  (25)| 00:00:01 |
    |   1 |  WINDOW SORT       |      |    14 |   182 |     4  (25)| 00:00:01 |
    |   2 |   TABLE ACCESS FULL| EMP  |    14 |   182 |     3   (0)| 00:00:01 |
    ---------------------------------------------------------------------------well, there is no group by and no visible performance enhancement in my example, but Oracle7, you must have written the query as :
    SQL> select ename, sal, sum from emp e,(select deptno,sum(sal) sum from emp group by deptno) s where e.deptno=s.deptno;
    ENAME             SAL        SUM
    SMITH             800      10875
    ALLEN            1600       9400
    WARD             1250       9400
    JONES            2975      10875
    MARTIN           1250       9400
    BLAKE            2850       9400
    CLARK            2450       8750
    SCOTT            3000      10875
    KING             5000       8750
    TURNER           1500       9400
    ADAMS            1100      10875
    JAMES             950       9400
    FORD             3000      10875
    MILLER           1300       8750
    14 rows selected.
    Execution Plan
    Plan hash value: 2661063502
    | Id  | Operation            | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT     |      |    14 |   546 |     8  (25)| 00:00:01 |
    |*  1 |  HASH JOIN           |      |    14 |   546 |     8  (25)| 00:00:01 |
    |   2 |   VIEW               |      |     3 |    78 |     4  (25)| 00:00:01 |
    |   3 |    HASH GROUP BY     |      |     3 |    21 |     4  (25)| 00:00:01 |
    |   4 |     TABLE ACCESS FULL| EMP  |    14 |    98 |     3   (0)| 00:00:01 |
    |   5 |   TABLE ACCESS FULL  | EMP  |    14 |   182 |     3   (0)| 00:00:01 |
    -----------------------------------------------------------------------------So maybe it helps

  • Using indexes when using group by clause

    How can I make use of indexes when there is a group by clause in the sql/ pl/sql. Heard that when ever there is a group by clause , sql bypasses use of indexes. Is it true?
    Thanks in advance

    Hi,
    Depending on the query containing the group by, indexes will still be used.
    For example, create a big table based on the all_objects table. Then create an index on the object_type column. Then run this query:
    select count(*), object_type from big_table where object_type != 'PACKAGE' group by object_type
    The execution plan for this query will show the index to be used, the group by does not prevent the optimizer from using an index. Then run this query:
    select count(*), object_type from big_table group by object_type
    The execution plan for this query will show the index not to be used because the whole table - no restrictions - needs to be read to get the result.
    Hope this helps!
    Regards,
    Marco Stuijvenberg
    =
    www.marcostuijvenberg.nl

  • How to use order by within Group by clause

    Hi All,
    I need a help as to how should i use the Order by clause so that the data should be in order with respect to one column, and at the same time whole data is grouped by some other column...like
    Select RaceNo,Venue,FP,BP from Race group by RaceNo
    Here I want to order by FP in ascending order for each group. When i am using it , whole order is changing.
    Can anybody suggest me how to use order by clause that would apply to each group of data.
    Thanks .

    order by clause should be used at the last in any query.......but in group by clause u can't use use that becoz u group according to column then no ordering is needed there......if u want to filter something then u can use having clause and later if u need to arrange then u can use order by clause.........
    i hope this eg.l gives u some clarification....
    e.g
    select deptno,count(empno)
    from dept
    group by deptno
    having count(empno) > 10
    order by deptno

  • SQL 2012 SP1 - How to determine a query that causes Error 8623 in SQL Log: The query processor ran out of internal resources and could not produce a query plan. This is a rare event...

    We are getting multiple 8623 Errors in SQL Log while running Vendor's software.
    How can you catch which Query causes the error?
    I tried to catch it using SQL Profiler Trace but it doesn't show which Query/Sp is the one causing an error. 
    I also tried to use Extended Event session to catch it, but it doesn't create any output either.
    Error:
    The query processor ran out of internal resources and could not produce a query plan. This is a rare event and only expected for extremely complex queries or queries that
    reference a very large number of tables or partitions. Please simplify the query. If you believe you have received this message in error, contact Customer Support Services for more information.
    Extended Event Session that I used;
    CREATE EVENT SESSION
        overly_complex_queries
    ON SERVER
    ADD EVENT sqlserver.error_reported
        ACTION (sqlserver.sql_text, sqlserver.tsql_stack, sqlserver.database_id, sqlserver.username)
        WHERE ([severity] = 16
    AND [error_number] = 8623)
    ADD TARGET package0.asynchronous_file_target
    (SET filename = 'E:\SQLServer2012\MSSQL11.MSSQLSERVER\MSSQL\Log\XE\overly_complex_queries.xel' ,
        metadatafile = 'E:\SQLServer2012\MSSQL11.MSSQLSERVER\MSSQL\Log\XE\overly_complex_queries.xem',
        max_file_size = 10,
        max_rollover_files = 5)
    WITH (MAX_DISPATCH_LATENCY = 5SECONDS)
    GO
    -- Start the session
    ALTER EVENT SESSION overly_complex_queries
        ON SERVER STATE = START
    GO
    It creates only .xel file, but not .xem
    Any help/advice is greatly appreciated

    Hi VK_DBA,
    According to your error message, about which query statement may fail with error message 8623, as other post, you can use trace flag 4102 & 4118 for overcoming this error. Another way is looking for queries with very long IN lists, a large number of
    UNIONs, or a large number of nested sub-queries. These are the most common causes of this particular error message.
    The error 8623 occurs when attempting to select records through a query with a large number of entries in the "IN" clause (> 10,000). For avoiding this error, I suggest that you could apply the latest Cumulative Updates media for SQL Server 2012 Service
    Pack 1, then simplify the query. You may try divide and conquer approach to get part of the query working (as temp table) and then add extra joins / conditions. Or You could try to run the query using the hint option (force order), option (hash join), option
    (merge join) with a plan guide.
    For more information about error 8623, you can review the following article.
    http://blogs.technet.com/b/mdegre/archive/2012/03/13/8623-the-query-processor-ran-out-of-internal-resources-and-could-not-produce-a-query-plan.aspx
    Regards,
    Sofiya Li
    Sofiya Li
    TechNet Community Support

  • How to setup a query plan in effective at any time for SP or SQL query?

    I have a SP which include a group by SQL statement. It retrieve data from a couple of tables which are over 1G size,
    When I run this SP at first time, it take more than 5 minutes to get the result. then I run it again and again, Finally, it become very quick, I can get the result within second.
    Not sure why. I guess it is because of query plan.
    How to make it running at first time to get result within second? How to force a better best query plan in effective at first time to run the query?
    If the engine has better plan in memory, could it be lost at some point? because I have the complain from end user said some times it is fast, sometime it is very slow.
    How to resolve this problem?

    thanks, kevin. Here is the pesudo query( I modify table name as business rule from my company). you are right, mytab3 is a lookup table.
    Select d.stock,i.description,c.categoryname,
    Round(IsNull(Sum(d.qty),0),2) AS qty,
    From mytab1 d,mytab2 s,invent i,mytab3 c       
    Where
    d.stock != 'param1'
    And d.id1 = s.id1    --id1: univarchar(11)        
    And i.code = c.code   --code:univarchar(2)         
    And d.stock = i.stock  --stock: univarchar(12)           
    And i.code2 = d.code2  --code2: univarchar(2)
    And d.code2 = 'param2'
    And s.id2 = 'param3'   --id2: univarchar(6)
    Group By  c.categoryname,d.stock,i.description
    Order By d.stock
    here is the query plan when run this query:
    The command completed with no results returned
    QUERY PLAN FOR STATEMENT 1 (at line 1).
    Executed in parallel by coordinating process and 4 worker processes.
        STEP 1
            The type of query is SELECT (into Worktable1).
            GROUP BY
            Evaluate Grouped SUM OR AVERAGE AGGREGATE.
            Evaluate Grouped SUM OR AVERAGE AGGREGATE.
            Evaluate Grouped SUM OR AVERAGE AGGREGATE.
            Executed in parallel by coordinating process and 4 worker processes.
            FROM TABLE
                mytab2
                s
            Nested iteration.
            Index : ind_mytab2 _id2
            Forward scan.
            Positioning by key.
            Keys are:
                id2  ASC
            Executed in parallel with a 4-way hash scan.
            Using I/O Size 16 Kbytes for index leaf pages.
            With LRU Buffer Replacement Strategy for index leaf pages.
            Using I/O Size 16 Kbytes for data pages.
            With LRU Buffer Replacement Strategy for data pages.
            FROM TABLE
                mytab1
                d
            Nested iteration.
            Index : ind_det_inv
            Forward scan.
            Positioning by key.
            Keys are:
                id1  ASC
            Using I/O Size 16 Kbytes for index leaf pages.
            With LRU Buffer Replacement Strategy for index leaf pages.
            Using I/O Size 16 Kbytes for data pages.
            With LRU Buffer Replacement Strategy for data pages.
            FROM TABLE
                invent
                i
            Nested iteration.
            Using Clustered Index.
            Index : invent_pk
            Forward scan.
            Positioning by key.
            Keys are:
                stock  ASC
                code2  ASC
            Using I/O Size 2 Kbytes for data pages.
            With LRU Buffer Replacement Strategy for data pages.
            FROM TABLE
                mytab3
                c
            Nested iteration.
            Table Scan.
            Forward scan.
            Positioning at start of table.
            Using I/O Size 2 Kbytes for data pages.
            With LRU Buffer Replacement Strategy for data pages.
            TO TABLE
                Worktable1.
            Parallel work table merge.
        STEP 2
            The type of query is INSERT.
            The update mode is direct.
            Executed by coordinating process.
            Worktable2 created, in allpages locking mode, for ORDER BY.
            FROM TABLE
                Worktable1.
            Nested iteration.
            Table Scan.
            Forward scan.
            Positioning at start of table.
            Using I/O Size 8 Kbytes for data pages.
            With MRU Buffer Replacement Strategy for data pages.
            TO TABLE
                Worktable2.
        STEP 3
            The type of query is SELECT.
            Executed by coordinating process.
            This step involves sorting.
            FROM TABLE
                Worktable2.
            Using GETSORTED
            Table Scan.
            Forward scan.
            Positioning at start of table.
            Using I/O Size 8 Kbytes for data pages.
            With MRU Buffer Replacement Strategy for data pages.
    Total estimated I/O cost for statement 1 (at line 1): 1409882.
    The sort for Worktable2 is done in Serial

Maybe you are looking for