Order by in select query

Hi guys
i am getting problem in my select query which is creating one long string, it is working fine without order by but when i run this with order by it get hanged. this query using on function to concatenate multiple strings in one string as well
Please help me what i am doing wroing.
select
regexp_substr(pe.emp_id,'[0-9]+$') ||'|'||
p.title ||'|'||
cdt.text||'|'||
j.tit||staff_pcb.host_pub_tit ||'|'||
jou.vol ||pcb.vol||pcp.vol ||'|'||
jou.journal_number||'|'||
substr (jou.pages||pcb.pages||pcp.pages, 1, instr (jou.pages||pcb.pages||pcp.pages, '-')-1)||'|'||
substr (jou.pages||pcb.pages||pcp.pages, instr (jou.pages||pcb.pages||pcp.pages, '-')+1)||'|'||
pcb.st||jou.st||pcp.st||'|'||
concat_aut(p.id)
from pub p,journal j,caa c,person pe,class_t cdt,
(select pcj.pub_id,pcj.vol,pcj.pages,pcja.st
From pub_C_j_a pcja,pc_j pcj
where pcja.pub_c_j_id = pcj.pub_id)jou,
(select pcb.pub_id,pcb.host_pub_tit,pcb.pages,pcb.vol,pcba.st
From pub_c_b pcb,pub_c_b_a pcba
where pcba.pub_c_b_id = pcb.pub_id)pcb,
(select pcp.pub_id,pcp.vol,pcp.pages,pcpa.st
From pub_c_p pcp,pub_c_p_a pcpa
where pcpa.pub_c_p_id = pcp.pub_id)pcp,
where
p.id = c.pub_id
and c.person_id = pe.id
and p.t_c_id = cdt.c_id
and p.journal_id = j.id(+)
and p.id = jou.publication_id(+)
and p.id = pcb.publication_id(+)
and p.id = pcp.publication_id(+)
and substr(regexp_substr(pe.emp_id,'[0-9]+$'),1,2) in('77','78')
and pcb.st||jou.st||pcp.st='1' order by pe.emp_id
;

Not sure about why it's only hanging on order by but looks like your query causing full table scan because of this in WHERE clause:
and pcb.st||jou.st||pcp.st='1'
I would change it to something like:
and ((pcb.st='1'  and jou.st = '' and pcp.st = '') or (jou.st='1'  and pcb.st = '' and pcp.st = '')  or (pcp.st='1'  and jou.st = '' and pcb.st  = '') )

Similar Messages

  • Column order in a select * query

    Suppose I have 256 columns in a table and if I query select * from  tablename ,what will the column order in the result.Will this be always same as order as in created statement?

    If the columns were all in the original CREATE TABLE statement, then, yes, the ordering of columns in SELECT * FROM will match the order from the CREATE TABLE statement.
    If columns were added after the initial create, then the original columns will come first (in their order) and then the added columns (in their order), etc.
    In the real world, it is a very bad practice to use SELECT * and have expectations about the ordering of the columns. Consider this scenario:
    Table T was created and implemented in production a year ago with columns A, B, C
    A project started up three months ago and added column D but the project is stalled in development. So in development T had columns A, B, C, D
    Later, another project started up and added columns E and F. Unlike the other project, it has progressed to Test. and Production. So in Development the table has columns A, B, C, D, E, F. In test and production the table has columns A, B, C, E, F.
    Now that stuck project has progressed to Test and Production. Now T has columns A, B, C, E, F, D in test and production but still A, B, C, D, E, F in development.
    Until someone notices and decides to fix it (where and how?)
    Be very, very careful about using SELECT *.

  • Default in "order by" in select query may be different in 11g from 10g

    Hi, I am wondering if when you are querying a table in 11g and you use the order by clause and there is more than one occurrences with the same values in the order by, if the 11g default is different than from 10g.  For instance.
    DECLARE MHBulk CURSOR FOR                       
      select invoice_nbr,
                   customer_nbr,
                    post_century,
                    post_yymmdd,
         from CUSTOMERS
         where customer_nbr = 1234
         order by
               post_century,
               post_yymmdd;
    If you have more than one occurrence of the same customer_nbr, post_century, and post_yymmdd it looks like the default order for how 11g retrieves the records is a bit different than the 10g default.   Does anyone know why this is?

    JustinCave wrote:
    In any version of Oracle, if your ORDER BY does not specify a completely unique order, the order in which ties are broken is arbitrary.  Realistically, it will depend on things like the specific query plan chosen, the physical order of data on disk, which parallel query slave read the row, etc.  So it is subject to change within the same version of the database when, for example, a query plan changes.  It is entirely plausible that the results would be returned in the same order for years and then suddenly change one day.  If you care about the order of ties, you should add additional logic to the ORDER BY clause that specifies the order you want rather than assuming that there is a "default" order applied.
    Upgrading to a new version of Oracle, particularly if that was done via something like exporting and importing the data so that you're changing the Oracle version and the physical order of data and various object statistics, it is not at all unusual that you would get slightly different plans and that ties would be broken differently.  I wouldn't assume that there is a new "default" order, though.  It's entirely possible for the order to change if the query plan changes again.
    Justin
    Well, what happened is we've gotten a few new customers and those customers are on Linux oracle 11g.  All the other customers are on regular unix 10g.  So, it sounds like we've just been lucky with the order until now.  In our system we have a sequence number column which is unique and I solved this by adding that in the ORDER BY clause.  I was just curious as to whether oracle had a default when it found duplicate fields in the ORDER BY clause.  I can't imagine that oracle doesn't have a default like unique_session_id or something like that.

  • Select query help for Sales order

    Hi Experts,
    I have to write a select query to fetch sales orders which are open along with the quantities which are open ( not delivered). What would the best approach for this?
    Any help is appreciated. Expecting code samples....Thanks
    Thanks
    Ricky

    hi,
    do like this,
    write a select query for vbak and vbuk as follows.
    delivery status field is <b>lfstk</b> from <b>vbuk</b>,
    and relation field is <b>vbeln</b> from the both the tables.
    reward points if useful,
    regards,
    seshu.

  • Select query gives result in abc order instead of creation order

    Hi,
    I used the following command in sql command window to insert some rows to my table:
    SQL>
    SQL> insert into regions (Region_ID, Region_Name) values (1 , 'Zafon');
    1 row inserted
    SQL> insert into regions (Region_ID, Region_Name) values (2 , 'Hasharon');
    1 row inserted
    SQL> insert into regions (Region_ID, Region_Name) values (3 , 'Merkaz');
    1 row inserted
    SQL> insert into regions (Region_ID, Region_Name) values (4 , 'Jerusalem');
    1 row inserted
    SQL> insert into regions (Region_ID, Region_Name) values (5 , 'Hashfela');
    1 row inserted
    SQL> insert into regions (Region_ID, Region_Name) values (6 , 'Darom');
    1 row insertedWhen I use select * query to see the table, I get the content in abc order:
    SQL> SELECT * FROM REGIONS;
    REGION_ID REGION_NAME
            6 Darom
            2 Hasharon
            5 Hashfela
            4 Jerusalem
            3 Merkaz
            1 Zafon
    6 rows selectedHow can I get the result in the creation order (first created- first shown)?
    Thanks

    >
    How can I get the result in the creation order (first created- first shown)?
    >
    You can't - not unless you use a solution that you should NEVER use unless absolutely necessary.
    WHY do you need to do this? You never provide a reason.
    To get a result in creation order there are two requirements:
    1. Use an ORDER BY when you query the table - this is the only requirement others have mentioned
    2. Control and specify the creation order when you INSERT the data
    Unfortunately there is only ONE way that I am aware of to implement #2 above (i.e. to control the insertion order) and that is to SERIALIZE the insertion of rows into the table. That means that only ONE user can insert rows into the table at a time perhaps by using a stored procedure to perform the insert.
    In a multi-user system a USER can NOT see uncommitted data of other users. If a user uses a trigger and a SEQUENCE generator to generate ascending numbers another user can use that same trigger and sequence to generate numbers also. If the first user performs an INSERT and gets number 37 but doesn't commit a second user can perform an INSERT, get number 38 and COMMIT before the first user commits.
    That means that the row with 38 was created (committed) first but has a higher sequence than the row with 37.
    The best you can do is use a sequence generator to generate unique ascending numbers. Then you can query the data using an ORDER BY on the column that contains the sequence value. But, as shown above, that doesn't guarantee that the rows were actually committed in that order.
    That may sound like a trivial distinction but it has a very important implication. It means that you can NOT use that sequenced column to extract data reliably for batch-type processing. For the above example supposed your batch process extracted data for values from 1 to 38 and then that first user did a COMMIT.
    The next extract would be for values from 39 to 50 (or some other value) and the row with 37 would never be extracted. For the same reasons you can't use a CREATION_DATE value for such extract purposes either since you would have the same issue.

  • Using order by in the select query

    Hi All,
    I have query in which I need the latest record. To get the latest record, I can
    1) Select all entries into an internal table and sort them descending and get the first one
    2) Select all entries into an internal table and order by in the select statement itself.
    Then read the first one.
    Which approach should be better as for as the performance is concern.
    The query is on MKPF table and I have the material document number. I need the latest entry.
    Regards,
    Shahu

    Hi,
    The first one would be better.At the most we should not use order by in select statement bcoz it directly sorts the data according to that in database itself reverting performance issues.
    Otherwise you can use select max* if records are less.
    Reward points if helpful.
    Thanks,
    Ponraj.s.

  • Order mismatch in selected data using Select query

    Hello Experts,
    We are upgrading from 4.6C to ECC6. I came across a select query on a custom table, which gives different order of data from 4.6C to ECC6. Data (no. of records) is same in both the servers but order is different. Table doesn't have indexes in either 4.6C or ECC6. What would be the cause for order change?
    Further, in 4,6C, ECC6 and data bases order of the data is totally different. Select query have some conditions in where clause with select options, but in both the cases (4.6C and ECC6) I am not passing any data from the selection screen so am getting entire data from the data base.
    Thanks in advance
    Phalani

    From the SAP service market place I found that
    1. Unless we use SORT or ORDER BY clause the order of the data is not in our control.
    2. In 4.6C, two same select queries never give the result in the same order, if the primary key contains character fields.
    Thanks for your help.
    Phalani

  • Select query result set order

    Hi,
    Can I know the order in which Oracle outputs the result set of a simple SELECT query ? Will the output always be same as the order in which rows got inserted ?
    Please advise,
    Thanks,
    Smitha

    If you include an ORDER BY than the order of the result set is known.
    It will not always be the same as the order in which rows got inserted.

  • Order of the selection fields in SAP QUERY

    Hello All,
    How can we set the order of the selection fields in SAP QUERY!
    Regards!
    Ashish

    Hi,
    You can go into infoset and change the order.
    Or you can select 1 by 1 in the same order, you want to display.
    Below is the link which might help you:
    help.sap.com/printdocu/core/Print46c/EN/data/.../BCSRVQUE.pdf
    Please revert, if needed more clarifications
    Regards,
    Yashwin

  • MDO select query: how to control sort order using parameter

    Hi experts, is there a way of controling the sort order of an MDO select query using some parameter?
    I was thinking about using some statement like CASE [Param.1] WHEN 'abc' THEN [ORDER_NO]...END in sort section of the query but it is not working.
    Of course I colud go for various select queries...but I am wondering if it can be done using only one?
    Any ideas?
    Thanks for any help

    Hi Marco,
    Yes this can be achieved dynamically using SortExpr under dynamic link assignment in MDOAction block if you are using a transaction to call it.
    Please check below thread:
    Re: MDO Query Action Block In MII Transaction
    Or else, this [Param.1] thing should work as well provided it doesn't get the logic part in it, just pass the columns names separated by comma. Haven't tried it though, will check it for you.
    Best Regards,
    Swaroop

  • To select particular rows from order by select query

    Hi all,
    I want to select particular rows from a order by select query like...
    select * from emp order by ename;
    If i pass 3 and 7 dynamically in where clause or something like that, it has to show rows from 3 to 7 only.
    Thanks in advance
    Pal

    This?
    SQL> select *
    from (
       select e.*,
          row_number() over (order by ename) rn
       from emp e)
    where rn in (3,7)
    EMPNO ENAME      JOB         MGR HIREDATE         SAL       COMM     DEPTNO RN
    7698 BLAKE      MANAGER    7839 01-MAY-81       2850                    30  3
    7566 JONES      MANAGER    7839 02-APR-81       2975                    20  7
    2 rows selected.

  • Finding the original quanitity on sales order : Select Query on CDPOS ?

    Hello ABAPers,
      I have created a sales order and I changed the order quantity over many times using Va02. If i want to programatically determine the orginal quantity, on the sales order when it was created , how would i determine ?
    I thought, I would do a select query on CDPOS table and find out. But i found from se16 that for the Object ID - VERKBELEG and Object id = 00000XXXXX ( where XXXXX is sales order number), the VBEP and VBAP entries for Update mode shows no Old_vales and New_values.
    But if i click on environment>Changes> in Va02 for that particular Sales order, I see the old and new values list.
    Why is this not listed in CDPOS ? How do I progrmatically determine the original quanitity on Sales order ?
    Thanks
    SHK

    Hi Ferry,
      That FM did the trick. I ended up creating a FM myself to find the original qty and original unit. Somehow select qry on CDHDR and CDPOS, returned empty field for Old_value and new_value. Here is my FM below
    FUNCTION z_sw_originalqty_on_so.
    *"*"Local interface:
    *"  IMPORTING
    *"     VALUE(I_VBELN) TYPE  VBELN OPTIONAL
    *"     VALUE(I_POSNR) TYPE  POSNR OPTIONAL
    *"  EXPORTING
    *"     VALUE(I_ORIGINAL_QTY) TYPE  KWMENG
    *"     VALUE(I_ORIGINAL_UNIT) TYPE  VRKME
      DATA : i_editpos TYPE TABLE OF cdred INITIAL SIZE 1  .
      DATA : wa_editpos LIKE LINE OF i_editpos.
      DATA : wa_editpos1 LIKE LINE OF i_editpos.
      DATA : i_cdhdr   TYPE TABLE OF cdhdr INITIAL SIZE 1.
      DATA : i_cdpos   TYPE TABLE OF cdpos INITIAL SIZE 1.
      DATA : wa_cdhdr  LIKE LINE OF i_cdhdr.
      DATA : wa_cdpos  LIKE LINE OF i_cdpos.
      DATA : i_objid TYPE  cdhdr-objectid.
      DATA : delimiter(1) VALUE ' '.
      DATA : lv_org_qty(127)      TYPE c,
             lv_org_unit(127)      TYPE c.
      DATA : l_tabkey TYPE cdpos-tabkey.
      DATA : i_flag.
      CLEAR i_flag.
      CONCATENATE sy-mandt i_vbeln i_posnr '0001'  INTO l_tabkey.
      i_objid = i_vbeln .
      CALL FUNCTION 'CHANGEDOCUMENT_READ'
           EXPORTING
                objectclass                = 'VERKBELEG'
                objectid                   = i_objid
                tablekey                   = l_tabkey
                tablename                  = 'VBEP'
           TABLES
                editpos                    = i_editpos
           EXCEPTIONS
                no_position_found          = 1
                wrong_access_to_archive    = 2
                time_zone_conversion_error = 3
                OTHERS                     = 4.
      IF sy-subrc <> 0.
        SELECT SINGLE bmeng  INTO i_original_qty FROM vbep
                       WHERE vbeln = i_vbeln  AND
                             posnr = i_posnr.
        SELECT SINGLE vrkme INTO i_original_unit FROM vbep
                       WHERE vbeln = i_vbeln  AND
                             posnr = i_posnr.
      ENDIF.
      SORT i_editpos  BY udate utime tabname fname .
      LOOP AT i_editpos INTO wa_editpos.
        READ TABLE i_editpos INTO wa_editpos1
                 WITH KEY tabname = 'VBEP'
                          fname   = 'WMENG'
                          CHNGIND = 'U'.
        CLEAR : i_original_qty,i_original_unit.
        IF sy-subrc EQ 0.
          SHIFT wa_editpos1-f_old  LEFT DELETING LEADING space.
          SPLIT wa_editpos1-f_old AT delimiter INTO lv_org_qty lv_org_unit .
          i_original_qty  = lv_org_qty.
          i_original_unit = lv_org_unit.
          i_flag = 'X'.
          EXIT .
        ENDIF.
      ENDLOOP.
      sy-subrc = 4.
      IF sy-subrc <> 0 AND i_flag NE 'X'.
        SELECT SINGLE bmeng  INTO i_original_qty FROM vbep
                       WHERE vbeln = i_vbeln  AND
                             posnr = i_posnr.
        SELECT SINGLE vrkme INTO i_original_unit FROM vbep
                       WHERE vbeln = i_vbeln  AND
                             posnr = i_posnr.
      ENDIF.

  • Select query for sales order for particular customer oder text and storage

    Hi All,
    I am trying to retriev customer order text and customer storage bin from the following select query, but it's giving huge number of records, I want to restrict the number of records.
    Select customer order text, customer storage bin
                       Select STXH–TDOBJECT, STXH–TDID
                       Where  TDOBJECT = VBBP
                              TDID = Y001
                              TDID = Y007
    Please let me know how to restirct the number of records.
    Thanks,
    Ranjan

    Try using the FM 'READ_TEXT'.
    NAME will be the order number concatenated with the item number.
    And you have the ID and OBJECT.  You may also need to use the LANGUAGE.
    Message was edited by:
            Matt Nagel

  • Simple select query - Row ordering issue

    Hi Guys,
    I want to ask that row chaining and row migration is applicable for Global Temporary Table as well?
    Or is it something related only to Physical DB tables?
    I have requirement as -
    DB Table --> populate GTT_First(process on this) --> Populate GTT_Second.
    I want to insert rows in GTT_Second in particular order.
    So which approach will assure this, or which is better approach?
    To have order by while selecting data from DB Table and inserting in GTT_First OR
    To have order by while inserting data from GTT_First into GTT_Second?
    Will row chaining or row migration play any role here, given that all tables have 85 columns.
    Thanks in advance!

    Avi4Ora wrote:
    We face some problem, here we are not using rownum as you have used for demo. We use input date, a date field.some problem? what problem?
    rownum is only used to fill the tables up with some data....
    And each row in our case has 80 columns.so?
    As i couldnt see the reason for this to happen, I could relate this behaviour to some extent with Row chaining and row migration.What problem are you facing, and why do you think it has to do with row chaining or row migration (doesn't make sense to me)
    Here an example with dates
    SQL> create global temporary table gtt_one
      2  (str varchar2(10)
      3  ,dt date
      4  )
      5  /
    Table created.
    SQL>
    SQL> create global temporary table gtt_two
      2  (id number
      3  ,str varchar2(10))
      4  /
    Table created.
    SQL>
    SQL> create sequence seq
      2  /
    Sequence created.
    SQL> insert into gtt_one
      2  select 'a'||rownum
      3       , sysdate + rownum
      4    from all_objects
      5   where rownum <= 10
      6  /
    10 rows created.
    SQL>
    SQL>
    SQL>
    SQL> insert into gtt_two
      2  select seq.nextval
      3       , str
      4    from (select str
      5            from gtt_one
      6           order by dt desc
      7         )
      8  /
    10 rows created.
    SQL>
    SQL> select *
      2    from gtt_two
      3  /
            ID STR
             1 a10
             2 a9
             3 a8
             4 a7
             5 a6
             6 a5
             7 a4
             8 a3
             9 a2
            10 a1
    10 rows selected.

  • Oracle SQL Select query takes long time than expected.

    Hi,
    I am facing a problem in SQL select query statement. There is a long time taken in select query from the Database.
    The query is as follows.
    select /*+rule */ f1.id,f1.fdn,p1.attr_name,p1.attr_value from fdnmappingtable f1,parametertable p1 where p1.id = f1.id and ((f1.object_type ='ne_sub_type.780' )) and ( (f1.id in(select id from fdnmappingtable where fdn like '0=#1#/14=#S0058-3#/17=#S0058-3#/18=#1#/780=#5#%')))order by f1.id asc
    This query is taking more than 4 seconds to get the results in a system where the DB is running for more than 1 month.
    The same query is taking very few milliseconds (50-100ms) in a system where the DB is freshly installed and the data in the tables are same in both the systems.
    Kindly advice what is going wrong??
    Regards,
    Purushotham

    SQL> @/alcatel/omc1/data/query.sql
    2 ;
    9 rows selected.
    Execution Plan
    Plan hash value: 3745571015
    | Id | Operation | Name |
    | 0 | SELECT STATEMENT | |
    | 1 | SORT ORDER BY | |
    | 2 | NESTED LOOPS | |
    | 3 | NESTED LOOPS | |
    | 4 | TABLE ACCESS FULL | PARAMETERTABLE |
    |* 5 | TABLE ACCESS BY INDEX ROWID| FDNMAPPINGTABLE |
    |* 6 | INDEX UNIQUE SCAN | PRIMARY_KY_FDNMAPPINGTABLE |
    |* 7 | TABLE ACCESS BY INDEX ROWID | FDNMAPPINGTABLE |
    |* 8 | INDEX UNIQUE SCAN | PRIMARY_KY_FDNMAPPINGTABLE |
    Predicate Information (identified by operation id):
    5 - filter("F1"."OBJECT_TYPE"='ne_sub_type.780')
    6 - access("P1"."ID"="F1"."ID")
    7 - filter("FDN" LIKE '0=#1#/14=#S0058-3#/17=#S0058-3#/18=#1#/780=#5#
    8 - access("F1"."ID"="ID")
    Note
    - rule based optimizer used (consider using cbo)
    Statistics
    0 recursive calls
    0 db block gets
    0 consistent gets
    0 physical reads
    0 redo size
    0 bytes sent via SQL*Net to client
    0 bytes received via SQL*Net from client
    0 SQL*Net roundtrips to/from client
    0 sorts (memory)
    0 sorts (disk)
    9 rows processed
    SQL>

Maybe you are looking for

  • Where is my file?

    Started a spread sheet in Numbers  a few days ago.  Opened it again tody by finding it on the list of recent docments, updated, closed. Just to check, tried to find it in Finder  - can't. File name does not show up in spotlight. If I open several mor

  • No Online backups due to datafiles offline than I canu0092t recover. How...?

    Hi gurus!!! I got into a problem with some datafiles. We have MySAP in a BD oracle 9.2.0.6 I used Oracle Entreprise Manager Console to generate two datafiles in the tablespace PSAPPRDUSR, but I generated them in another tablesapce (PSAPPRD) with a na

  • Blocked bb id

    i have accidentally deleted my bb id ! I have created a new id but am unable to change it on my app world or bb protect so i cant use either of them can anyone help ?

  • Return Component flag in Good Receipt

    Hello, I'm creating a report which need to know which one is a Good Receipt and a Return Component from Production Order. I've tried to look at the table, but can't find which is the flag for Return Component and the other (Good Receipt). Does anyone

  • Problems installing informatica 8.1.1

    Hi, I have installed personal oracle 8 on my wndows xp successfully now i am tryying to install informatica 8.1.1(downloaded from the downloads section here) But I cant get past the configure domain step ,Could ne1 provide me some guide to get past t