Where to place ORDER BY clause when a query includes UNION

I have a query that has UNION in it. could you please tell me where to place the ORDER BY clause. Because it's throwing an error if i place the ORDER BY clause at the end

Because you are using the UNION set operator, you need to either specifically list your columns or use positional notation.
Without a set operator we can order by the column name without specifically listing it:
SQL> select * from dual
  2  order by dummy;
D
X
1 row selected.This doesn't work once you introduce a set operator:
SQL> ed
Wrote file afiedt.buf
  1  select * from dual union all
  2  select * from dual union all
  3  select * from dual
  4* order by dummy
SQL> /
order by dummy
ERROR at line 4:
ORA-00904: "DUMMY": invalid identifierSo you need to either use positional notation:
SQL> ed
Wrote file afiedt.buf
  1  select * from dual union all
  2  select * from dual union all
  3  select * from dual
  4* order by 1
SQL> /
D
X
X
X
3 rows selected.Or, specifically list or alias the columns you are projecting:
SQL> ed
Wrote file afiedt.buf
  1  select dummy from dual union all
  2  select dummy from dual union all
  3  select dummy from dual
  4* order by dummy
SQL> /
D
X
X
X
3 rows selected.
SQL> ed
Wrote file afiedt.buf
  1  select dummy as d from dual union all
  2  select dummy as d from dual union all
  3  select dummy as d from dual
  4* order by d
SQL> /
D
X
X
X
3 rows selected.cheers,
Anthony

Similar Messages

  • Query can't include an "ORDER BY" clause when having column heading sorting

    I'm getting the following error when I try to include "ORDER BY" in my sql statement :
    "Your query can't include an "ORDER BY" clause when having column heading sorting enabled"
    I have used other sql statements with "ORDER BY" but this is the first time I have come across this and I don't understand why it's going wrong. Does anyone have a suggestion as to how I could fix it? Here is one of the sql statements which I have tried which is giving me the error:
    select "ID_NUMBER",
    "PROJECT_NAME",
    "PROJECT_TYPE",
    "OWNER",
    "PRIORITY",
    "STATUS",
    "END_DATE",
    "COMMENTS"
    from "PROJECT"
    WHERE "STATUS" != 'Completed' AND "STATUS" != 'Cancelled'
    ORDER BY "END_DATE"
    Regards,
    Ed.

    You must deselect column heading sorting that is in the page "Report Attributes" .This is a check box placed on the same line of the element of the report.
    bye

  • Order by clause in Sub query

    Hi,
    Can we use order by clause in Sub query?
    While using the order by clause, I am getting the "missing expression error" . If I remove order by clause query executing fine.
    Here is my query:
    select *
    from emp_mstr
    where emp_no in(select
    emp_no
    from emp_mstr
    order by branch_no);
    Thanks & Regards,
    Mahi

    May be you miss some required spaces also, other than wrong use of ORDER BY
    select *
    from emp_mstr
    where emp_no in
         ( select e2.emp_no
           from emp_mstr e2
    --       order by e2.branch_no
         );Why do you want to ORDER BY in the subquery, which you use with IN clause? That will not make any difference in the result..Means the result you get with ORDER BY will be same as without that.. And in this case, ORDER by is a unncessary overhead.. And Ordering is very costly..
    And why do you want to have the IN clause at all in your query? You are referring the same tables in the main query and sub query..
    The below will give the same result
    select *
    from emp_mstr
    where emp_no is not nullIf you want to use another table in the subquery, always use aliasess...
    select *
    from emp_mstr
    where emp_no in
         ( select e2.emp_no
           from emp_mstr2 e2
    --       order by e2.branch_no
         );

  • IS IT POSSIBLE TO  WRITE ORDER BY CLAUSE WITHIN INNER QUERY

    IS IT POSSIBLE TO WRITE ORDER BY CLAUSE WITHIN INNER QUERY

    So you still can't :) I still don't see it that strict:
    You know of course that this is possible:
    select ename, (select ename
                     from (select   empno, ename
                               from emp
                              where deptno = 10
                           order by 1) e2
                    where e.empno = e2.empno) a
      from emp eso we have an »ORDER BY CLAUSE WITHIN INNER QUERY« which is even correlated (though through the outer query).
    Whether this makes sense or not is not question imho :-) ... but you can

  • Suppress "Order By" clause in Answers Query

    Hello,
    Is it possible to Suppress "Order By" clause in Answers Query.
    I'm using a database view as data source. In the view definition, "order by" clause is already specified. Is it possible to get the same order in the OBIEE report??
    I do not want to use Sort Order column in the repository.
    Thanks,
    Girish

    You add a rownumber to your DB view and use that to 'sort' your report.
    regards
    John
    http://obiee101.blogspot.com/

  • Order by clause with Named Query

    hi
    i have to give order by clause in Named Query
    how we have to specify is can any body help
    thanks
    Harish

    Assuming an Entity called Handset:
    select h from Handset h order by h.description

  • Problem with group by/order by clause when using huge data

    Hi,
    I'm using below query on my table of size more than 210 million rows.
    SELECT booking_date FROM T_UTR
    WHERE four_eyes_status = 'A' AND booking_date <= '01-jul-2005' AND booking_date >= '01-jan-2004'
    AND invoice_id IS NULL AND link_id = 12345
    AND billing_indicator = 'L'
    GROUP BY booking_date ORDER BY booking_date
    If I'm skipping last line "GROUP BY booking_date ORDER BY booking_date", its giving me immediate result, but, because of group by/order by, the query may take 30 seconds to 2 minutes based on the data fetched for the date range. It may vary from 2 to 2 million rows, & grouping by for so many rows at run time will automatically take some time.
    Here I want to know, is there any procedure in oracle(any function based index) so that I can store/retrieve distinct values for link_id, & booking_date without grouping them at run time. Or the performance of the query can be increased
    Thanks
    Deepak

    Hi,
    You can use Materialized Views as stated earlier - specifically by using Query Rewrite. If the conditions on columns "four_eyes_status", "invoice_id", and "billing_indicator" never change in your query - then you can create a Materialized View that is targeted for those conditions and has lower cardinality (since you aren't grouping by those columns). The "COUNT(*)" allows the use of the DISTINCT operator in addition to "GROUP BY' as well for Query Rewrite.
    Create the Materialized View like this:
    CREATE MATERIALIZED VIEW test_mv1
    BUILD IMMEDIATE
    USING NO INDEX
    REFRESH FORCE ON DEMAND
    ENABLE QUERY REWRITE
    AS
    SELECT booking_date
         , link_id
         , COUNT(*) AS count_star
    FROM T_UTR
    WHERE four_eyes_status = 'A'
      AND invoice_id IS NULL
      AND billing_indicator = 'L'
    GROUP BY booking_date
           , link_id ;To improve performance further - create an index on the "LINK_ID" column like this:
    CREATE INDEX test_mv1_link_id_idx
    ON test_mv1 (link_id);Then - gather stats immediately on the Materialized View so that the CBO can use it for rewriting your original query - like this:
    BEGIN
       DBMS_STATS.gather_table_stats (ownname               => USER
                                    , tabname               => 'TEST_MV1'
                                    , partname              => NULL
                                    , estimate_percent      => DBMS_STATS.auto_sample_size
                                    , block_sample          => FALSE
                                    , method_opt            => 'FOR ALL COLUMNS SIZE 1'
                                    , degree                => NULL
                                    , granularity           => 'ALL'
                                    , cascade               => TRUE
                                    , no_invalidate         => FALSE
    END;
    /Now - the CBO should be able to rewrite your original query to use the Materialized View - provided you set up your session for Query Rewrite like this:
    ALTER SESSION SET query_rewrite_enabled = TRUE;
    ALTER SESSION SET query_rewrite_integrity = ENFORCED; -- set this to whatever staleness you can tolerate - see the docs for details...Now - after setting up your session - try running your query with autotrace to see if it was rewritten...
    Good luck!
    Message was edited by:
    PDaddy

  • [10g] Need help with order by clause in hierarchical query

    I have the following sample data:
    CREATE TABLE     bill_test1
    (     parent_part     CHAR(25)
    ,     child_part     CHAR(25)
    ,     line_nbr     NUMBER(5)
    ,     qty_per          NUMBER(9,5)
    INSERT INTO bill_test1 VALUES ('ABC-1','ABC-10',100,1);
    INSERT INTO bill_test1 VALUES ('ABC-1','ABC-20',200,2);
    INSERT INTO bill_test1 VALUES ('ABC-1','ABC-30',300,3);
    INSERT INTO bill_test1 VALUES ('ABC-1','HARDWARE-1',401,10);
    INSERT INTO bill_test1 VALUES ('ABC-1','HARDWARE-2',402,5);
    INSERT INTO bill_test1 VALUES ('ABC-10','ABC-155',100,2);
    INSERT INTO bill_test1 VALUES ('ABC-10','HARDWARE-1',200,1);
    INSERT INTO bill_test1 VALUES ('ABC-155','RAW-2',100,4.8);
    INSERT INTO bill_test1 VALUES ('ABC-155','HARDWARE-3',200,3);
    INSERT INTO bill_test1 VALUES ('ABC-20','RAW-1',100,10.2);
    INSERT INTO bill_test1 VALUES ('ABC-30','RAW-3',100,3);And the query below gives me exactly what I want, in the order I want it. However, I am wondering if there is a way to get this order without creating the SEQ column, since I don't need it in my results
    SELECT     part_nbr
    ,     parent_part
    ,     child_part
    FROM     (
         SELECT     CONNECT_BY_ROOT b.parent_part                         AS part_nbr
         ,     b.parent_part
         ,     b.child_part
         ,     SYS_CONNECT_BY_PATH(b.line_nbr,' ')                    AS seq
         FROM     bill_test1 b
         ,     dual
         CONNECT BY     parent_part     = PRIOR child_part
    WHERE          part_nbr     = 'ABC-1'
    ORDER BY     seq
    Results of above query, except with SEQ included in SELECT (just to show what I'm sorting off of):
    PART_NBR                     PARENT_PART                  CHILD_PART                   SEQ
    ABC-1                        ABC-1                        ABC-10                        100
    ABC-1                        ABC-10                       ABC-155                       100 100
    ABC-1                        ABC-155                      RAW-2                         100 100 100
    ABC-1                        ABC-155                      HARDWARE-3                    100 100 200
    ABC-1                        ABC-10                       HARDWARE-1                    100 200
    ABC-1                        ABC-1                        ABC-20                        200
    ABC-1                        ABC-20                       RAW-1                         200 100
    ABC-1                        ABC-1                        ABC-30                        300
    ABC-1                        ABC-30                       RAW-3                         300 100
    ABC-1                        ABC-1                        HARDWARE-1                    401
    ABC-1                        ABC-1                        HARDWARE-2                    402

    Hi,
    As long as there's only one root, you can say ORDER SIBLINGS BY, but you can't do that in a sub-query (well, you can, but usually there's no point in doing it in a sub-query). If the CONNECT BY is being done in a sub-query, there is no guarantee that the main query will preserve the hierarchical order that the sub-query provides.
    The query you posted doesn't require a suib-query, so you can say:
    SELECT     CONNECT_BY_ROOT b.parent_part                         AS part_nbr
    ,     b.parent_part
    ,     b.child_part
    --,     SYS_CONNECT_BY_PATH(b.line_nbr,' ')                    AS seq
    FROM     bill_test1 b
    WHERE          CONNECT_BY_ROOT b.parent_part     = 'ABC-1'
    CONNECT BY     parent_part     = PRIOR child_part
    ORDER SIBLINGS BY     b.line_nbr     
    ;I said the query you posted doesn't require a sub-query. It also doesn't require dual, so I suspect what you posted is a simplification of what you're really doing, and that may need a sub-query. In particular, if you intend to GROUP BY part_nbr, then you need the sub-query. We can repeat the CONNECT_BY_ROOT expression in the WHERE clause (or, now that I think about it, use a START WITH clause instead of WHERE), but, for some reason, we can't use CONNECT_BY_ROOT in a GROUP BY clause; we need to compute CONNECT_BY_ROOT in a sub-query, give it a name (like part_nbr), and GROUP BY that column in a super-query.
    This assumes that there is only one root node. ORDER SIBLINGS BY means just that: children of a common parent will appear in order, but the root nodes, who have no parents, will not necessarily be in order.
    Here's what I meant by using START WITH instead of WHERE:
    SELECT     CONNECT_BY_ROOT b.parent_part                         AS part_nbr
    ,     b.parent_part
    ,     b.child_part
    --,     SYS_CONNECT_BY_PATH(b.line_nbr,' ')                    AS seq
    FROM     bill_test1 b
    START WITH     b.parent_part     = 'ABC-1'
    CONNECT BY     parent_part     = PRIOR child_part
    ORDER SIBLINGS BY     b.line_nbr     
    ;This should be much more efficient, because it narrows down the results before you waste time getting their descendants.
    Using a START WITH clause here is analagous to me sending you an e-mail, saying "Come to a meeting a my office at 3:00."
    Using a WHERE clause here is analagous to me sending an e-mail to everyone in the company, saying "Come to a meeting a my office at 3:00", and then, as people get here, telling everyone except you that they can go back.
    ORDER SIBLINGS BY was introduced in Oracle 9.
    Edited by: Frank Kulash on Dec 9, 2010 2:39 PM
    Added version with START WITH clause

  • SQL Load ORDER BY clause

    Does anyone know how or where to enter the ORDER BY clause when using a SQL data source in a load rule? I would prefer to do the ordering in the load rule rather than creating a view on the DB side to do this if at all possible.
    According to the documentation "The SQL Statement box in the Open SQL Data Sources dialog box provides Select, From, and Where text boxes that help you write SQL queries. You can specify multiple data sources, filter the display of records, and specify how records displayed in Data Prep Editor are ordered and grouped." but I haven't found anywhere where you can order or group data. I don't need to be able group data I just want to be able to order my data to make the load process as efficient as possible.
    I do sort the data when inserting it into the load table but Oracle doesn't necessarily insert the records into the table based on their order when going in.
    We are currently on Essbase 11.1.1.3 and Oracle 11g.
    Any help is greatly apprecied.

    Well DUH! Everyone knows that! :-)
    Not sure why I never tried that, but it works. They need to update the documentation to say this, but we all know that will never happen.
    Thanks again!

  • Query taking 6mins to execute wityh order by clause, 3secs without orderby

    Dear All,
    The below query is taking nearly 6minutes time to execute (as i have order by clause in the query)
    /* Formatted on 2007/09/26 10:03 (Formatter Plus v4.8.0) */
    SELECT (SELECT DISTINCT grndate
    FROM fs_lg_grnhdr
    WHERE grnid = pl.grnid AND custwhid = pl.custwhid)
    grndate,
    pl.grnid,
    (SELECT DISTINCT vi.orderno
    FROM fs_lg_vendorinvoicehdr vi, fs_lg_grndtl gd
    WHERE gd.vendorinvoiceid = vi.vendorinvoiceid
    AND gd.custwhid = vi.custwhid
    AND gd.custwhid = pl.custwhid
    AND gd.grnid = pl.grnid
    AND gd.partid = pl.partid) orderno,
    pl.expirydate, pl.batchno, pl.packuom,
    NVL (pl.receiptqty, 0) receiptqty, pl.putawayid, pl.lineno,
    (SELECT customscontrolno
    FROM fs_lg_putawaydtl
    WHERE custwhid = pl.custwhid
    AND putawayid = pl.putawayid
    AND partid = pl.partid
    AND locationto = pl.locationid) cctrlno,
    (SELECT customspermitno
    FROM fs_lg_putawayhdr
    WHERE custwhid = pl.custwhid
    AND putawayid = pl.putawayid) cpermitno,
    (SELECT SUM (pdtl.pickqty)
    FROM fs_lg_pickticketdtl pdtl,
    fs_lg_picktickethdr phdr
    WHERE pdtl.custwhid = pl.custwhid
    AND pdtl.putawayid = pl.putawayid
    AND pdtl.putawaylineno = pl.lineno
    AND phdr.custwhid = pdtl.custwhid
    AND phdr.pickticketid = pdtl.pickticketid
    AND phdr.pickdate < '01-SEP-2007'
    AND pdtl.status = 'CM') previousoutqty,
    (SELECT SUM (pdtl.pickqty)
    FROM fs_lg_pickticketdtl pdtl,
    fs_lg_picktickethdr phdr
    WHERE pdtl.custwhid = pl.custwhid
    AND pdtl.putawayid = pl.putawayid
    AND pdtl.putawaylineno = pl.lineno
    AND phdr.custwhid = pdtl.custwhid
    AND phdr.pickticketid = pdtl.pickticketid
    AND phdr.pickdate BETWEEN '01-SEP-2007'
    AND '25-SEP-2007'
    AND pdtl.status = 'CM') presentoutqty,
    NVL ((SELECT SUM (qty)
    FROM fs_lg_internaltransdtl
    WHERE putawayid = pl.putawayid
    AND fromputawaylineno = pl.lineno
    AND custwhid = pl.custwhid),
    0
    ) toistqty,
    NVL ((SELECT SUM (qty)
    FROM fs_lg_internaltransdtl
    WHERE custwhid = pl.custwhid
    AND putawayid = pl.putawayid
    AND slno = pl.lineno),
    0
    ) fromistqty
    FROM fs_lg_partloads pl
    WHERE pl.partid = '2ERCH-2022'
    AND pl.custwhid = 'RNH-CSM'
    AND inventoryflag IN ('AVAIL','')
    AND pl.status = 'CM'
    AND pl.grndate <= '25-SEP-2007'
    ORDER BY grndate, pl.grnid, pl.putawayid, pl.lineno;
    But when i don't use the order by clause it is executing within 3 seconds. But i need to get the output in the sorted order as shown in the order by clause.
    Is there any way to avoid order by clause and to get the same output as with order by clasue, and i need to execute the query with less time.
    Please help me in this.
    Thanks in advance
    Mahi

    Dear Alok Kumar,
    When i execute sql>set autotrace traceonly statistics ;
    I am getting the below errors...
    SP2-0618: Cannot find the Session Identifier. Check PLUSTRACE role is enabled
    SP2-0611: Error enabling STATISTICS report
    What could be the problem, how to resolve this to get the statistics?
    But when i use sql>set autotrace traceonly explain; i got the below output for the above query..
    Execution Plan
    0 SELECT STATEMENT Optimizer=CHOOSE
    1 0 TABLE ACCESS (BY INDEX ROWID) OF 'FS_LG_GRNHDR'
    2 1 INDEX (UNIQUE SCAN) OF 'SYS_C00293078' (UNIQUE)
    3 0 SORT (UNIQUE)
    4 3 NESTED LOOPS
    5 4 TABLE ACCESS (BY INDEX ROWID) OF 'FS_LG_GRNDTL'
    6 5 INDEX (RANGE SCAN) OF 'SYS_C00293075' (UNIQUE)
    7 4 TABLE ACCESS (BY INDEX ROWID) OF 'FS_LG_VENDORINVOICEH
    DR'
    8 7 INDEX (UNIQUE SCAN) OF 'PK_VENDORINVOICE' (UNIQUE)
    9 0 TABLE ACCESS (BY INDEX ROWID) OF 'FS_LG_PUTAWAYDTL'
    10 9 INDEX (UNIQUE SCAN) OF 'SYS_C00293260' (UNIQUE)
    11 0 TABLE ACCESS (BY INDEX ROWID) OF 'FS_LG_PUTAWAYHDR'
    12 11 INDEX (UNIQUE SCAN) OF 'SYS_C00293263' (UNIQUE)
    13 0 SORT (AGGREGATE)
    14 13 NESTED LOOPS
    15 14 TABLE ACCESS (BY INDEX ROWID) OF 'FS_LG_PICKTICKETDTL'
    16 15 INDEX (RANGE SCAN) OF 'F_L_P_CWI_IND1' (NON-UNIQUE)
    17 14 TABLE ACCESS (BY INDEX ROWID) OF 'FS_LG_PICKTICKETHDR'
    18 17 INDEX (UNIQUE SCAN) OF 'SYS_C00293202' (UNIQUE)
    19 0 SORT (AGGREGATE)
    20 19 NESTED LOOPS
    21 20 TABLE ACCESS (BY INDEX ROWID) OF 'FS_LG_PICKTICKETDTL'
    22 21 INDEX (RANGE SCAN) OF 'F_L_P_CWI_IND1' (NON-UNIQUE)
    23 20 TABLE ACCESS (BY INDEX ROWID) OF 'FS_LG_PICKTICKETHDR'
    24 23 INDEX (UNIQUE SCAN) OF 'SYS_C00293202' (UNIQUE)
    25 0 SORT (AGGREGATE)
    26 25 TABLE ACCESS (BY INDEX ROWID) OF 'FS_LG_INTERNALTRANSDTL
    27 26 INDEX (RANGE SCAN) OF 'PK_INTERNALTRANSDTL' (UNIQUE)
    28 0 SORT (AGGREGATE)
    29 28 TABLE ACCESS (BY INDEX ROWID) OF 'FS_LG_INTERNALTRANSDTL
    30 29 INDEX (RANGE SCAN) OF 'PK_INTERNALTRANSDTL' (UNIQUE)
    31 0 SORT (ORDER BY)
    32 31 TABLE ACCESS (BY INDEX ROWID) OF 'FS_LG_PARTLOADS'
    33 32 INDEX (RANGE SCAN) OF 'PK_PARTLOADS' (UNIQUE)
    Please advice me regarding this...
    Thanks in advance
    Mahi

  • In Report,order by clause is not working

    Hi All,
    For the report i prepared the query in this one am using the order by clause,i run the query in the sql plus working fine am getting the data based on the order by clause.when i use the same query for the report am getting the data but not in the order(i.e order by clause in not working).
    Please help me how to do this one.
    Thanks in Advance.
    Regards,
    Leelakrishna.G

    Hi Dora,
    Data is coming in the proper sequence,but in the first group data is not coming(In first group data first line only displaying,remaining data is not comming).
    My req is:
    The report is executing based on the creation date(i.e.,from creation date to today).
    In this so many Purchase requisitions will be there for this one different approval in different times will be there.
    For Ex:
    we will take 2 PR number only(for the first one 3 approvals,second one 4 levels of approval).
    1. one supplier 1person raised by 1PR submit
    No Action
    Approve
    2. 2Supplier 2personraised by 2PR Submit
    NO Action
    Forword
    Approve
    with ur suggestion am trying data is gettin fine but first group first line is coming remaining data is not coing.
    EX:
    1. one supplier 1person raised by 1PR submit
    No Action
    Approve
    2PR Submit
    NO Action
    Forword
    Approve
    Note:"2. 2Supplier 2personraised by " this kind of lines data is missing.
    Can you pls check and suggest me how i can do this.
    Thanks in Advance.
    Regards,
    Leelakrishna.G

  • Order by clause with union

    Hi,
    I wanted to know if this is possible with order by clause and union. some how union messes up the ordering of the left part of the union statement.
    assume the data is as below in table tab1
    c1 c2
    4 1
    4 2
    5 1
    5 2
    7 1
    7 2
    8 3
    9 4
    the expected output must be for all c1 < 7 ordering must be on c1 and for all c1 > 7 ordering must be on c2.
    so the query i tried was
    select c1,c2 from tab1 where c1 <7 order by c1
    union
    select c1,c2 from tab1 where c1 >=7 order by c2
    it is giving the message 'Sql command not properly ended'.
    Suggestions are welcome

    SQL>
    SQL> With t As
      2  (
      3  Select 4 c1, 1 c2 From dual Union All
      4  Select 4 ,2       From dual Union All
      5  Select 5 ,1       From dual Union All
      6  Select 5 ,2       From dual Union All
      7  Select 7 ,1       From dual Union All
      8  Select 7 ,2       From dual Union All
      9  Select 8 ,3       From dual Union All
    10  Select 9 ,4       From dual
    11  ), t1 As (Select c1,c2 From t Where c1 <7 Order By c1)
    12  ,t2 As (select c1,c2 from t where c1 >=7 Order By c2)
    13  Select * From t1 Union All
    14  Select * From t2;
            C1         C2
             4          1
             4          2
             5          1
             5          2
             7          1
             7          2
             8          3
             9          4
    8 rows selected
    SQL> /*-- Union All
      2   select c1,c2 from t where c1 >=7
      3   Order By c1,c2;
      4  */
      5 
    with union clause order by must be placed in the end,,
    select c1 from dual union all
    select c2 from dual
    order by  c1

  • Order by clause in PL/SQL cursors

    I am trying to execute a procedure with some input parameters. I open a cursor
    with a select statement. However, the order by clause in the query does not
    recognize parameter sent through the procedure input parameters.
    For example:
    open <<cursor name>> for
    select id from member order by <<dynamic parameter>>" does not work (Compiles fine but does not return the right result).
    But if I try and give a static order by <<column name>> it works. Is the
    order by clause in the PL/SQL a compile time phenomenon?
    I have also tried it through dynamic sql. All the other parameters work except the order by <<parameter>> asc|desc
    Also "asc" and "desc" does not work if given dynamically.
    What alternatives do I have?
    null

    I don't think order by can be dynamic in a cursor, but it sure can be using dynamic sql. The only issue is that you must do a replace in the sql string with the dynamic variable. For example:
    create or replace procedure test_dyn(p_col in varchar2, p_order in varchar2) as
    q varchar2(500);
    u_exec_cur number;
    u_columnnumber NUMBER;
    u_columndate DATE;
    u_columnvarchar varchar2(50);
    u_cur_count number;
    u_ename varchar2(20);
    u_sal number;
    begin
    q := 'select ename, sal from scott.emp order by p_col p_order';
    -- got to do these two replaces
    q:= replace(q,'p_col',p_col);
    q:= replace(q,'p_order',p_order);
    u_exec_cur := dbms_sql.open_cursor;
    dbms_sql.parse(u_exec_cur,q,dbms_sql.v7);
    dbms_sql.define_column(u_exec_cur, 1, u_columnvarchar, 20);
    dbms_sql.define_column(u_exec_cur, 2, u_columnnumber);
    u_cur_count := dbms_sql.execute(u_exec_cur);
    loop
    exit when (dbms_sql.fetch_rows(u_exec_cur) <= 0);
    dbms_sql.column_value(u_exec_cur, 1, u_ename);
    dbms_sql.column_value(u_exec_cur, 2, u_sal);
    dbms_output.put_line(u_ename);
    dbms_output.put_line(u_sail);
    --htp.p(u_ename);
    --htp.p(u_sal);
    end loop;
    end;
    show errors;
    Now when when I execute my procedure I can change the order by clause all I want, for example:
    SQL> set serveroutput on;
    SQL> exec gmika.test_dyn('sal','asc');
    SMITH
    800
    ADAMS
    1100
    WARD
    1250
    MARTIN
    1250
    MILLER
    1300
    TURNER
    1500
    ALLEN
    1600
    JLO
    2222
    BLAKE
    2850
    JONES
    2975
    SCOTT
    3000
    FORD
    3000
    LOKITZ
    4500
    KING
    5000
    JAMES
    5151
    JAMES
    5555
    PL/SQL procedure successfully completed.
    SQL>
    null

  • Decode in order by clause

    Is it possible to use a decode function in the order by clause, when you have two select statements with a union between? I seem to be getting an error-message telling me to type a number.
    Can anybody help me?

    Tove,
    Is this what you mean?
    SQL> SELECT
      2  *
      3  FROM
      4  (SELECT
      5      empno     no
      6  ,   ename     name
      7  ,   job       description
      8  FROM          emp
      9  UNION
    10  SELECT
    11      deptno    no
    12  ,   dname     name
    13  ,   loc       description
    14  FROM          dept
    15  )
    16  ORDER BY
    17  DECODE(1
    18  ,      1,TO_CHAR(no)
    19  ,      2,name
    20  ,      3,description)
    21  /
            NO NAME           DESCRIPTION
            10 ACCOUNTING     NEW YORK
            20 RESEARCH       DALLAS
            30 SALES          CHICAGO
            40 OPERATIONS     BOSTON
          7369 SMITH          CLERK
          7499 ALLEN          SALESMAN
          7521 WARD           SALESMAN
          7566 JONES          MANAGER
          7654 MARTIN         SALESMAN
          7698 BLAKE          MANAGER
          7782 CLARK          MANAGER
          7788 SCOTT          ANALYST
          7839 KING           PRESIDENT
          7844 TURNER         SALESMAN
          7876 ADAMS          CLERK
          7900 JAMES          CLERK
          7902 FORD           ANALYST
          7934 MILLER         CLERK
    18 rows selected.Now, to order by the second column, I set the first parameter of the
    DECODE to "2":
    SQL> SELECT
      2  *
      3  FROM
      4  (SELECT
      5      empno     no
      6  ,   ename     name
      7  ,   job       description
      8  FROM          emp
      9  UNION
    10  SELECT
    11      deptno    no
    12  ,   dname     name
    13  ,   loc       description
    14  FROM          dept
    15  )
    16  ORDER BY
    17  DECODE(2
    18  ,      1,TO_CHAR(no)
    19  ,      2,name
    20  ,      3,description)
    21  /
            NO NAME           DESCRIPTION
            10 ACCOUNTING     NEW YORK
          7876 ADAMS          CLERK
          7499 ALLEN          SALESMAN
          7698 BLAKE          MANAGER
          7782 CLARK          MANAGER
          7902 FORD           ANALYST
          7900 JAMES          CLERK
          7566 JONES          MANAGER
          7839 KING           PRESIDENT
          7654 MARTIN         SALESMAN
          7934 MILLER         CLERK
            40 OPERATIONS     BOSTON
            20 RESEARCH       DALLAS
            30 SALES          CHICAGO
          7788 SCOTT          ANALYST
          7369 SMITH          CLERK
          7844 TURNER         SALESMAN
          7521 WARD           SALESMAN
    18 rows selected.
    SQL> SELECT
      2  *
      3  FROM
      4  (SELECT
      5      empno     no
      6  ,   ename     name
      7  ,   job       description
      8  FROM          emp
      9  UNION
    10  SELECT
    11      deptno    no
    12  ,   dname     name
    13  ,   loc       description
    14  FROM          dept
    15  )
    16  ORDER BY
    17  DECODE(3
    18  ,      1,TO_CHAR(no)
    19  ,      2,name
    20  ,      3,description)
    21  /
            NO NAME           DESCRIPTION
          7788 SCOTT          ANALYST
          7902 FORD           ANALYST
            40 OPERATIONS     BOSTON
            30 SALES          CHICAGO
          7369 SMITH          CLERK
          7934 MILLER         CLERK
          7900 JAMES          CLERK
          7876 ADAMS          CLERK
            20 RESEARCH       DALLAS
          7566 JONES          MANAGER
          7698 BLAKE          MANAGER
          7782 CLARK          MANAGER
            10 ACCOUNTING     NEW YORK
          7839 KING           PRESIDENT
          7499 ALLEN          SALESMAN
          7844 TURNER         SALESMAN
          7654 MARTIN         SALESMAN
          7521 WARD           SALESMAN
    18 rows selected.I needed to put the TO_CHAR in the DECODE so all of the columns
    by which I could potentially order are VARCHAR2's, else I was
    getting
    SQL> /
    DECODE(1
    ERROR at line 17:
    ORA-01785: ORDER BY item must be the number of a SELECT-list expressionHTH
    T.

  • Order By Clause - Slows performance

    On 10.2 when adding an order by clause to a query affects performance that returns 6 rows of data.
    Before:
    select distinct col1
    from table1
    Cost: 3,000
    Execution Time: less than a second
    Chooses: Bitmap Index Fast Full Scan Index (BitMap)
    After:
    select distinct col1
    from table1
    order by col1
    Cost: 14,000
    Execution time: 90 seconds
    Chooses: Full TableScan
    Any ideas as to why the order by causes the slow down ?
    Thanks,

    Venzi wrote:
    Now you add the order by clause to it and Oracle has now to do a sort on it. It can't sort on the BITMAP index in that case so it has to go to the table. It is possible for Oracle to do the order by through the bitmap index - the reason it doesn't is probably down to arithmetic. (The situation is made a little messier by the fact that the table and index have been parallel enabled). Here's a plan from 10.2.0.3 showing the "order by" query running through the bitmap index:
    | Id  | Operation                          | Name     | Rows  | Bytes | Cost  |    TQ  |IN-OUT| PQ Distrib |
    |   0 | SELECT STATEMENT                   |          |     6 |    18 |   356 |        |      |            |
    |   1 |  PX COORDINATOR                    |          |       |       |       |        |      |            |
    |   2 |   PX SEND QC (ORDER)               | :TQ10001 |     6 |    18 |   356 |  Q1,01 | P->S | QC (ORDER) |
    |   3 |    SORT GROUP BY                   |          |     6 |    18 |   356 |  Q1,01 | PCWP |            |
    |   4 |     PX RECEIVE                     |          |  2000K|  5859K|    63 |  Q1,01 | PCWP |            |
    |   5 |      PX SEND RANGE                 | :TQ10000 |  2000K|  5859K|    63 |  Q1,00 | P->P | RANGE      |
    |   6 |       PX BLOCK ITERATOR            |          |  2000K|  5859K|    63 |  Q1,00 | PCWC |            |
    |   7 |        BITMAP CONVERSION TO ROWIDS |          |  2000K|  5859K|    63 |  Q1,00 | PCWP |            |
    |   8 |         BITMAP INDEX FAST FULL SCAN| T1_B1    |       |       |       |  Q1,00 | PCWP |            |
    ------------------------------------------------------------------------------------------------------------Note how the optimizer can recognise that the "group by" operation will allow it to avoid an explicit "order by" operation, and uses the "(ORDER)" distribution to pass the data to the Query Coordinator to enforce correct ordering.
    Running up a test case with a couple of million rows, it looks like the underlying problem the OP has is that the CBO bypasses a few of the execution options in this particular case when parallel execution is possible. (I had to hint this plan - the default plan was a serial full scan of the index that allowed the optimizer to bypass the "sort order" because of a "sort unique", but the cost was much higher than this parallel plan - see below).
    | Id  | Operation               | Name  | Rows  | Bytes | Cost  |
    |   0 | SELECT STATEMENT        |       |     6 |    18 |  2269 |
    |   1 |  SORT UNIQUE NOSORT     |       |     6 |    18 |  2269 |
    |   2 |   BITMAP INDEX FULL SCAN| T1_B1 |  2000K|  5859K|   278 |
    -----------------------------------------------------------------Regards
    Jonathan Lewis
    http://jonathanlewis.wordpress.com
    http://www.jlcomp.demon.co.uk
    To post code, statspack/AWR report, execution plans or trace files, start and end the section with the tag {noformat}{noformat} (lowercase, curly brackets, no spaces) so that the text appears in fixed format.
    There is a +"Preview"+ tab at the top of the text entry panel. Use this to check what your message will look like before you post the message. If it looks a complete mess you're unlikely to get a response. (Click on the +"Plain text"+ tab if you want to edit the text to tidy it up.)
    +"I believe in evidence. I believe in observation, measurement, and reasoning, confirmed by independent observers. I'll believe anything, no matter how wild and ridiculous, if there is evidence for it. The wilder and more ridiculous something is, however, the firmer and more solid the evidence will have to be."+
    Isaac Asimov                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

Maybe you are looking for

  • MBP App Memory Clean showing a total of only 3.38GB RAM, although my MAC should have a total of 4?

    Hello all, Perhaps a question more for the tech-experts (I'm not one ) : I have been running the (well-known) App Memory Clean for a while, and have been quite satisfied with its "Auto-Clean" function, as it saves me up on the Disk swapping. However,

  • Afform with mixed readonly and updateable attributes

    Hi Everyone. I have an af:form in which I want to get the key attribute (EmpID) from the securityContext (based on the user login) and then based on the EmpID all other attributes of the VO should be populated in the form. Which is ok. But when I am

  • Have a look at this thread

    Hi all, Urgent - Issue -XI upgrade to NW2004s - PI 7.0 reg,

  • Rules inside email templates

    Has anyone tried calling a rule from inside an email template? It seems like everything has to be passed in from the workflow to the template. I'm wondering if I can call a rule from inside the template itself to get the data. Thanks!!

  • Trouble streaming videos on Amazon

    Why am I having so much trouble streaming instant videos on Amazon when I have the updated version of Adobe Flash Player as prompted by Amazon and my computer? It keeps starting and stopping and reloading and asking me to update my flash player.