CASE in an order by clause?

Can I use a case statement in an order by clause to acheive the following?
I have set up a parameter (:p_order) and placed it in a case statement in my order by clause. The idea is that the user will select a value from a LoV in the report and then dependant upon which one they picked, it will order by their selection. The problem I'm hitting is that the CASE statement seems to want to return an actual value instead of just returning the alias name to complete the order by clause. Here is the syntax I'm using:
ORDER BY
CASE WHEN :p_order = 'INVOICE NUMBER' THEN INVOICE_NUMBER
WHEN :p_order = 'INVOICE DATE' THEN INVOICE_DATE
     WHEN :p_order = 'VENDOR' THEN VENDOR_NAME
WHEN :p_order = 'CHECK NUMBER' THEN CHECK_NUMBER
WHEN :p_order = 'CHECK DATE' THEN CHECK_DATE
WHEN :p_order = 'CHECK AMOUNT' THEN CHECK_AMOUNT
WHEN :p_order = 'DOA CHECK NUMBER' THEN DOA_CHECK_NUMBER
WHEN :p_order = 'DOA CHECK DATE' THEN DOA_CHECK_DATE
WHEN :p_order = 'DOA CHECK AMOUNT' THEN DOA_CHECK_AMOUNT
END
Any ideas? How can I force the case statement to return the alias name instead of a value or is that defiance in the face of what case is? Thanks!
Steve

Note, however, that if you want to dynamically choose the ORDER, you have to use dynamic SQL, not static SQL.
Justin
Distributed Database Consulting, Inc.
http://www.ddbcinc.com/askDDBC

Similar Messages

  • Case statement in order by clause

    Hi,
    I have written the below query which is having CASE statement in ORDER BY clause. Please let me know what mistake i have done in the query because am getting "Missing Keyword" Error.
    SELECT opn_quest_id, seq_nbr
    FROM opinion_question
    order by case when :p=1 then
    opn_quest_id,seq_nbr
    else
    opn_quest_id
    end;
    Thanks,
    Santhosh.S

    Try Ignore the following solution.
    SELECT   opn_quest_id, seq_nbr
    FROM   opinion_question
    ORDER BY   CASE
    WHEN : p = 1 THEN opn_quest_id || seq_nbr
    ELSE opn_quest_id
    END;
    What are the data type of the corresponding columns used in the CASE Statement? I have assumed it to be strings.
    !http://www.mysmiley.net/imgs/smile/sad/sad0049.gif! My Apologies....
    Regards,
    Jo
    Edited by: Joice John on Jul 13, 2009 3:07 AM
    Wrong Solution. Corrected by Sven.

  • Dual Case Column names fail in select ORDER BY clause

    This one is solved, but I thought someone might be able to explain why it happens.
    I'm a newbie, since I just downloaded Oracel XE last night, and am trying it out.
    I set up a trivial table with 4 text columns. As it happened, I used dual case for some of my column names, such as 'Nickname'.
    When trying out the Query Builder, the Select statement failed whenever I added a sort.
    After some head scratching and back-and-forth with the sample data base (HR), I finally renamed all the columns to upper case. (e.g. column 'Nickname' became 'NICKNAME'). Then it works.
    Seems like a bug, but maybe it's just a feature. Here's the code generated by the Query Builder. As you can see, there are no quotes around the Table name or column names in the ORDER BY clause (and the dual case version of the column name works if I put the quotes in manually and run it with SQL command.) Seems quirky.
    select     "TEAMS"."NICKNAME" as "NICKNAME",
         "TEAMS"."CITY" as "CITY",
         "TEAMS"."DIVISION" as "DIVISION",
         "TEAMS"."CONFERENCE" as "CONFERENCE"
    from     "TEAMS" "TEAMS"
    order by TEAMS.NICKNAME ASC

    Welcome to forum. :)
    Now, answering your question - no i don't think this is a bug.
    It is your code - which create this bug.
    Now, question is - what happen?
    Just check your select and from clause. You put all the names are in double quote. When you put anything within double quotes - it become a case sensitive. So, the problem occurs there.
    Let's see ->
    satyaki>
    satyaki>select * from v$version;
    BANNER
    Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - Prod
    PL/SQL Release 10.2.0.3.0 - Production
    CORE    10.2.0.3.0      Production
    TNS for 32-bit Windows: Version 10.2.0.3.0 - Production
    NLSRTL Version 10.2.0.3.0 - Production
    Elapsed: 00:00:01.11
    satyaki>
    satyaki>create table s_otn
      2      (
      3        id    number(4)
      4      );
    Table created.
    Elapsed: 00:00:02.14
    satyaki>
    satyaki>set lin 80
    satyaki>
    satyaki>desc s_otn;
    Name                                      Null?    Type
    ID                                                 NUMBER(4)
    satyaki>
    satyaki>desc S_OTN;
    Name                                      Null?    Type
    ID                                                 NUMBER(4)
    satyaki>
    satyaki>desc s_OtN;
    Name                                      Null?    Type
    ID                                                 NUMBER(4)
    satyaki>
    satyaki>drop table s_otn;
    Table dropped.
    Elapsed: 00:00:05.22
    satyaki>
    satyaki>
    satyaki>create table "S_otn"  
      2       (
      3         id     number(4)
      4       );
    Table created.
    Elapsed: 00:00:00.12
    satyaki>
    satyaki>
    satyaki>desc S_otn;
    ERROR:
    ORA-04043: object S_otn does not exist
    satyaki>
    satyaki>desc S_OTN;
    ERROR:
    ORA-04043: object S_OTN does not exist
    satyaki>
    satyaki>desc s_otn;
    ERROR:
    ORA-04043: object s_otn does not exist
    satyaki>
    satyaki>desc "S_OTN";
    ERROR:
    ORA-04043: object "S_OTN" does not exist
    satyaki>
    satyaki>desc "S_otn";
    Name                                      Null?    Type
    ID                                                 NUMBER(4)
    satyaki>Got me?
    Regards.
    Satyaki De.

  • 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
         );

  • ORDER BY Clause in XMLAGG is throwing errors.

    Hi,
    I'm getting errors when generating the XML using the ORDER BY clause in the XMLAgg function. Although, running the SQL directly in SQL Plus doesn't have any problem.
    Here is the PL/SQL sample.
    DECLARE
    vX_XML SYS.XMLTYPE;
    vCL_XML CLOB;
    BEGIN
    SELECT XMLElement("GROUP",
    XMLAttributes(Group_Id AS "ID", Group_Name AS "NAME", Group_Description AS "DESC"),
    XMLAgg(XMLElement("FIELD",
    XMLAttributes(Field_Id AS "ID", Field_Description AS "DESC",
    Table_Name AS "TAB_NM", Rule_Name AS "RULE_NM",
    Field_Hierarchy_Depth AS "DOL_VAR_CALC")) ORDER BY Field_Description))
    INTO vX_XML
    FROM (SELECT g.Group_Id, g.Group_Name, g.Group_Description, f.Field_Id, f.Field_Description,
    DECODE(f.Table_Name, 'ESTIMATES', 'E', 'LINE_ITEMS', 'L', NULL) Table_Name,
    rt.Rule_Name,
    CASE NVL(f.Field_Hierarchy_Depth, 0) WHEN 0 THEN 'N' ELSE 'Y' END Field_Hierarchy_Depth
    FROM GROUPS g,
    Rules r,
    Rule_Types rt,
    Fields f
    WHERE g.Group_Id = 3087
    AND r.Group_Id_Fk = g.Group_Id
    AND rt.Rule_Type_Id = r.Rule_Type_Id_Fk
    AND f.Field_Id = r.Field_Id_Fk) tab
    GROUP BY Group_Id, Group_Name, Group_Description;
    vCL_XML := vX_XML.GetCLOBVal();
    END;
    And, here are the errors.
    ERROR at line 8:
    ORA-06550: line 8, column 23:
    PLS-00306: wrong number or types of arguments in call to 'XMLAGG'
    ORA-06550: line 8, column 23:
    PL/SQL: ORA-00904: "XMLAGG": invalid identifier
    ORA-06550: line 6, column 5:
    PL/SQL: SQL Statement ignored
    Thanks in Advance.
    BTW, we are using Oracle 9.2.0.4.

    This is bug 2785463 with no ETA for a fix
    regards
    Coby D. Adams Jr.

  • Why I cannot use RowID in where clause but can use it in order by clause

    I am on SQL Server 2008.
    1. If I use
    SELECT (ROW_NUMBER()  over
    (order by ImportId, ScenarioId, SiteID, AssetID, LocalSKUID, WEEKID, MonthID)) RowID, * 
      FROM [JnJ_Version1].[dbo].[td_Production_Week]
      order by RowID
    Statement works
    But
    2. If I use
    SELECT (ROW_NUMBER()  over
    (order by ImportId, ScenarioId, SiteID, AssetID, LocalSKUID, WEEKID, MonthID)) RowID, * 
      FROM [JnJ_Version1].[dbo].[td_Production_Week]
      where  RowID > 10000
    I get error, RowID is an invalid column Name why? How to correct query 2.

    This is due to the logical evaluation order of a SELECT statement. Logically, a SELECT statement is computed in the order:
    FROM (which includes JOIN)
    WHERE
    GROUP BY
    HAVING
    SELECT
    ORDER BY
    OFFSET
    Thus, you can use what is defined in the SELECT list in the ORDER BY clause, but not in the WHERE clause.
    In the case of row_number(), this has immediate repurcussions. row_number() is computed from the rows as they arrive the SELECT clause, and if you then you would filter on the value in the WHERE clause you would be going round in circles.
    To do what you are looking for, you use a nested table, for instance with a CTE:
    WITH numbering AS (
       SELECT (ROW_NUMBER()  over
    (order by ImportId, ScenarioId, SiteID, AssetID, LocalSKUID, WEEKID, MonthID)) RowID, * 
      FROM [JnJ_Version1].[dbo].[td_Production_Week]
    SELECT *
    FROM   numbering
    WHERE  RowID > 10000
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Slow SQL output when table alias is NOT used in order by clause

    Hi guys,
    My query is based on Oracle 9208
    I have a table TAB1 with 68000 records with transaction_id as the primary key in this table (unique index).
    I have another TAB2 with the same number of records again with transaction_id in this table (foreign key to above).
    I have the below query that gets executed via an application:-
    SELECT TO_CHAR(V1.TRANSACTION_ID), V1.POLICY_ID, V1.REQUEST_TYPE
    FROM <VIEW> V1 WHERE V1.CERT_SERIAL_NUM=56192 AND
    (V1.AUTH_GROUP_ID=0 OR V1.AUTH_GROUP_ID=1) AND ROWNUM <= 3 ORDER
    BY TRANSACTION_ID ASC
    The above view V1 is created as below:-
    CREATE OR REPLACE FORCE VIEW "V1"
    ("TRANSACTION_ID",
    "PARENT_TRANSACTION_ID",
    "CA_DN_ID",
    "AUTH_GROUP_ID",
    "POLICY_ID",
    "REQUEST_TYPE",
    "REQUEST_STATUS",
    "EE_DN_HASH",
    "EE_DN",
    "EE_EMAIL_HASH",
    "EE_EMAIL",
    "KEY_USAGE",
    "SMART_CARD_SERIAL",
    "CERT_TYPE",
    "CERT_SERIAL_NUM",
    "CERT_INDEX",
    "RENEWAL_FLAG",
    "ARCHIVE_FLAG",
    "TIME_RECEIVED",
    "DOWNLOADED",
    "REQUEST_DATA",
    "ACTION",
    "STEP_NUM")
    AS
    SELECT
    T1.transaction_id,
    T1.parent_transaction_id,
    T1.ca_dn_id,
    V2.auth_group_id,
    V2.policy_id,
    T1.request_type,
    T1.request_status,
    T2.ee_dn_hash,
    T2.ee_dn,
    T2.ee_email_hash,
    T2.ee_email,
    T2.key_usage,
    T2.smart_card_serial,
    T2.cert_type,
    T2.cert_serial_num,
    T2.cert_index,
    T2.renewal_flag,
    T2.archive_flag,
    T1.time_received,
    T1.downloaded,
    T1.request_data,
    V2.action,
    V2.step_num
    FROM TAB1
    <ANOTHER VIEW> V2,
    TAB2 T1,
    TAB2 T2
    WHERE
    T1.transaction_id = T2.transaction_id
    AND
    V2.policy_id = T1.policy_id
    order by transaction_id;
    The query at the top runs within milliseconds if the VIEW is created as :-
    order by t2.transaction_id
    But without the alias "t2" in the order by, the query takes about 1 1/2 minutes
    Can you tell me why? I thought if you ordering by primary key (lesser number of values compared to foreign key values), the query should be faster..no?
    Thanks in advance

    Thanks for keeping up with this issue Hemant.
    Here are the plans for each case.
    I would be very interested in how you'd recognize which plan is the best and what are the derivatives.
    I don't much (or rather anything!) what is 'card' values, 'cost' values etc which I believe are used to decide the best plan of the lot.
    Thanks again
    Note TAB1 and TAB2 are from view definition posted initially
    1) Execution Plan for VIEW1 <<-- With ORDER BY" clause but no table ailas (order by transaction_id)
    SQL> EXPLAIN PLAN FOR SELECT TO_CHAR(QT.TRANSACTION_ID), QT.POLICY_ID, QT.REQUEST_TYPE
    2 FROM <VIEW1> QT WHERE QT.CERT_SERIAL_NUM=24293 AND
    3 (QT.AUTH_GROUP_ID=0 OR QT.AUTH_GROUP_ID=1) AND ROWNUM <= 3 ORDER
    4 BY TRANSACTION_ID ASC
    5 /
    Explained.
    Elapsed: 00:00:01.00
    SQL> select * from table(dbms_xplan.display);
    PLAN_TABLE_OUTPUT
    | Id | Operation | Name | Rows | Bytes | Cost |
    | 0 | SELECT STATEMENT | | 3 | 195 | 17 |
    |* 1 | COUNT STOPKEY | | | | |
    | 2 | VIEW | VIEW1 | 17 | 1105 | 17 |
    |* 3 | SORT ORDER BY STOPKEY | | 17 | 38573 | 17 |
    | 4 | NESTED LOOPS | | 17 | 38573 | 10 |
    | 5 | MERGE JOIN CARTESIAN | | 1 | 167 | 9 |
    | 6 | VIEW | VIEW2 | 1 | 52 | 8 |
    | 7 | SORT UNIQUE | | 1 | 156 | 8 |
    | 8 | NESTED LOOPS | | 1 | 156 | 6 |
    | 9 | NESTED LOOPS | | 1 | 143 | 6 |
    | 10 | NESTED LOOPS OUTER | | 1 | 117 | 5 |
    |* 11 | HASH JOIN | | 1 | 104 | 5 |
    | 12 | NESTED LOOPS | | 1 | 52 | 2 |
    |* 13 | TABLE ACCESS FULL | TAB3 | 1 | 39 | 2 |
    |* 14 | INDEX UNIQUE SCAN | (PK_TAB4) | 1 | 13 | |
    | 15 | TABLE ACCESS FULL | TAB5 | 82 | 4264 | 2 |
    | 16 | VIEW PUSHED PREDICATE | View3 | 1 | 13 | |
    | 17 | NESTED LOOPS | | 1 | 52 | 2 |
    | 18 | NESTED LOOPS | | 1 | 39 | 2 |
    |* 19 | INDEX UNIQUE SCAN | (PK_TAB6) | 1 | 13 | 1 |
    |* 20 | INDEX RANGE SCAN | (PK_TAB7) | 1 | 26 | 1 |
    |* 21 | INDEX UNIQUE SCAN | (PK_TAB8) | 1 | 13 | |
    | 22 | TABLE ACCESS BY INDEX ROWID| TAB9 | 3 | 78 | 1 |
    |* 23 | INDEX UNIQUE SCAN | (PK_TAB9) | 1 | | |
    |* 24 | INDEX UNIQUE SCAN | (PK_TAB10)| 1 | 13 | |
    | 25 | BUFFER SORT | | 1 | 115 | 9 |
    | 26 | TABLE ACCESS BY INDEX ROWID | TAB2 | 1 | 115 | 1 |
    |* 27 | INDEX RANGE SCAN | (TAB2_IDX2)| 1 | | |
    |* 28 | TABLE ACCESS BY INDEX ROWID | TAB1 | 12 | 25224 | 1 |
    |* 29 | INDEX UNIQUE SCAN | (PK_TAB1) | 1 | | |
    Predicate Information (identified by operation id):
    1 - filter(ROWNUM<=3)
    3 - filter(ROWNUM<=3)
    11 - access("TAB5"."PATH_ID"="TAB4"."PATH_ID")
    13 - filter("TAB3"."AUTH_GROUP_ID"<>(-1) AND ("TAB3"."AUTH_GROUP_ID"=0 OR "TAB3"."AUTH_GROUP_ID"=1))
    14 - access("TAB3"."PATH_ID"="TAB4"."PATH_ID")
    19 - access("TAB5"."DOMAIN_ID"="TAB6"."DOMAIN_ID")
    20 - access("TAB6"."DOMAIN_ID"="TAB7"."DOMAIN_ID")
    21 - access("TAB7"."RULE_ID"="TAB8"."RULE_ID")
    23 - access("TAB9"."POLICY_ID"="TAB5"."POLICY_ID")
    24 - access("TAB9"."ASSOCIATED_FORM_ID"="TAB10"."FORM_ID")
    27 - access("TAB2"."CERT_SERIAL_NUM"=24293)
    28 - filter("View2"."POLICY_ID"="TAB1"."POLICY_ID")
    29 - access("TAB1"."TRANSACTION_ID"="TAB2"."TRANSACTION_ID")
    Note: cpu costing is off
    54 rows selected.
    Elapsed: 00:00:01.81
    Execution Plan
    0 SELECT STATEMENT Optimizer=CHOOSE
    1 0 COLLECTION ITERATOR (PICKLER FETCH) OF 'DISPLAY'
    Statistics
    39 recursive calls
    0 db block gets
    629 consistent gets
    0 physical reads
    104 redo size
    5169 bytes sent via SQL*Net to client
    405 bytes received via SQL*Net from client
    5 SQL*Net roundtrips to/from client
    31 sorts (memory)
    0 sorts (disk)
    54 rows processed
    2) Execution Plan for VIEW1 <<-- With ORDER BY" clause and table alias (order by TAB2.transaction_id)
    SQL> explain plan for SELECT TO_CHAR(QT.TRANSACTION_ID), QT.POLICY_ID, QT.REQUEST_TYPE
    2 FROM <VIEW1> QT WHERE QT.CERT_SERIAL_NUM=30003 AND
    3 (QT.AUTH_GROUP_ID=0 OR QT.AUTH_GROUP_ID=1) AND ROWNUM <= 3 ORDER
    4 BY TRANSACTION_ID ASC
    5 /
    Explained.
    Elapsed: 00:00:10.20
    SQL> select * from table(dbms_xplan.display);
    PLAN_TABLE_OUTPUT
    | Id | Operation | Name | Rows | Bytes | Cost |
    | 0 | SELECT STATEMENT | | 3 | 195 | 14 |
    | 1 | SORT ORDER BY | | 3 | 195 | 14 |
    |* 2 | COUNT STOPKEY | | | | |
    | 3 | VIEW | VIEW1 | 17 | 1105 | 13 |
    | 4 | NESTED LOOPS | | 17 | 38573 | 13 |
    | 5 | MERGE JOIN CARTESIAN | | 1 | 167 | 12 |
    |* 6 | TABLE ACCESS BY INDEX ROWID | TAB2 | 1 | 115 | 4 |
    | 7 | INDEX FULL SCAN | (TAB2_IDX) | 94 | | 1 |
    | 8 | BUFFER SORT | | 1 | 52 | 8 |
    | 9 | VIEW | VIEW2 | 1 | 52 | 8 |
    | 10 | SORT UNIQUE | | 1 | 156 | 8 |
    | 11 | NESTED LOOPS | | 1 | 156 | 6 |
    | 12 | NESTED LOOPS | | 1 | 143 | 6 |
    | 13 | NESTED LOOPS OUTER | | 1 | 117 | 5 |
    |* 14 | HASH JOIN | | 1 | 104 | 5 |
    | 15 | NESTED LOOPS | | 1 | 52 | 2 |
    |* 16 | TABLE ACCESS FULL | TAB3 | 1 | 39 | 2 |
    |* 17 | INDEX UNIQUE SCAN | (PK_TAB4) | 1 | 13 | |
    | 18 | TABLE ACCESS FULL | TAB5 | 82 | 4264 | 2 |
    | 19 | VIEW PUSHED PREDICATE | View3 | 1 | 13 | |
    | 20 | NESTED LOOPS | | 1 | 52 | 2 |
    | 21 | NESTED LOOPS | | 1 | 39 | 2 |
    |* 22 | INDEX UNIQUE SCAN | (PK_TAB6) | 1 | 13 | 1 |
    |* 23 | INDEX RANGE SCAN | (PK_TAB7) | 1 | 26 | 1 |
    |* 24 | INDEX UNIQUE SCAN | (PK_TAB8) | 1 | 13 | |
    | 25 | TABLE ACCESS BY INDEX ROWID| TAB9 | 3 | 78 | 1 |
    |* 26 | INDEX UNIQUE SCAN | (PK_TAB9) | 1 | | |
    |* 27 | INDEX UNIQUE SCAN | (PK_TAB10) | 1 | 13 | |
    |* 28 | TABLE ACCESS BY INDEX ROWID | TAB1 | 12 | 25224 | 1 |
    |* 29 | INDEX UNIQUE SCAN | (PK_TAB1) | 1 | | |
    Predicate Information (identified by operation id):
    2 - filter(ROWNUM<=3)
    6 - filter("TAB2"."CERT_SERIAL_NUM"=30003)
    14 - access("TAB5"."PATH_ID"="TAB4"."PATH_ID")
    16 - filter("TAB3"."AUTH_GROUP_ID"<>(-1) AND ("TAB3"."AUTH_GROUP_ID"=0 OR "TAB3"."AUTH_GROUP_ID"=1))
    17 - access("TAB3"."PATH_ID"="TAB4"."PATH_ID")
    22 - access("TAB5"."DOMAIN_ID"="TAB6"."DOMAIN_ID")
    23 - access("TAB6"."DOMAIN_ID"="TAB7"."DOMAIN_ID")
    24 - access("TAB7"."RULE_ID"="TAB8"."RULE_ID")
    26 - access("TAB9"."POLICY_ID"="TAB5"."POLICY_ID")
    27 - access("TAB9"."ASSOCIATED_FORM_ID"="TAB10"."FORM_ID")
    28 - filter("VIEW2"."POLICY_ID"="TAB1"."POLICY_ID")
    29 - access("TAB1"."TRANSACTION_ID"="TAB2"."TRANSACTION_ID")
    Note: cpu costing is off
    53 rows selected.
    Elapsed: 00:00:08.29
    Execution Plan
    0 SELECT STATEMENT Optimizer=CHOOSE
    1 0 COLLECTION ITERATOR (PICKLER FETCH) OF 'DISPLAY'
    Statistics
    1079 recursive calls
    0 db block gets
    597 consistent gets
    21 physical reads
    0 redo size
    5177 bytes sent via SQL*Net to client
    405 bytes received via SQL*Net from client
    5 SQL*Net roundtrips to/from client
    63 sorts (memory)
    0 sorts (disk)
    53 rows processed
    3) Execution Plan for VIEW1 <<-- Without any "ORDER BY" clause
    SQL> explain plan for SELECT TO_CHAR(QT.TRANSACTION_ID), QT.POLICY_ID, QT.REQUEST_TYPE
    2 FROM <VIEW1> QT WHERE QT.CERT_SERIAL_NUM=30003 AND
    3 (QT.AUTH_GROUP_ID=0 OR QT.AUTH_GROUP_ID=1) AND ROWNUM <= 3 ORDER
    4 BY TRANSACTION_ID ASC
    5 /
    Explained.
    Elapsed: 00:00:10.20
    SQL> select * from table(dbms_xplan.display);
    PLAN_TABLE_OUTPUT
    | Id | Operation | Name | Rows | Bytes | Cost |
    | 0 | SELECT STATEMENT | | 3 | 213 | 11 |
    | 1 | SORT ORDER BY | | 3 | 213 | 11 |
    |* 2 | COUNT STOPKEY | | | | |
    | 3 | NESTED LOOPS | | 17 | 1207 | 10 |
    | 4 | MERGE JOIN CARTESIAN | | 1 | 32 | 9 |
    | 5 | VIEW | VIEW2 | 1 | 26 | 8 |
    | 6 | SORT UNIQUE | | 1 | 156 | 8 |
    | 7 | NESTED LOOPS | | 1 | 156 | 6 |
    | 8 | NESTED LOOPS | | 1 | 143 | 6 |
    | 9 | NESTED LOOPS OUTER | | 1 | 117 | 5 |
    |* 10 | HASH JOIN | | 1 | 104 | 5 |
    | 11 | NESTED LOOPS | | 1 | 52 | 2 |
    |* 12 | TABLE ACCESS FULL | TAB3 | 1 | 39 | 2 |
    |* 13 | INDEX UNIQUE SCAN | PK_TAB4 | 1 | 13 | |
    | 14 | TABLE ACCESS FULL | TAB5 | 82 | 4264 | 2 |
    | 15 | VIEW PUSHED PREDICATE | VIEW3 | 1 | 13 | |
    | 16 | NESTED LOOPS | | 1 | 52 | 2 |
    | 17 | NESTED LOOPS | | 1 | 39 | 2 |
    |* 18 | INDEX UNIQUE SCAN | PK_TAB6 | 1 | 13 | 1 |
    |* 19 | INDEX RANGE SCAN | PK_TAB7 | 1 | 26 | 1 |
    |* 20 | INDEX UNIQUE SCAN | PK_TAB8 | 1 | 13 | |
    | 21 | TABLE ACCESS BY INDEX ROWID| TAB9 | 3 | 78 | 1 |
    |* 22 | INDEX UNIQUE SCAN | PK_TAB9 | 1 | | |
    |* 23 | INDEX UNIQUE SCAN | PK_TAB10 | 1 | 13 | |
    | 24 | BUFFER SORT | | 1 | 6 | 9 |
    | 25 | TABLE ACCESS BY INDEX ROWID | TAB2 | 1 | 6 | 1 |
    |* 26 | INDEX RANGE SCAN | TAB2_IDX2 | 1 | | |
    |* 27 | TABLE ACCESS BY INDEX ROWID | TAB1 | 12 | 468 | 1 |
    |* 28 | INDEX UNIQUE SCAN | PK_TAB1 | 1 | | |
    Predicate Information (identified by operation id):
    2 - filter(ROWNUM<=3)
    10 - access("TAB5"."PATH_ID"="TAB4"."PATH_ID")
    12 - filter("TAB3"."AUTH_GROUP_ID"<>(-1) AND ("TAB3"."AUTH_GROUP_ID"=0 OR "TAB3"."AUTH_GROUP_ID"=1))
    13 - access("TAB3"."PATH_ID"="TAB4"."PATH_ID")
    18 - access("TAB5"."DOMAIN_ID"="TAB6"."DOMAIN_ID")
    19 - access("TAB6"."DOMAIN_ID"="TAB7"."DOMAIN_ID")
    20 - access("TAB7"."RULE_ID"="TAB8"."RULE_ID")
    22 - access("TAB9"."POLICY_ID"="TAB5"."POLICY_ID")
    23 - access("TAB9"."ASSOCIATED_FORM_ID"="TAB10"."FORM_ID")
    26 - access("TAB2"."CERT_SERIAL_NUM"=1022)
    27 - filter("VIEW2"."POLICY_ID"="TAB1"."POLICY_ID")
    28 - access("TAB1"."TRANSACTION_ID"="TAB2"."TRANSACTION_ID")
    Note: cpu costing is off
    52 rows selected.
    Elapsed: 00:00:03.37
    Execution Plan
    0 SELECT STATEMENT Optimizer=CHOOSE
    1 0 COLLECTION ITERATOR (PICKLER FETCH) OF 'DISPLAY'
    Statistics
    38 recursive calls
    0 db block gets
    287 consistent gets
    0 physical reads
    0 redo size
    5006 bytes sent via SQL*Net to client
    405 bytes received via SQL*Net from client
    5 SQL*Net roundtrips to/from client
    29 sorts (memory)
    0 sorts (disk)
    52 rows processed

  • Sorting character column ( used in order by clause dynamically)

    Hi,
    I need help on sorting character-based numbers. Like say, I want to sort customers based on street numbers(which is a character string being used in the
    order by clause) they live in.
    The criteria are :
    i. Numbers must take precedence.
    This being a character string, 1000001 comes before 2. This shouldn't happen. And you cannot use to_number
    since using it with a string having characters in it would raise an error.
    ii. If only a single alphabet occurs as the last character, then treat the whole string as a number except the last character and then sort it
    as if sorting a number. Something like : if you have 1000A, 200D, 200B, 1000X, the result would be 200B,200D,1000A,1000X.
    iii. if a character occurs elsewhere in the string, then perform the search normally as if performing a character search.
    The output of the following data :
    100
    A101
    B100A
    110C
    C120B
    120
    100020
    120C
    C1100
    100D
    would be like :
    100
    100D
    110C
    120
    120C
    100020
    A101
    B100A
    C120B
    C1100
    Please note that the sort is being done dynamically, so I could have access to the values of the street numbers only during run time.
    Any help is really appreciated.
    Thanks in advance.
    Regards,
    Anil.

    Create a function to test whether the column is numeric :
    create FUNCTION is_numeric(v_number VARCHAR2)
    RETURN INTEGER
    IS
    l_number NUMBER;
    BEGIN
    IF INSTR(UPPER(v_number),'E') > 0 THEN
    RETURN 0;
    END IF;
    l_number := TO_NUMBER(v_number);
    RETURN 1;
    EXCEPTION
    WHEN OTHERS THEN
    RETURN 0;
    END;
    And try this query
    Assume the table name is TEST with column STREET
    select * from TEST
    order by case is_numeric(STREET) when 1 then LPAD(STREET,20, ' ') else STREET end
    Please make sure that 20 mentioned above is the column size for STREET.
    Hope this helps.
    -Nags

  • JPQL - No UPPER() in ORDER BY clause??

    I have created a NamedQuery and am attempting to order my returned collection using the ORDER BY clause, however, the specification asks for string ordering to be case insensitive. It seems that I cannot do that with the Java Persistence Query Language - or at least the implementation that we are using. I am using Glassfish v2ur2 with uses Oracle TopLink Essentials - 2.0.1, Build b04-fcs (found in my Exception message).
    I suspect that the only way to do what I want is to create a Comparator for the ResultList and run a sort after I get the result list from my EntityManager. Is that correct or is my syntax wrong in my JPQL?
    Here is my named query (cut from a larger list of named queries), pretty simple:
    @NamedQuery(name = "MyObject.findAll", query = "SELECT a FROM MyObject a ORDER BY UPPER(a.myString), a.Id")Here is a summary exception report that I receive:
    ===========================================================================
       Exception: javax.ejb.EJBException
       Description: nested exception is: java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
            java.rmi.RemoteException: null; nested exception is:
            Exception [TOPLINK-8024] (Oracle TopLink Essentials - 2.0.1 (Build b04-fcs (04/11/2008))): oracle.toplink.essentials.excepti
    ons.EJBQLException
    Exception Description: Syntax error parsing the query [MyObject.findAll: SELECT a FROM MyObject a WHERE ORDER BY UPPER(a.myString), a.Id], line 1, column 81: syntax error at [UPPER].
    Internal Exception: line 1:81: expecting IDENT, found 'UPPER'
    (Stack-Trace Included)
    ===========================================================================

    Post Author: krypton
    CA Forum: Data Connectivity and SQL
    Thanks Lynn
    I tried your suggestion. But there is one probelm.
    When i sort the data in descending order using the count(calls) field, the data is returned but the customer's name appears multiple times along with their calls raised.
    E.g, if customer Mark raised multiple calls i.e. 2, 5, and 10 calls, then the report will show
    Mark   2
    Mark  5
    Mark 10
    But is there a way to aggregate all the calls for mark and show them only once:
    such as Mark   17
    Thanks

  • Passing parameters in order by clause of cursor

    Hi friends,
    I am facing a strange problem
    I have a cursor with a order by clause.
    OPEN cursor_nomrpt FOR
    SELECT DISTINCT
    CAST(plano.desc3 AS VARCHAR2(50)) category
    ,plano.name plan_name
    ,nvl(CAST(plano.desc6 AS VARCHAR2(50)),'not applicable') pcrr
    ,nvl(trunc(plano.value18,2),0) nominal_slm
    ,nvl(trunc(plano.value19,2),0) blm
    ,plano.dbdateeffectivefrom date_live
    plano.dbkey pog_id
    ,case when plano.value47 < 0 THEN 0 when plano.value47 IS NULL THEN 0 ELSE plano.value47 END AS parent_id
    FROM
    dplapro1.ix_spc_planogram plano
    INNER JOIN dplapro1.ix_spc_performance perf ON plano.dbkey = perf.dbparentplanogramkey
    INNER JOIN dplapro1.ix_spc_product product ON perf.dbparentproductkey = product.dbkey
    INNER JOIN dplapro1.ix_spc_product_key prodkey ON product.dbkey2 = prodkey.dbkey
    AND prodkey.keylevel = 2
    WHERE
    plano.value50 = 0
    AND plano.dbkey4 = p_subcatkey
    ORDER BY ltrim(rtrim(p_orderby)) ASC;
    p_orderby is the parameter being passed. But the output is not sorted. But when I run the cursor by hardcoding the parameter value it works fine...
    Need your help on this

    Hi,
    When you use a local variable in a cursor, it's as if you had hard-coded a literal in its place, so you can't use a variable for a column name.
    If you know all the possible values of p_orderby, you can do something like this:
    ORDER BY  TRIM ( CASE  p_orderby
                   WHEN  'DESC'     THEN  plano.desc
                   WHEN  'VALUE'     THEN  plano.value
               END
                ) ASC;If you don't know all the possible values, you could use dynamic SQL.
    By the way,
    TRIM (x)returns the same results as
    LTRIM ( RTRIM (x))

  • [JPA/TOPLINK] is the function "lower" supported in "order by" clause?

    In EJB-QL
    I can use lower() or upper() in where clause.
    But there is always a parse exception thrown when i tried to use it in main clause or order by clause.
    works:
    select s from Student s where lower(s.name) like 'm%'
    exception thrown:
    select s from Student s where s.name like 'm%' order by lower(s.name)
    OR --------------
    Why i am asking this is that the resultset returned from database is not alphabetical sorted but ascii sorted, which means any characters with upper case is always prior to the ones with lower case.
    If EJB-QL doesn't support using lower() in order by clause, do I have any other options to avoid this problem?
    BTW, it is the Oracle 10g we are using as DB
    many thanks,
    Xuphey
    Edited by: Xuphey on Nov 29, 2007 1:33 AM

    If you want to do this, you'd have to use dynamic SQL (execute immediate or DBMS_SQL). For the easier 'execute immediate' approach, you'd do something like
    create or replace someProc( someArg varchar2 )
    as
      strSQL varchar2(4000)
    begin
      strSQL := <<string containing your SQL statement up to the order by clause>>
      strSQL := strSQL || 'ORDER BY ' || someArg
      execute immediate strSQL;
    endJustin

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

  • Problem in sql query because of order by clause

    Hi All,
    I am facing a one problem in my one sql query.I am using Oracle 10gR2.
    Query is given below:
    SELECT t1.ename
            FROM T1, T2
           WHERE T1.EMPNO = 1234
             AND T1.ACCOUNTNO = T2.ACCOUNTNO
             AND T1.SEQ = T2.SEQ
           ORDER BY T2.SEQThe Plan of the query is :
    | Id  | Operation                     | Name                 | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT              |                      |     2 |   218 | 11716   (1)| 00:00:41 |
    |*  1 |  TABLE ACCESS BY INDEX ROWID  | T1                   |     1 |    89 |     1   (0)| 00:00:01 |
    |   2 |   NESTED LOOPS                |                      |     2 |   218 | 11716   (1)| 00:00:41 |
    |*  3 |    TABLE ACCESS BY INDEX ROWID| T2                   |     2 |    40 | 11715   (1)| 00:00:41 |
    |   4 |     INDEX FULL SCAN           | PK_T2_SEQ            | 58752 |       |   122   (5)| 00:00:01 |
    |*  5 |    INDEX RANGE SCAN           | FK_ACCOUNTNO         |     3 |       |     0   (0)| 00:00:01 |
    ----------------------------------------------------------------------------------------------------Now i want to reduce the time of this query.
    If i am removing Order by clause from query than performance of the query is totally perfect but with order by clause its taking a time.
    I have already set SORT_AREA_SIZE but still nothing is improving.
    Welcome and thanks for your suggestions.
    Thanks,
    Edited by: BluShadow on 23-Jun-2011 07:55
    added {noformat}{noformat} tags and formatted explain plan to make it readable.  Please see {message:id=9360002} for details on how to post code and data                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    Hi,
    There are a couple of things I do not understand.
    1. Why don't you put {noformat}{noformat} around your code, it makes it so much easier to read, especially your explain plan
    2. You claim that the ORDER BY is problematic compared to no order by. Then why do you choose to post only one plan?
    3. It is hard to understand how your tables relate, and which indexes you have and which you don't.
    - PK_T2_SEQ, does this mean that SEQ alone is primary key of T2?
    - If SEQ is primary key of T2, why do you join on accountno, seq and not just seq?
    - If SEQ is primary key of T2 one of the tables is denormalized.
    4. FK_ACCOUNTNO, is this an index on accountno, alone?
    - Or is this AccountNo, Seq?
    5. Is there no index on T1.EMPNO?
    Above could of course just be a case of my not understanding the names of your indexes.
    So, here are my guesses:
    Above plan is for the ORDER BY query. That means the optimizer, has chosen to full scan PK_T2_SEQ, since data is then read according to the ORDER BY.
    (This could be a bad choice)I
    You could try and order by t1.seq, instead. Result should be the same.
    Regards
    Peter                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • 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

  • Need to copy the current order-by clause of a report.

    Situation:
    - I have a report with a default sort setting, and sortable column headers.
    - User navigates to page with this report.
    - Report page renders in default sort setting.
    - User changes sort (clicks on one of the column headers).
    I now want to create a button (and process) to copy the current report data including the sort it is in right now. For this I need to somehow find out what the current order-by clause is of the rendered report.
    I'm looking into always saving the REQUEST in an application item in case the request is LIKE 'fsp_sort%'. And then parse this value in the process.
    Any better way of doing this?
    Toon

    Toon,
    eventually this example may help you:
    http://htmldb.oracle.com/pls/otn/f?p=31517:69
    Denes Kubicek
    http://deneskubicek.blogspot.com/
    http://htmldb.oracle.com/pls/otn/f?p=31517:1
    -------------------------------------------------------------------

Maybe you are looking for

  • Graphic Designer Pismo G3 Owner not sure what to do about upgrading...

    Ok. Here's the scenario. I'm running my Powerbook G3 Pismo(Firewire) 500 MHZ, 512MB ram, 20GB hard Drive. Dead Battery. Daystar Superdrive CD/DVD Burner. I also run OSX Panther 10.3.9. Most of my graphics programs are still on OS9, while I websurf an

  • Adobe photoshop cs4 graphics card acceleration help!

    Need a little help, everytime i start cs4, it says "adobe photoshop cs4 now includes graphics card acceleration.  we recomend you vist your video card manufacturers website and download and install latest drives. I am running vista 64 bit and a ati r

  • Multiple Value in additional fields using SAP Query

    HI All, I have a question related additional field in SAP Query. I tried to create report about PR and PO using SAP Query. Since one PR can be converted to multiple PO, I decided to create additional field po_1 to display the value of PO that related

  • Distributing 'save for later' distribution pdf forms

    I have created a _pub_ pdf form and corresponding data_set file for their collection. Things seem to work IF the person receiving them understands to use Acrobat or Reader to fill the form and not Apple Preview for example. When the form was original

  • Itunes store displays text, no pictures

    When i open itunes store, all the information appears but the no pictures. Instead little question marks are in there places. I'm very frustrated because i think its effecting my purchases. Please Help! http://i303.photobucket.com/albums/nn152/rainbo