Order by in subquery ignores where clause

Following the suggestion to simulate "select first," I did the following:
select e.*,
(select * from (select dname from scott.dept d where d.deptno = e.deptno order by dname) t where rownum = 1) dname
from scott.EMP e;
The "order by dname" however, cause the subquery to ignore the where clause.
I know in this case, I can use a first_value() or min(), and it'll always return 1 row b/c of the PK. Still, any idea why it would ignore the where clause in the presence of an order by?
Thanks

My output:
SQL*Plus: Release 10.2.0.1.0 - Production on Fri Mar 31 13:50:54 2006
Copyright (c) 1982, 2005, Oracle. All rights reserved.
Connected to:
Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Production
With the Partitioning, OLAP and Data Mining options
SQL> select (select dname from (select dname from scott.dept d where d.deptno = e.deptno order by dname) t where rownum = 1) dname, e.* from scott.EMP e;
DNAME EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
ACCOUNTING 7369 SMITH CLERK 7902 17-DEC-80 800 20
ACCOUNTING 7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
ACCOUNTING 7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
ACCOUNTING 7566 JONES MANAGER 7839 02-APR-81 2975 20
ACCOUNTING 7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
ACCOUNTING 7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
ACCOUNTING 7782 CLARK MANAGER 7839 09-JUN-81 2450 10
ACCOUNTING 7788 SCOTT ANALYST 7566 19-APR-87 3000 20
ACCOUNTING 7839 KING PRESIDENT 17-NOV-81 5000 10
ACCOUNTING 7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
ACCOUNTING 7876 ADAMS CLERK 7788 23-MAY-87 1100 20
ACCOUNTING 7900 JAMES CLERK 7698 03-DEC-81 950 30
ACCOUNTING 7902 FORD ANALYST 7566 03-DEC-81 3000 20
ACCOUNTING 7934 MILLER CLERK 7782 23-JAN-82 1300 10
14 rows selected.
SQL> select (select dname from (select dname from scott.dept d where d.deptno = e.deptno) t where rownum = 1) dname, e.* from scott.EMP e;
DNAME EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
RESEARCH 7369 SMITH CLERK 7902 17-DEC-80 800 20
SALES 7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
SALES 7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
RESEARCH 7566 JONES MANAGER 7839 02-APR-81 2975 20
SALES 7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
SALES 7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
ACCOUNTING 7782 CLARK MANAGER 7839 09-JUN-81 2450 10
RESEARCH 7788 SCOTT ANALYST 7566 19-APR-87 3000 20
ACCOUNTING 7839 KING PRESIDENT 17-NOV-81 5000 10
SALES 7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
RESEARCH 7876 ADAMS CLERK 7788 23-MAY-87 1100 20
SALES 7900 JAMES CLERK 7698 03-DEC-81 950 30
RESEARCH 7902 FORD ANALYST 7566 03-DEC-81 3000 20
ACCOUNTING 7934 MILLER CLERK 7782 23-JAN-82 1300 10
14 rows selected.
SQL>

Similar Messages

  • Does the Order of the tablesjoins in Where clause matter in ORDERED hint?

    The ORDERED hint requests that the tables listed in the FROM clause of a SQL statement be joined in the order specified. But does the order of the join in "where" clause matters?
    Will be there any performance difference between below query? The order of the table in the FROM clause remains the same, but there is a difference in the order of conditions in the WHERE clause
    SELECT /*+ ORDERED */ a.fp_i f
    FROn iw_owner.revenue_fpct b,
    dw_owner.fp_dinn c,
    dw_owner.nanaged_at_dinn a,
    dw_owner.at_dinn_curr d,
    iw_owner.na_progran e,
    dw_owner.fp_dinn_curr f,
    dw_owner.fpn_of_at_dinn g
    WHERE a.nacc_dinn_i = b.nacc_dinn_i
    AND b.fp_dinn_i = c.fp_dinn_i
    AND a.acc_i = d.acc_i
    AND a.acc_nacc_c = e.npn_pro_c
    AND a.fp_i = f.fp_i
    AND b.org_fpn_dinn_i = g.org_fpn_dinn_i(+)
    AND c.fp_i IN ('JG 04')
    AND b.dte_dinn_i BETWEEN '1-Apr-2011' and '30-Apr-2011'
    SELECT /*+ ORDERED */ a.fp_i f
    FROn iw_owner.revenue_fpct b,
    dw_owner.fp_dinn c,
    dw_owner.nanaged_at_dinn a,
    dw_owner.at_dinn_curr d,
    iw_owner.na_progran e,
    dw_owner.fp_dinn_curr f,
    dw_owner.fpn_of_at_dinn g
    WHERE c.fp_i IN ('JG 04')
    AND b.dte_dinn_i BETWEEN '1-Apr-2011' and '30-Apr-2011'
    AND b.fp_dinn_i = c.fp_dinn_i
    AND a.nacc_dinn_i = b.nacc_dinn_i
    AND a.acc_i = d.acc_i
    AND a.acc_nacc_c = e.npn_pro_c
    AND a.fp_i = f.fp_i
    AND b.org_fpn_dinn_i = g.org_fpn_dinn_i(+)
    Thanks

    Gangadhar Reddy wrote:
    Does it matter the order of first 2 tables?This question makes me really wonder. It's fairly easy to see how explain changes when using hints.
    Your question indicates that you do not look at explain plans?
    Then why are you asking about hints in the first place?
    Using hints is something you do when you want to force a specific execution plan as part of some investigation, because you know something that the optimizer does no, or you have found a bug in the optimizert.
    In all cases you know exactly what you are doing.
    The /*+ ORDERED */ is all about you telling the optimizer to join the tables in the order you specified them in the from clause.
    As to your original question, there exists a similar ORDERED_PREDICATES hint.
    Regards
    Peter

  • Dynamic Order by with user defined Where clause...

    Hello!
    I have a block based on a table, with no order by set and no where clause.
    The block is queryable so users can filter the data to be retrieved.
    Each of the columns on the form have a button above which requeries the block, applying the order by (SET_BLOCK_PROPERTY ( 'B12', ORDER_BY, :bc1.h_b12_custom_orderby ); )
    The problem is that each time the block is requeried the user definied filter criteria is lost. Is there any way I can get a handle on this and maintain the filtering?
    GET_BLOCK_PROPERTY(item, DEFAULT_WHERE); only retrieves the query entered while in design mode so this won't work.
    I'm using Oracle Forms 6i, web based. Any suggestions are very much appreciated.
    Thanks in advance,
    Jay

    Many thanks for your response Hedy,
    Below is the procedure I used to achieve this.
    I found GET_BLOCK_PROPERTY ( p_block, LAST_QUERY ) worked better than :SYSTEM.last_query. As the first time it is called within a block :SYSTEM.last_query returned the query made in another block - which I'm sure has it's applications.
    Thanks again,
    Jay
    PROCEDURE set_last_query_where ( p_block IN VARCHAR2
    , p_where IN VARCHAR2 DEFAULT NULL )IS
    l_last_query VARCHAR2(10000);
    l_last_where VARCHAR2(10000);
    BEGIN
    IF p_where IS NULL THEN
    l_last_query := UPPER(GET_BLOCK_PROPERTY ( p_block, LAST_QUERY ));
    l_last_where := SUBSTR ( UPPER ( l_last_query),
    INSTR ( l_last_query, 'WHERE')+6, INSTR(SUBSTR(UPPER(l_last_query), INSTR(l_last_query, 'WHERE')+8), 'ORDER BY'));
    ELSE
    l_last_where := p_where;
    END IF;
    SET_BLOCK_PROPERTY ( p_block, DEFAULT_WHERE, l_last_where );
    EXCEPTION
         WHEN FORM_TRIGGER_FAILURE THEN
         ref_raise_ftf;
         WHEN OTHERS THEN
         ref_others( 'P-SLQW' );
    END;

  • In which order does the query's where clause condition is checked

    Hi All,
    can anyone tell me in which order does oracle evaluate the where clause condition?
    for ex: select * from users where user_type='Admin' and stauts='Enabled'

    user9981103 wrote:
    The conditions in the WHERE clause are checked in the reverse order of the given order.
    i.e; first it will check stauts='Enabled'* and then user_type='Admin'* for your given queryWhy do you believe that?
    If there is a sufficiently selective b-tree index on USER_TYPE, the optimizer would undoubtedly use that index to process the USER_TYPE = 'Admin' condition and then check the STATUS column.
    If there is a sufficiently selective b-tree index on STATUS, the optimizer would undoubtedly use that index to process the STATUS='Enabled' condition and then check the USER_TYPE column.
    If there is a composite b-tree index on (STATUS, USER_TYPE), the optimizer would use that index to process the two conditions nearly simultaneously, though technically the leading column of the index is evaluated first. Of course, if you reverse the order of columns in the index, you get a different evaluation order
    If there are bitmap indexes on STATUS and USER_TYPE, Oracle can combine the two indexes and evaluate the two conditions simultaneously.
    And that is leaving out tons of query plan options and other optimizer wrinkles.
    Justin

  • Update query running fine when subquery in where clause is wrong.

    Hi,
    I am running one update statement-
    Update table a set column1=2000
    where a.column2 in(select col 3 from Table b where b.col4=111)
    Now when I run the subquery: select col 3 from Table b where b.col4=111-----> It gives me error "col 3 invalid identifier"
    But when I run the full query then it updates the 700 rows.
    Can somebody please explain this?
    My subquery is throwing error but when i use that in another query it is running fine.

    Col_3 must be in your outer table (table_a, I guess).
    If you always prefixed column names with a table alias, you'd know in an instant.

  • WHERE clause order ox execution question

    I dont understand order of execution of a WHERE clause, using a complex database
    I want to write a SELECT statement with the following condition
    ... WHERE ( branch = 'main' ) AND ( type = 1 ) OR ( charge -1 AND charge = 2 )
    My question is
    <1> Can yoyu use parenthesis inside of a WHERE clause
    <2> How would you write such a clause as above if you can not use parenthesis
    Thanks

    Just to echo what everyone else is saying, of course parentheses are syntactically valid and can make a difference to the logic. In you example though,
    WHERE ( branch = 'main' ) AND ( type = 1 ) OR ( charge {noformat}<{noformat}> -1 AND charge <= 2 )is the same thing as
    WHERE ( branch = 'main' AND type = 1 ) OR ( charge {noformat}<{noformat}> -1 AND charge <= 2 )and even
    WHERE branch = 'main' AND type = 1 OR charge {noformat}<{noformat}> -1 AND charge <= 2because AND takes precedence over OR. You can think of it as a "stronger" operator.
    However I would not use the last version because it's ambiguous to anyone reading it, and code like that can easily hide bugs. I would also not use the first version because all those redundant brackets are just confusing, making it almost as hard to read (and therefore prone to bugs) as the last version.
    btw I've changed your example because I know this forum can swallow *{noformat}<{noformat}>* (I've used {noformat} tags to preserve it).
    I'm not sure if any of this affects order of execution (and if it does, your Oracle version will make a difference).

  • Where clause of SubQuery

    Hello!I beg your pardon for my poor English.
    Oracle prompts "invalid month" when running the following sentence:
    select *
    from xtcs xtcs
    where xtcs.csmc like '%month'
    and (xtcs.cnq,xtcs.csmc) not in (
    select distinct
    to_char(add_months(to_date((case when substr(yhjf1.pzh,1,2)>='50' then '19' else '20' end)||substr(yhjf1.pzh,1,4),'yyyymm'),-4),'yyyy') pzcnq
    ,yhjf1.pzhbs||'month'
    from yhjf yhjf1
    where yhjf1.pzhbs is not null);
    But,oracle runs well when running only the subquery in where clause:
    select distinct
    to_char(add_months(to_date((case when substr(yhjf1.pzh,1,2)>='50' then '19' else '20' end)||substr(yhjf1.pzh,1,4),'yyyymm'),-4),'yyyy') pzcnq
    ,yhjf1.pzhbs||'month'
    from yhjf yhjf1
    where yhjf1.pzhbs is not null;
    I have checked the data in the table yhjf.And there are some wrong about field pzh which cause oracle wrong .But the where clause 'yhjf1.pzhbs is not null' can filter them out.I'm being in puzzle now.Please tell me why and how I can do.Thanks very much!

    > Sorry,I'm a Chinese.The names originally were in
    Chinese.I converted them into alphabets before posting.
    I did not think of that option. I'm glad to hear that the names are meaningful to you :-)
    > My data is very large and I had not created a
    small data set on which the error happens.
    To know what the problem is, you will have to identify the rows that are causing the trouble. Once identified, the solution should be simple.
    Regards,
    Rob.

  • Order in where clause - SQL statement

    Hi,
    The order of the fields in Where clause in OpenSQL statements is important to get the right index?
    Select a b c from t1
    where 
    d = p_d and
    e = p_e
    Or
    Select a b c from t1
    where 
    e = p_e and
    d = p_d
    Index:
    columns e and d.
    Thanks !

    HI,
      Both will give you the same result.. but it is always good to pass the sequence as in the table.. the performance will be good when you follow the sequece of occurance of the fields.
    Thanks
    Mahesh

  • Issue with where clause

    Hi All,
    I am trying to combine a subquery in where clause but could not get it to work. Does anyone have better idea how can i achieve this?
    >
    select l.olic_id, l.olic_key, o.trading_name , p.name, l.olic_term, l.expire_date, l.status
    from table1 l, table2 o, table3 p, table4 a
    where l.cop_id=o.cop_id
    and o.par_id=p.par_id
    and l.olic_id=a.olic_id and ( select scripts from tb_scripts where dst_id=66)
    >
    Sub query in the where clause return -
    AB is not null or BC is not null or AC is not null or CA is not null or DE is not nullThe region I want to use subquery because it contains more than 60 columns for each dst_id.
    Please give me some suggestion. I hope this make sense.
    Regards,
    Tajuddin

    Here is my table structure -
    CREATE TABLE TB_SCRIPTS
      DST_ID    NUMBER,
      SCRIPTS   VARCHAR2(500 BYTE)
    )Sample data for TB_SCRIPTS table -
    dst_id     scripts
    66     AB is not null or BC is not null or AC is not null or CA is not null or DE is not null
    65     AB is not null or CA is not null or DE is not null
    67     CA is not null or DE is not nulltable structure for TABLE4 -
    CREATE      TABLE      TABLE4
    PK_ID      NUMBER,
    OLIC_ID      NUMBER,
    AB      VARCHAR2(200),
    BC      VARCHAR2(200),
    AC      VARCHAR2(200),
    CA      VARCHAR2(200),
    DE      VARCHAR2(200),
    EF      VARCHAR2(200)
    )OLIC_ID is the foreign key in this table referencing table1.
    sample data for TABLE4 -
    pk_id     olic_id     AB     BC     AC     CA     DE     EF
    1     123     6     2          8     
    2     23          9     2     0     1
    3     123     0     2     1          7
    4     44                              7
    5     12     8     1                    8Table1 structure -
    CREATE      TABLE      TABLE1
    OLIC_ID      NUMBER,
    OLIC_KEY      VARCHAR2(20),
    OLIC_TERM      VARCHAR2(20),
    EXPIRE_DATE      DATE,
    STATUS      VARCHAR2(60)
    )Some sample data -
    OLIC_ID     OLIC_KEY     OLIC_TERM     EXPIRE_DATE     STATUS
    123     TR42332          1 Year          12/06/2010     Current
    154     TR43232          2 Years          24/08/2011     Current     
    122     TR32422          2 Months     23/01/2009     ExpiredOther tables are not necessary to include here. Basically TABLE1 and TABLE4 joining to retrieve data here. Hope this make sense.
    Regards,
    M Tajuddin

  • Where clause priority in Select Query

    Hi All,
    I have one doubt, Pls clarify
    SELECT empno, ename, sal, comm
    FROM emp E, dept D -- (deptno is pk for DEPT)
    WHERE D.deptno = E.deptno
    AND E.sal >= 3000
    In WHERE clause which one will execute first (right to left or left to right
    OR[b] First join conditions then after filter conditions or vice versa)
    D.deptno = E.deptno
    OR
    E.sal >= 3000
    (this is the example tables)
    Because I have large volume of data with 5 tables with joins
    so, pls. kindly give me the sugession for where clause.
    Thanks
    Naresh

    It depends, the order the where clause is written in makes no difference to how the statement is processed.
    In the section on Developing Efficient SQL Statements in the Performance Tuning Guide changing the order of statements in the where clause is notably missing.
    There is more information in the Understanding Joins section of the same manual.

  • Where clause and joins

    HI all,
    If i Have a select statement that needs two different tables
    and a where clause with only 1 join and the rest of conditions dependent on only 1 table such as:
    select .... from table a, table b
    where a.col1 = b.col1
    and b.col2 some condition
    and b.col3 some condition;
    is it better/optima for performancel for me to have the join right at the beginning of the where clause or after table b has been filtered out such as:
    select ... from table a, table b
    where b.col2 some condition
    and b.col3 some condition
    and a.col1 = b.col1

    Hi,
    The order of conditions in a WHERE clause doesn't effect performance; the Cost-Based Optimizer will decide how to perform them.
    The order can make a difference on how easy it is to understand and maintain the code. I find ANSI join syntax far better for this:
    select      ...
    from      table      a
    join     table      b     on     a.col1     = b.col1
    where      b.col2  <some condition>
    and      b.col3  <some condition>
    ;

  • JSP, DataWebBean: How to dynamically set the where clause of query and display record

    Hi,
    I am reposting this question as per suggestions made by Mr. Dwight.
    I have used ViewCurrentRecord web bean to display records from EMP table. I have to use the Dept_Id_FK from the current
    record of the EMP table to display corresponding records of Dept table. I have a view object called DeptView in my Business
    Components which selects all the records from the Dept table.
    How do I get the value of Dept_Id_FK and use it to display the required records of the Dept table?
    I tried to declare a variable and get the value of Dept_Id_FK but it did not work. My code is as follows:
    <%! String m_DeptId = null; %>
    <jsp:useBean id="RowViewer" class="oracle.jbo.html.databeans.ViewCurrentRecord" scope="request">
    <%
    RowViewer.initialize(pageContext, "EMPApp_EMP_EMPAppModule.EMPView1");
    RowViewer.setReleaseApplicationResources(false);
    RowViewer.getRowSet().next();
    m_DeptId = (String)RowViewer.getRowSet().getCurrentRow().getAttribute("DeptIdFk");
    %>
    </jsp:useBean>
    Thanks.
    null

    First of all, Thank you very much for making use of the new topic format. It is very much appreciated.
    As for your question, I think there are several different ways to accomplish what I think you want to do.
    1. Create a view object that includes both Emp and Dept entities and join them there. In this case, your query would look something like this:
    Select e.empno,e.name,...,d.dname,d.loc from emp e, dept d
    where e.deptno = d.deptno
    You should be able to create a JSP off of this view object that contains both the employee and department information. In this case, BC4J takes care of the foreign key to primary key coordination.
    2. In order to set a dynamic where clause for a view, you need to do the following in your usebean tag:
    rsn.initialize(application,session, request,response,out,"DeptView");
    rsn.getRowSet().getViewObject().setWhereClause("deptno=" &#0124; &#0124; m_DeptId);
    rsn.getRowSet().getViewObject().executeQuery();
    rsn.getRowSet().first();
    You will need to do this in a separate usebean tag from the EmpView, since the usebean can only initialize one view object.
    In other words, you would have your ViewCurrentRecord bean tag for the EmpView, then a separate one for the DeptView where you use the above code to set the where clause to display just the information for the department you want.
    Another option, but one I'm not sure would work as well, is to create a master-detail JSP to do this for you. Usually a master-detail is a one-to-many (one department to many employees). Your request appears to be the reverse, but might still be doable using the same mechanism.
    You set up relationships between views in your BC4J project using View Links. If you used the BC4J project wizard and created default views, some of these links may have been created for you. They are created when BC4J detects a foreign key to primary key relationship in the database.
    You can create your own View Links using the View Link wizard. Select your BC4J project node and choose Create View Link... from the context menu. You will be asked to select a source view (Emp), and a target view (Dept), then select the attribute in each view that related the two of them (deptno).
    Next, you need to reflect this new relationship setting in your application module. Select your app module and choose Edit from the context menu. On the data model page, select the EmpView node in the Selected list. Now select the DeptView node in the available list and shuttle it over. You should see DeptView1 via yourlink appear indented under the EmpView node. Save and rebuild your BC4J project to reflect the changes.
    In your JSP project, you can now have the wizard create a master-detail form for you based on DeptView1.
    Let me know if the above answers your question, or if I have misunderstood what it is you wanted to do.
    null

  • Subquery in the Where clause

    Can I put a subquery in the where clause, on the left side on the operator?
    This is a multi-row query.
    Like this,
       select a.col1, a.col2, b.col1, b.col2,
                 my_function(a.date1, b.date2) AS GROSSDAYS
       from table1 a
       where ( select ( a.date1 - b.date2 ) as range
                   from     table1 a
                   join      table2 b
                   on       a.col3 = b.col3
                   where rownum =1
                   in ( 1,2,3)
    and  a.col1 = b.col2I need to use a subquery because the column I need does not exist in the table, and I cannot make any changed to the table structure.
    Is what I'm doing possible?
    The subquery is the same as the function I have in the Select clause.

    I tried a subquery in the where clause, but now I'm getting a missing expression error!
       SELECT
            r.complete_flag, r.order_num, r.referral_num, TRUNC(r.referral_datetime) AS referral_datetime,
            r.clinic_specialty, a.appointment_datetime, TRUNC(a.appointment_date_made) AS appt_datemade, a.appointment_status_id,
             scref.scr_rules.calcatcdays(r.referral_datetime,a.appointment_date_made) AS ATCDays  -- returns difference between two dates
    FROM
            referral r,
                                 ( SELECT referral_num,appointment_datetime, appointment_date_made, appointment_status_id
                                      FROM   ( SELECT referral_num, appointment_datetime, appointment_date_made, appointment_status_id,
                                                ROW_NUMBER() OVER (PARTITION BY referral_num
                                                ORDER BY appointment_datetime) rn
                                            FROM   appointment
                                     WHERE rn = 1
                             a
    WHERE r.order_num IS NOT NULL
    AND   ( SELECT adays                      -- THIS IS WHERE I'M GETTING A MISSING EXPRESSION ERROR!!!
           FROM ( SELECT scref.scr_rules.calcatcdays(r.referral_datetime,a.appointment_date_made) AS adays
                    FROM referral r
                     JOIN appointment a
                     ON   a.referral_num = r.referral_num
                     WHERE ROWNUM = 1
           WHERE  adays
          ) = 3
    AND   r.referral_num = a.referral_num(+)
    AND   TRUNC(r.referral_datetime) >= TO_DATE('01-JUL-05','DD-MON-YY')
    AND   TRUNC(r.referral_datetime) <= TO_DATE('31-JUL-05','DD-MON-YY')

  • Where clause problem in a subquery

    I'll try to explain as detailed as possible.
    Given the following set of data and the parameters passed the query must only return one row;
    If the structure_chain is like the parameter passed, then select that row
    If not then strip out the first number in both the parameter and the column,
    e.i., '2.35364194.34889485' becomes '35364194.34889485'
    The select is what is currently in the code and so far I've not been able to get the (new) desired results - customer changed/enhanced requirements
    with TT as
        (select 1 row_no, 22794978 old_child_id, 51755902 new_child_id, '1.35364194' structure_chain from dual union all
         select 2, 22794978, 51755899, '1.23576950' from dual union all
         select 3, 17872962, 51755893, '1.23576950' from dual union all
         select 4, 17872962, 51756065, '1.35364194.34880851' from dual union all
         select 5, 17872962, 51759249, '2.35364194.34880851' from dual union all
         select 6, 17872962, 51759248, '1.23576950.22795468' from dual union all
         select 7, 17872962, 51759250, '2.23576950.22795468' from dual )
    select * from tt
    where old_child_id = &1
    and   &2 like structure_chain ||'%'
    17872962 '2.35364194.34880851'   -- Return row_no 5 
    17872962 '1.23576950.22795468'   -- Return row_no 6 - this returns more than one
    17872962 '1.35364194.34880851'   -- Return row_no 4
    17872962 '2.23576950.22795468'   -- Return row_no 7
    22794978 '2.35364194.34889485'   -- Return row_no 1 - does not return anything
    22794978 '1.35364194.34889485'   -- Return row_no 1

    Hi,
    I'm not sure what you're asking.
    It would help if you posted the results you want as clearly as you posted the sample data. For each set of parametes, post the desired result set.
    I think you want to do two kinds of pattern matches, and return the results of the strictest one that has results.
    That is, if there is a match on all parts of structure_chain, then return the rows that match all parts.
    But if there is no match on all parts of structure_chain, then return the rows (if any) that match if we ignore the sub-atring before the first dot.
    That's an example of a Top-N Query , and here's one way to do it:
    WITH     got_r_num AS
         SELECT  tt.*
         ,     DENSE_RANK () OVER (ORDER BY  CASE
                                                WHEN  '&2'        LIKE structure_chain || '%'
                                    THEN  1
                                    ELSE  2
                                            END
                           ) AS r_num
         FROM     tt
         WHERE      old_child_id     = &1
         AND        SUBSTR ( '&2'
                     , INSTR ('&2', '.')
                     )                LIKE SUBSTR ( structure_chain
                                                  , INSTR (structure_chain, '.')
                                      ) || '%'
    SELECT     row_no, old_child_id, new_child_id, structure_chain
    FROM     got_r_num
    WHERE     r_num     = 1
    ;With parameters &1=17872962 and &2=1.23576950.22795468, the query above produces this output:
    `   ROW_NO OLD_CHILD_ID NEW_CHILD_ID STRUCTURE_CHAIN
             3     17872962     51755893 1.23576950
             6     17872962     51759248 1.23576950.22795468because both rows matched the given &2, including the '1.' at the beginning. (The query you posted gave the same results in this case.)
    With parameters &1=22794978 and &2=2.35364194.34889485, the query above produces:
        ROW_NO OLD_CHILD_ID NEW_CHILD_ID STRUCTURE_CHAIN
             1     22794978     51755902 1.35364194because there was no match when considering the '2.' at the beginning of &2, but the row shown does match when we ignore the '2.'.
    The WHERE clause in the sub-query narrows the result set down to rows that meet at least the looser match reuirement.
    The CASE expression ranks each row as 1 if it meets the stricter requirement, and 2 if it only met the looser one.
    DENSE_RANK returns 1 for the lower of those numbers that was actually found.

  • DECODE is not working in WHERE clause when subquery returns more rows

    Hi Gurus,
    I want to write a query on CCENTERS table(Script given below) and expect the following result:
    1. When I pass a value of 0 for ID, It returns all the rows given in the table.
    2. When I pass a value other than 0, It returns the row for the given value as well as all its child records.
    CCENTER has parent-child relationship in ID and BASE column. I am using a query with DECODE function. but DECODE function in WHERE clause is not capable of handling sub-query with multiple rows.
    VARIABLE ParaCCenter NUMBER
    BEGIN
    :paraccenter:=0;
    END;
    CREATE TABLE ccenters
    (id NUMBER,
    name VARCHAR2(20),
    base number);
    INSERT INTO ccenters VALUES(1,'NUST',null);
    INSERT INTO ccenters VALUES(2,'SEECS',1);
    INSERT INTO ccenters VALUES(3,'NBS',1);
    commit;
    SELECT * FROM ccenters
    WHERE id IN DECODE(:ParaCCenter, 0, id,
    (SELECT id FROM ccenters
    START WITH base=:ParaCCenter
    CONNECT BY PRIOR id = base
    UNION
    SELECT :ParaCCenter FROM dual
    BEGIN
    :paraCCenter:=1;
    END;
    SELECT * FROM ccenters
    WHERE id IN DECODE(:ParaCCenter, 0, id,
    (SELECT id FROM ccenters
    START WITH base=:ParaCCenter
    CONNECT BY PRIOR id = base
    UNION
    SELECT :ParaCCenter FROM dual))
    The result is
    (SELECT id FROM ccenters
    ERROR at line 3:
    ORA-01427: single-row subquery returns more than one row
    How this query can be rewritten for the given functionality. Any response will be highly appreciated.
    Thanks

    And if you want to use DECODE:
    SQL> BEGIN
      2  :paraccenter:=0;
      3  END;
      4  /
    PL/SQL procedure successfully completed.
    SQL> select  *
      2    from  ccenters
      3    where :paraccenter = decode(:paraccenter,0,0,id)
      4  /
            ID NAME                       BASE
             1 NUST
             2 SEECS                         1
             3 NBS                           1
    SQL> BEGIN
      2  :paraccenter:=2;
      3  END;
      4  /
    PL/SQL procedure successfully completed.
    SQL> select  *
      2    from  ccenters
      3    where :paraccenter = decode(:paraccenter,0,0,id)
      4  /
            ID NAME                       BASE
             2 SEECS                         1
    SQL> SY.

Maybe you are looking for

  • Condition AZWR value = 0

    Hi, I am trying to configure the standard down payments but I have the following questions: 1º ) I have configured the condition type AZWR with all the requirements from the manual, condition 2 and the calculation formula 48 but I donu2019t know whic

  • Authorization Issue for Object CRM_ORD_PR

    Dear All, When user search sales orders in PCUI by sales org, Distributional Channel and Division criteria it shows the result list. But it is also throwing the error as "You are not authorized to Display this transaction" I am not sure why system is

  • CrystalReports.msi problems

    Hi, Everyday for the last 3 weeks I get a pop up window stating that there is a new patch/update for Crystal Reports XI Release 2. I have downloaded this patch/update but when it installs the following things occur. A window appears with the followin

  • Ping command is not working on server 2008 r2

    Arvind

  • Language translation widget

    Hello, I'm looking for a language translation widget. I searched a lot many mac sites / forums and was not sucessfull finding a (free) translation widget (like Babel for windows) I'm looking at English / French & German. Any hints? regards,