Order by clause + Union

Hi ,
i want to use "union" to combine 2 query results and also i need to apply order by clause in both queries,how i can achieve this
i.e
i wrote query like
select item_id from item_mst
where item_id <5
order by item_no
union
select item_id from item_mst
where item_id <10
order by item_no
But it is giving ORA-00933 error.
Please help me to over come this error.
Thanks in advance

You cannot have an ORDER BY clause on each part of the union - there is only one ORDER BY allowed and that applies to the result of the union.
select item_id from item_mst
where item_id <5
union
select item_id from item_mst
where item_id <10
order by item_idI'm assuming you meant 'order by item_ID', not item_NO, since there is no item_NO column in the query.

Similar Messages

  • 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

  • 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

  • Using ORDER BY in UNION clause in cursor

    Hi Everybody,
    I have one situation and i need your help guys. I have to use ORDER BY in UNION of two queries and return value in cursor.
    OPEN cursor FOR
    SELECT ID, DESC,SID, ITID, SID_DESC
    FROM (SELECT A.ID,
    A.DESC,
    B.SID,
    NULL AS ITID,
    B.SID_DESC
    FROM TABLEA A, TABLEB B
    WHERE A.ID = B.ID
    order by A.SORTORDER asc,B.SORTORDER)
    UNION
    SELECT ID, DESC, ,SID,ITID, ITID_DESCRIPTION,
    FROM (SELECT A.ID,
    A.DESC,
    NULL AS SID,
    C.ITID,
    C.ITID_DESC,
    FROM TABLEA A,
    TABLEC C
    WHERE A.ID = C.ID
    order by A.SORTORDER asc,C.SORTORDER)
    I SORT ORDER is column in all three tables. TABLEA has unique number for each record as sort order. TABLEB has sortorder as 1 for each id. If id is two times then its 1 and 2 for each id. TABLEC has sort order as TABLEB, 1 for each id and if id is two times then it is 1 and 2 and id id is three times, it is 1, 2, 3.
    I am not getting correct sorting as i cant use order by like this in UNION. Please let me know how i can handle this.
    Thank you in advance to everybody.
    I will really appreciate your comments and responses.

    Hi,
    You can use ORDER BY in a sub-query, but there's usually no point in doing so, because the super-query won't necessarily preserve that order. You need to make the columns that you want to ORDER BY available to the main query, so that they can be used there.
    Try this:
    SELECT      ID, DESC,SID, ITID, SID_DESC
    FROM      (
             SELECT    A1.ID,
                        A1.DESC,
                    B.SID,
                    NULL          AS ITID,
                    B.SID_DESC,
                    A1.SORTORDER     AS sortorder_1
                    B.SORTORDER     AS sortorder_2
             FROM      TABLEA     A1,
                        TABLEB     B
             WHERE     A1.ID = B.ID
        UNION
             SELECT    A2.ID,
                        A2.DESC,
                    NULL          AS SID,
                           C.ITID,
                    C.ITID_DESC,
                    A2.SORTORDER     AS sortorder_1
                    B.SORTORDER     AS sortorder_2
             FROM      TABLEA          A2,
                        TABLEC         C
             WHERE     A2.ID = C.ID
    order by  SORTORDER_1     ASC     -- ASC is the default, but it doesn't hurt to say it
           SORTORDER_2This assumes that tableb.sortorder and tablec.sortorder have the same, or at least similar, data types. If not, explicitly convert sortorder_1 in one branch of the UNION to the type of sortorder_2 in the other branch.
    Using the same alias to mean different things in the same query is just asking for trouble. I changed the table alias a (which was used in different places to mean two different things) to A1 and A2, each of which means only one thing.
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all tables, and also post the results you want from that data.
    Explain, using specific examples, how you get those results from that data.
    Always say which version of Oracle you're using.

  • IN clause with ORDER BY clause in sub-queries

    Hello,
    We generate dynamic queries with the following statement pattern (could be many union/intersect sub-queries):
    select my_col
    from my_table
    where my_col IN
    select table_2.my_col , x_col from table_2 where x_col > 10
    UNION
    select table_3.my_col , y_col from table_3 where y_col > 20
    INTERSECT
    select table_4.my_col , z_col from table_4 where z_col is between 30 and 50
    I know that I can do just the sub-queries w/ an ORDER BY clause as follows (as long as the 2nd parameter in the select stmts are of the same type):
    select table_2.my_col , x_col from table_2 where x_col > 10
    UNION
    select table_3.my_col , y_col from table_3 where y_col > 20
    INTERSECT
    select table_4.my_col , z_col from table_4 where z_col is between 30 and 50
    order by 2 desc
    But my questions are:
    1. What is (if there is) the syntax that will ensure that the result set order will be that of the ordering of the sub-queries?
    Or does my SQL stmt have to have syntactically (but not semantically) change to achieve this?
    Thanks,
    Jim

    Randolf Geist wrote:
    just a minor doubt - I think it is not officially supported to have separate ORDER BYs in a compound query with set operators (e.g. UNION / UNION ALL subsets). Of course one could use inline views with NO_MERGE + NO_ELIMINATE_OBY hints, but I think the only officially supported approach is to use a single, final ORDER BY (that needs to use positional notation as far as I remember).
    Randolf,
    You're right, of course, about the separate "order by" clauses.
    Interestingly the following type of thing does work though (in 10.2.0.3, at least):
    with v1 as (
        select * from t1 where col1 = 'ABC' order by col2
    v2 as (
        select * from t1 where col1 = 'DEF' order by col2
    select * from v1
    union all
    select * from v2
    ;A quick check the execution plan suggsts that Oracle appears to be convering this to the following - even though its technically not acceptable in normal circumstances:
    select * from t1 where col1 = 'ABC' order by col2
    union all
    select * from t1 where col1 = 'DEF' order by col2
    ;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.
    "Science is more than a body of knowledge; it is a way of thinking"
    Carl Sagan                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Using Decode in Order By clause

    Hi all,
    I've a prblem with the DECODE in ORDER BY clause
    Could you please advise if I did something wrong with my sort order.
    Actually,I've a store procedure which gather all information from several tables and return with a resultset.
    Therefore I just post an example table_resultset instead of lenghthy StoreProc in forum
    /* table contain the column need to be sort on the resultset */
    create table table_sort (sortnum,sortname) as
    select 1553, 'IDNO' from dual union all
    select 1231, 'IDNAME' from dual union all
    select 1001, 'CREDATE' from dual;
    /* a sample of some information that resultset return by a storeproc */
    create table table_resultset (idno,idname,credate) as
    select 1111, 'SORT ORDER', sysdate-7 from dual union all
    select 54555, 'NEED A TEST CASE', sysdate+5 from dual union all
    select 10012, 'BEYOND THE LIMIT', sysdate from dual union all
    select 10522, 'CONCENTRATION', sysdate+20 from dual union all
    select 01231, 'A VALIDATION', sysdate-3 from dual;
    /* this select statement similar to execute a storeproc with s decode in the ORDER BY clause */
    select * from table_resultset
    order by decode((select ltrim(rtrim(sortname)) from table_sort where sortnum=1231),'IDNO',1,'IDNAME',2,3);
    OR
    select * from table_resultset
    order by case (select ltrim(rtrim(sortname)) from table_sort where sortnum=1231)
    when 'IDNO' then 1
    when 'IDNAME' then 2
    else 3
    end;
    Thanks.

    Thanks for the tip Samb ... :)
    I got it ... all sort field must be same datatype.
    SQL> create table table_sort (sortnum,sortname) as
    2 select 1553, 'IDNO' from dual union all
    3 select 1231, 'IDNAME' from dual union all
    4 select 1001, 'CREDATE' from dual;
    Table created.
    SQL> create table table_resultset (idno,idname,credate) as
    2 select 1111, 'SORT ORDER', sysdate-7 from dual union all
    3 select 54555, 'NEED A TEST CASE', sysdate+5 from dual union all
    4 select 10012, 'BEYOND THE LIMIT', sysdate from dual union all
    5 select 10522, 'CONCENTRATION', sysdate+20 from dual union all
    6 select 01231, 'A VALIDATION', sysdate-3 from dual;
    Table created.
    SQL> select * from table_resultset;
    IDNO IDNAME CREDATE
    1111 SORT ORDER 08-07-03
    54555 NEED A TEST CASE 08-07-15
    10012 BEYOND THE LIMIT 08-07-10
    10522 CONCENTRATION 08-07-30
    1231 A VALIDATION 08-07-07
    SQL> select * from table_sort;
    SORTNUM SORTNAM
    1553 IDNO
    1231 IDNAME
    1001 CREDATE
    if I want to sort the resultset by the column IDNAME of table_resultset then
    SQL> select * from table_resultset
    2 order by decode((select ltrim(rtrim(sortname)) from table_sort
    3 where sortnum=1231),'IDNO',to_char(idno),'IDNAME',idname,to_char(credate,'yyyymmdd'));
    IDNO IDNAME CREDATE
    1231 A VALIDATION 08-07-07
    10012 BEYOND THE LIMIT 08-07-10
    10522 CONCENTRATION 08-07-30
    54555 NEED A TEST CASE 08-07-15
    1111 SORT ORDER 08-07-03
    if I want to sort the resultset by the column CREDATE of table_resultset then
    SQL> select * from table_resultset
    2 order by decode((select ltrim(rtrim(sortname)) from table_sort
    3 where sortnum=1001),'IDNO',to_char(idno),'IDNAME',idname,to_char(credate,'yyyymmdd'));
    IDNO IDNAME CREDATE
    1111 SORT ORDER 08-07-03
    1231 A VALIDATION 08-07-07
    10012 BEYOND THE LIMIT 08-07-10
    54555 NEED A TEST CASE 08-07-15
    10522 CONCENTRATION 08-07-30
    But if I want to sort the resultset by the column IDNO of table_resultset then I've a problem due to the field converted into character, and the field IDNO define as number(9) of a table in production. therefore I've to find a solution when that field convert into character must be same length in order to sort IDNO correctly. As you can see from below
    SQL> select * from table_resultset
    2 order by decode((select ltrim(rtrim(sortname)) from table_sort
    3 where sortnum=1553),'IDNO',to_char(idno),'IDNAME',idname,to_char(credate,'yyyymmdd'));
    IDNO IDNAME CREDATE
    10012 BEYOND THE LIMIT 08-07-10
    10522 CONCENTRATION 08-07-30
    1111 SORT ORDER 08-07-03
    1231 A VALIDATION 08-07-07
    54555 NEED A TEST CASE 08-07-15
    your suggestion always welcome.
    Thanks,
    DT.

  • 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...

    Hi everyone,
    How can i achieve this with order by clause
    If i have the following data in my table. I need one record (which has the data 'Last record')
    to be the last record for my select statement, and order the other records according to "no"
    whatever data i have i need to arrange that record last
    select * from
    select 'A' order_by_test,5 no  from dual
    union all
    select 'B' order_by_test,1 no from dual
    union all
    select 'C' order_by_test,8 no from dual
    union all
    select 'Last record' order_by_test,3 no from dual
    union all
    select 'Z' order_by_test,7 no from dual
    union all
    select null order_by_test,null no from dual
    union all
    select '  ' order_by_test,null no from dual
    output:
    =======
    order_by_test     no
        B             1         -->other records ,order by no nulls last
        A             5
        Z             7
        C             8
       null           null
      '  '            null
      Last record     3      ----> everytime this should be the last record of my select statement,I am sorry if it is a dumb question to ask.
    Thanks in advance

    Hi,
    Use CASE (or equivalents) to map your values into sortable values.
    ORDER BY  CASE
                     WHEN  order_by_test = 'Last record'
               THEN  2
               ELSE  1
                 END
    ,       noIf the sort order depends on two different columns, it's often best to have two different expressions in the ORDER BY clause.
    SET     NULL     [NULL]
    select * from
    select 'A' order_by_test,5 no  from dual
    union all
    select 'B' order_by_test,1 no from dual
    union all
    select 'C' order_by_test,8 no from dual
    union all
    select 'Last record' order_by_test,3 no from dual
    union all
    select 'Z' order_by_test,7 no from dual
    union all
    select null order_by_test,null no from dual
    union all
    select '  ' order_by_test,null no from dual
    ORDER BY  CASE
                     WHEN  order_by_test = 'Last record'
               THEN  2
               ELSE  1
                 END
    ,       no
    ORDER_BY_TE         NO
    B                    1
    A                    5
    Z                    7
    C                    8
                [NULL]
    [NULL]      [NULL]
    Last record          3Edited by: Frank Kulash on Mar 31, 2010 1:20 PM
    Added full query and output

  • Using order by in Union ALL

    hi Following is my query and am unable to accomplish my order by statement in Union All . please help me in this.
    <code>
    SELECT b.audit_trail_id,
    TO_CHAR (b.last_update_date, 'DD-Mon-YYYY') "Revision Date",
    (u.last_name || ', ' || u.first_name || ' ' || u.mi) "By",
    b.col_name "Field",
    b.new_value "New Value",b.previous_value "Old Value",
    a.lot_id,
    b.comment_text "Comments"
    FROM clem_audit_trail b,lot a, users u
    WHERE a.lot_id = b.lot_id(+)
    AND u.user_id(+) = b.last_update_user_id
    AND a.lot_id in (select lot_id from request_lot where request_id = 51914)
    AND col_name IN
    ('Interim Release Date',
    'Final Disposition Date',
    'On Time Disposition',
    'Intended Use',
    'REJECTS_YN',
    '# of QARs',
    '# of Quality Events',
    '# of LIRs',
    '# of Change Controls',
    '# of Batch Records',
    '# of GMP Batch Records',
    'EXPLANATION',
    'QA Notes',
    'GDMS_LINK')
    AND UPPER (table_name) IN('LOT') order by b.last_update_date
    UNION ALL
    SELECT b.audit_trail_id,
    TO_CHAR (b.last_update_date, 'DD-Mon-YYYY') "Revision Date",
    (u.last_name || ', ' || u.first_name || ' ' || u.mi) "By",
    b.col_name "Field",
    b.new_value "New Value",b.previous_value "Old Value",
    r.request_id,
    b.comment_text "Comments"
    FROM clem b,request r, users u
    WHERE r.request_id = b.request_id(+)
    AND u.user_id(+) = b.last_update_user_id
    AND r.request_id = 51914
    AND UPPER (table_name) IN ('REQUEST') AND
    b.col_name IN ('Partial Release',
    'All QP Docs in GDMS',
    'Number of Batch Records',
    'Request',
    'QP Issues',
    'Snag Comments',
    'Responsible Group',
    'Reason Late',
    'Study Impact',
    'Other Details',
    'Request Status',
    'QP Link to GDMS'
    ) order by b.last_update_date
    </code>
    If i execute individually it works fine, if i use union all it throughs error for me.
    Any suggestion...

    Hi,
    In a set operation (such as UNION) table aliases (such as b.) only have meaning within the branch in which they are defined. The ORDER BY clause is not part of any 1 branch, so a table alias can't be used there.
    In most cases, you can use a column name (or alias) from the first branch, like this:
    SELECT    b.audit_trail_id,
              TO_CHAR (b.last_update_date, 'DD-Mon-YYYY') "Revision Date",
    order by  "Revision Date"
    ;and you can always order by column number, like this:
    SELECT    b.audit_trail_id,
              TO_CHAR (b.last_update_date, 'DD-Mon-YYYY') "Revision Date",
    order by  2
    ;In this case, however, there's an extra problem. You're transforming the DATE to a string in the SELECT clause. The string is all that's available in the ORDER BY clause, and the string '19-NOV-2012' comes after the string '01-JAN-2015', because the character '1' comes after '0'. Perhaps the simplest solution is to have your front end, and not the query, format the dates. In SQL*Plus, you can do this:
    ALTER SESSION  SET NLS_DATE_FORMAT = 'DD-MON-YYYY';
    SELECT    b.audit_trail_id,
              b.last_update_date    AS "Revision Date",
    order by  2
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all the tables involved, and the results you want from that data.
    Explain, using specific examples, how you get those results from that data.
    Always say what version of Oracle you're using (e.g. 11.2.0.2.0).
    See the forum FAQ {message:id=9360002}

  • Doubt regarding multiple criteria in order by clause

    Hi, I don't understand the effect of multiple elements inside the order by clause. I have the following example table:
    factor_x | factor_y | price
    =====================
    1 | 5 | 1000
    2 | 4 | 6970
    3 | 3 | 3688
    4 | 2 | 9087
    5 | 1 | 10000
    =====================
    So I tried: select price from pricetable order by factor_x; results as follows:
    1000
    6970
    3688
    9087
    10000
    Then: select price from pricetable order by factor_y; results as follows:
    10000
    9087
    3688
    6970
    1000
    Then: select price from pricetable order by factor_x, factor_y; results as follows:
    1000
    6970
    3688
    9087
    10000
    which is same as using order by factor_x. Can anyone tells me what is the effect of adding a 2nd, 3rd..... criterion in the order by clause? Because in this example I cannot see the difference. Many thanks.

    Hi,
    I did a little change in your data. Hope it will help you to understand.
    SQL> WITH T AS (SELECT 1 X , 1 Y , 1000 PRICE FROM DUAL UNION A
      2  SELECT 2 , 4 , 6970 FROM DUAL UNION ALL
      3  SELECT 4 , 3 , 3688 FROM DUAL UNION ALL
      4  SELECT 4 , 2 , 9087 FROM DUAL UNION ALL
      5  SELECT 4 , 5 , 10000 FROM DUAL)
      6  SELECT PRICE,X,Y FROM T ORDER BY X;
         PRICE          X          Y
          1000          1          1
          6970          2          4
          9087          4          2
         10000          4          5
          3688          4          3
    SQL> WITH T AS (SELECT 1 X , 1 Y , 1000 PRICE FROM DUAL UNION A
      2  SELECT 2 , 4 , 6970 FROM DUAL UNION ALL
      3  SELECT 4 , 3 , 3688 FROM DUAL UNION ALL
      4  SELECT 4 , 2 , 9087 FROM DUAL UNION ALL
      5  SELECT 4 , 5 , 10000 FROM DUAL)
      6  SELECT PRICE,X,Y FROM T ORDER BY X,Y;
         PRICE          X          Y
          1000          1          1
          6970          2          4
    9087 4 2
    3688 4 3
    10000 4 5
    SQL>Regards
    Avinash

  • Writing order by clause with user parameter

    I have a user parameter where the user is supposed to choose what column they want to sort by.
    And they can choose between k.personnr and k.personnavn. I am trying to do this with a decode function.
    Now this would work fine if there was no union between these select statements.
    But with the union I get a ORA-01785, where they tell me to put in a number.
    Here is the sql:
    SELECT
    k.personnr as PERSON ,
    k.personnavn as NAVN,
    r.belop as SUM,
    concat(to_char(r.bilagdato,'MM'), to_char(r.bilagdato,'YYYY')) AS MND,
    PERIODE(concat(to_char(r.bilagdato,'MM'), to_char(r.bilagdato,'YYYY'))) AS PERIODE
    FROM
    reskontro r,
    klient k,
    kontoplan p,
    konto c
    WHERE
    r.distriktnr='21'
    and r.distriktnr=c.kontoid
    and r.distriktnr=k.distriktnr
    and r.personnr=k.personnr
    and r.kontonr=p.kontonr
    and (((r.bilagdato between :p_fra_dato and :p_til_dato) and (:p_fra_dato <= c.overfort) and (:p_til_dato <= c.overfort))
    or ((r.bilagdato between :p_fra_dato and c.overfort) and (:p_fra_dato <= c.overfort) and (:p_til_dato >= c.overfort)))
    UNION ALL
    SELECT
    k.personnr as PERSON ,
    k.personnavn as NAVN,
    (t.belop/100) as SUM,
    concat(to_char(t.bilagdato,'MM'), to_char(t.bilagdato,'YYYY')) AS MND,
    PERIODE(concat(to_char(t.bilagdato,'MM'), to_char(t.bilagdato,'YYYY')),:P_HORISONTAL) AS PERIODE
    FROM
    transaksjon t,
    klient k,
    kontoplan p
    WHERE
    t.distriktnr='21'
    and t.distriktnr=k.distriktnr
    and t.personnr=k.personnr
    and t.kontonr=p.kontonr
    and t.bilagdato between :p_fra_dato and :p_til_dato
    This is the order by clause I would like to use:
    order by decode(:p_order_by,'Personnavn',k.personnavn,k.personnr)
    I also get an error when I use:
    order by decode(:p_order_by,'Personnavn',2,1)
    Can anybody tell me how to work around this problem?

    Hi,
    One way you can do to get around this problem could be :
    select * from (
    SELECT
    k.personnr as PERSON ,
    k.personnavn as NAVN,
    r.belop as SUM,
    concat(to_char(r.bilagdato,'MM'), to_char(r.bilagdato,'YYYY')) AS MND,
    PERIODE(concat(to_char(r.bilagdato,'MM'), to_char(r.bilagdato,'YYYY'))) AS PERIODE
    FROM
    reskontro r,
    klient k,
    kontoplan p,
    konto c
    WHERE
    r.distriktnr='21'
    and r.distriktnr=c.kontoid
    and r.distriktnr=k.distriktnr
    and r.personnr=k.personnr
    and r.kontonr=p.kontonr
    and (((r.bilagdato between :p_fra_dato and :p_til_dato) and (:p_fra_dato <= c.overfort) and (:p_til_dato <= c.overfort))
    or ((r.bilagdato between :p_fra_dato and c.overfort) and (:p_fra_dato <= c.overfort) and (:p_til_dato >= c.overfort)))
    UNION ALL
    SELECT
    k.personnr as PERSON ,
    k.personnavn as NAVN,
    (t.belop/100) as SUM,
    concat(to_char(t.bilagdato,'MM'), to_char(t.bilagdato,'YYYY')) AS MND,
    PERIODE(concat(to_char(t.bilagdato,'MM'), to_char(t.bilagdato,'YYYY')),:P_HORISONTAL) AS PERIODE
    FROM
    transaksjon t,
    klient k,
    kontoplan p
    WHERE
    t.distriktnr='21'
    and t.distriktnr=k.distriktnr
    and t.personnr=k.personnr
    and t.kontonr=p.kontonr
    and t.bilagdato between :p_fra_dato and :p_til_dato)
    order by decode(:p_order_by,'Personnavn', NAVN, PERSON)
    /Uffe

  • Order by clause need more tuning

    i have a report with a query having 2 more union all queries
    i give an order by clause on the column no. 3 i.e. order by 3,the order by column is a varchar2 column having the data in this format 05-06/1,05-06/10,,now the problem is the order in which data is displayed is
    05-06/1
    05-06/10
    05-06/100
    05-06/101
    05-06/199
    05-06/2
    05-06/20
    05-06/21
    i hope u understood the problem,,i want this to be displayed serially,,not happening,,help me

    select c1
    from
    select '05-06/1' c1 from dual
    union
    select '05-06/10' from dual
    union
    select '05-06/100' from dual
    union
    select '05-06/7' from dual
    union
    select '05-06/220' from dual
    order by substr(c1,1,instr(c1,'/'))||lpad(substr(c1,instr(c1,'/')+1),10,'0')

  • Order by clause not working

    Hi, everyone,
    I am trying to use the following insert statement to insert records in asc order. if i use the select statement alone the order by clause works fine, but when i use the same sql and add a insert into table statment the order by clause does not work. I am not getting the records in ascending order. could anybody help me in this regard?
    INSERT INTO cat_sales_stg
    select      b.SSC,                
         ltrim(rtrim(a.CAT_DESC)) cat_desc,                
         SUM(a.AMOUNT) AMOUNT               
    FROM Trans a, SSC b                     
    WHERE a.ACCOUNT_NUMBER = TO_CHAR(b.ACCOUNT_NUMBER)                    
         AND a.TMONTH >= 200905 AND a.TMONTH <= 200910                
         AND a.FORMAT_NAME = 'ABC'                
         AND b.BMONTH = 200910                
         AND b.SAMPLE = 3                
         AND b.BANNER_NAME = 'ABC'               
         AND b.MODEL_NAME = 'XYZ'               
    group by b.SSC, ltrim(rtrim(a.CAT_DESC))
    order by ssc,cat_desc
    Thanks in advance

    user10636796 wrote:
    Hi, everyone,
    I am trying to use the following insert statement to insert records in asc orderWhat Toon, William, and others have said is that you DON'T insert rows in a specific order. That is completely outside the way relational databases are designed. You insert rows as unordered and use an ORDER BY clause in a SELECT when reading them. ORDER BY is for SELECT statements, not INSERT.
    In particular Toon poined out that we can't control where individual rows get stored.
    There is a databas object called a varray that can store data in sorted order. I have never seen them used because selecting the data back out again is more work; using an ordinary table and an ORDER BY clause is much easier.

  • 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/

  • How to make an ORDER BY clause dynamic

    is there anyway to make the ORDER BY clause in an SQL query within a DB control
    dynamic? I have tried to pass a String of the column name and place it in the
    statement within {}, but it doesn't work

    "Mark" <[email protected]> wrote:
    >
    is there anyway to make the ORDER BY clause in an SQL query within a
    DB control
    dynamic? I have tried to pass a String of the column name and place
    it in the
    statement within {}, but it doesn't workDid you find how ? please let me know, I also need to have a dynamic order by
    clause.

Maybe you are looking for

  • New Mac User Facing Sudden System Slowdowns - Advice Appreciated

    I recently purchased a MacPro for video editing, switching from Premiere on my PC. Everything was working great for the past month, and now suddenly I've been having terrible slowdowns in Final Cut Pro. Shortly after these slowdowns occured (constant

  • Manual Bank Reconciliation Statement - Processing Batch Input Session

    Hi experts, After processing FF67 transaction, while processing batch input session, system expecting manual clearing of open items in bank sub accounts.  If I manually clear, then only it is processing further till end of all transactions in batch i

  • EBS R12 jtffmctl.txt error while starting Apps services

         My Apps log-in page shows: Error page: you have encountered an unexpected error. Please contact the System Administrator for assistance. and displays Logout at the top right hand corner of the screen. my jtffmctl.txt shows the following exceptio

  • TransactionStateChanged gives wrong value when validation error.

    In my navbar, wich extends the standard one I extended the transactionStateChanged method. It seems to work and when the transaction goes dirty I receive a true state; when transaction returns clean I receive false. However if a validation fails duri

  • Rhythmbox 0.8.8 problem

    hi, Since last upgrade I haven't been able to add new music or internet radio stations to Rhythmbox. Also my entire music library is lost. The files are still there but Rhythmbox can't find them.. Any ideas how to correct it? .murkus EDIT: I suspect