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

Similar Messages

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

  • The issue with using the multiple columns sub-query in WHERE clause

    Hi All,
    my database version is 10.2.
    the problem i am trying to deal with is that when I use multiple column sub-query in the WHERE clause of the SELECT statement, the actual row number returned from the sub-query is different from the whole statement.
    And what I found is that, whenever there is NULL in any of those columns returned from the SUB-QUERY, the outer query will just return NULL for that whole row.
    Here is an example:
    select empno, ename, job, mgr, hiredate, sal, deptno from EMP
    intersect
    select empno, ename, job,  mgr, hiredate, sal, deptno from t;
    7782     CLARK     MANAGER     7839     09-JUN-81     2450     10
    7839     KING     PRESIDENT  NULL  17-NOV-81     5000     10
    7934     MILLER     CLERK     7782     23-JAN-82     1300     10
    select * from EMP where (EMPNO, ENAME, job, MGR, HIREDATE, SAL, DEPTNO) in (
    select empno, ename, job, mgr, hiredate, sal, deptno from EMP
    intersect
    select empno, ename, job,  mgr, hiredate, sal, deptno from t);
    7782     CLARK     MANAGER     7839     09-JUN-81     2450          10     
    7934     MILLER     CLERK     7782     23-JAN-82     1300          10     If I specifically deal with the NULL situations for the columns which might return NULL, I can get the result right.
    select * from EMP where (EMPNO, ENAME, job, NVL(MGR,-1), HIREDATE, SAL, DEPTNO) in (
    select empno, ename, job, nvl(mgr,-1), hiredate, sal, deptno from EMP
    intersect
    select empno, ename, job,  nvl(mgr,-1), hiredate, sal, deptno from t);
    7782     CLARK     MANAGER     7839     09-JUN-81     2450          10     
    7839     KING     PRESIDENT  null   17-NOV-81     5000          10     
    7934     MILLER     CLERK     7782     23-JAN-82     1300          10     the problem is that, I feel this is a very lame way of handling it.
    So, I wonder or am asking if there is any better or standard way to do it?
    any help would be highly appreciated.
    Thanks

    Hi,
    As you discovered, INTERSECT treats NULL as a value, but IN does not.
    What you did with NVL is one way to handle the situation. If there was a chance that any of the columns could be NULL, then you might prefer something like this:
    select      *
    from      EMP
    where      ( EMPNO      || '~' ||
           ENAME      || '~' ||
           job           || '~' ||
           MGR           || '~' ||
           TO_CHAR (HIREDATE, 'DD-MON-YYYY HH24:MI:SS')
                    || '~' ||
           SAL           || '~' ||
           DEPTNO
         ) in (
              select  EMPNO      || '~' ||
                     ENAME      || '~' ||
                   job     || '~' ||
                   MGR     || '~' ||
                   TO_CHAR (HIREDATE, 'DD-MON-YYYY HH24:MI:SS')               
                        || '~' ||
                   SAL      || '~' ||
                   DEPTNO
              from     emp
             intersect
              select  EMPNO      || '~' ||
                     ENAME      || '~' ||
                   job     || '~' ||
                   MGR     || '~' ||
                   TO_CHAR (HIREDATE, 'DD-MON-YYYY HH24:MI:SS')               
                        || '~' ||
                   SAL      || '~' ||
                   DEPTNO
              from      t
             );This assumes that you can identify some string (I used '~') that never occurs in the strings in these tables.
    This is implicitly converting the NUMBERs. That's usually not a good thing to do. but explicitly converting them would make this even more tedious.
    You should explicitly convert any DATEs to strings, however. Depending on your default format, and your data, you might get away with implicit conversions even for DATEs, but don't bet on it.
    If you had to do this often, you might consider writing a user-defined function:
    delimited_string (empno, ename, job, mgr, hiredate, sal, deptno) would return a string like
    '7839~KING~PRESIDENT~~17-NOV-1981~5000~10'
    This will make the coding easier, but beware: it will make the execution slower.

  • WHERE clause affects sort order???

    Hi,
    I'm playing around with linguistic sorting and comparing and was using the examples from
    http://download.oracle.com/docs/cd/B19306_01/server.102/b14225/ch5lingsort.htm#g1018324
    So I have the three entries Große, große and Grosse in my table (the sample data from the manual)
    To test these features, I did
    alter session set nls_comp = Linguistic;
    alter session set nls_sort = XGerman_CI; and ran the following select statement:
    SELECT name
    FROM words
    ORDER BY 1;The rows are then returned in the following order:
    Große
    große
    Grosse
    which is exactly what I expect.
    When I run
    SELECT name
    FROM words
    WHERE name = 'Grosse'; it returns all three rows which is expected as well.
    When I add the ORDER BY (which is the same ORDER BY as in the first step):
    SELECT name
    FROM words
    WHERE name = 'Grosse'
    ORDER BY 1; the rows are returned in the following order
    Große
    Grosse
    große
    which is different to the order without the WHERE clause (and wrong)
    The question is: why does the WHERE clause affect the ordering?

    I'm not sure why you think the third sort order is incorrect. In English, the capitals will sort before the lower case leaving both "G" values before the "g". I don't know where the special ... German? ... character will appear but assume that ORDER BY is sorting correctly. If not you need to contact Oracle and open a support ticket.
    WHERE clauses will affect how data comes back by influencing index use, but some of what they do will be random. The only way to be sure data will be returned in a certain order is to use an ORDER BY clause.
    In particular, in 10g the parallel query option is notorious for returnding data in random order. Where in 9i an indexed lookup would tend to return data in an imaginary sorted order the same query using PQO in 10g often returns data in random order.

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

  • How do I use the IF-ELSE condition in a WHERE clause?

    I want to merge the condition results of my 2 If statements. First if statement result shows only both 0 result, in second if statement result one of them has to be bigger than 0... 
         If (Inventory) <> 0 Then
            If Apple = "" And Banana = "" Then
         strSQL = strSQL & " AND (myApple = 0 AND myBanana = 0)"
      End If
      End If
         If int(Inventory) <> -1 Then
      If Apple = "" And Banana = "" Then
         strSQL = strSQL & " AND (myApple <> 0 OR myBanana <> 0)"
      End If
      End If
    **Want to get something like this**
         If int(Inventory) <> 0 Then
                If Apple = "" And Banana = "" Then
           strSQL = strSQL & " AND ((myApple = 0 AND myBanana = 0) AND (myApple <> 0 AND myBanana <> 0))"
        End If
        End If
        If int(Inventory) <> -1 Then
        If Apple = "" And Banana = "" Then
           strSQL = strSQL & " AND (myApple <> 0 AND myBanana <> 0)"
        End If
        End If
       myApple myBanana
             0       0
             0       0
             0       5
             1       0
             6       0
             0       0
          continue.....

    Maybe
    with
    fruits as
    (select null apple,null banana from dual union all
    select 'Golden Delicious','Chiquita' from dual union all
    select 'Granny Smith',null from dual union all
    select null,'Cavendish' from dual
    select apple,banana,nvl2(apple,1,0) * nvl2(banana,1,0)
      from fruits
    APPLE
    BANANA
    NVL2(APPLE,1,0)*NVL2(BANANA,1,0)
    0
    Golden Delicious
    Chiquita
    1
    Granny Smith
    0
    Cavendish
    0
    Regards
    Etbin

  • Different order in the results

    I have a problem with order consistency in the data set on the screen vs. the sequence of records being selected one by one behind the screen.
    Say, in the first form I select certain "where clause" and several "order by". I pass parameters to the second form, compile query in runtime and start bringing records into the form for update, one by one. That's when the original first screen order is being messed up.
    Say, we have a group of records sorted by type, received_date. The set on the screen (user can only 2,3 and 4th columns) and in SQL*Plus would display:
    Rownum     Unique # Type     Date
    11     100 E     10/10/2005
    13     103 E     10/10/2005
    12     102 E     10/10/2005
    14     104 E     10/10/2005
    15     105 E     10/10/2005
    Records retrieved by the second screen via cursor, one by one, would appear in the following order:
    Rownum     Unique # Type     Date
    11     100 E     10/10/2005
    12     102 E     10/10/2005
    13     103 E     10/10/2005
    14     104 E     10/10/2005
    15     105 E     10/10/2005
    Basically, Oracle adds rownum as a last Order by to the customized Order By. Has anyone run into the similar problem and what did you do to fix it?

    And Rownum is an internal number that is applied AFTER the rows are sorted, so no matter how you order your records, Rownum will always start with 1.
    Does my result have something to do with subquery?
    SELECT rownum, unique#, report_type, received_date
    FROM table x
    WHERE condition blah-blah-blah
    AND unique# IN (subquery from table y)
    ORDER BY report_type ASC, received_date DESC
    My query above gives the result as follows:
    rownum unique# report_type received_date
    1     4630093     E     4/8/2005
    2     4630095     E     4/8/2005
    3     4630096     E     4/8/2005
    11     4629916     E     4/8/2005
    4     4630099     E     4/8/2005
    62     4631257     E     4/8/2005
    64     4631286     E     4/8/2005
    66     4631288     E     4/8/2005
    68     4631290     E     4/8/2005
    218     4630693     E     4/8/2005
    196     4630163     E     4/8/2005
    195     4630599     E     4/8/2005
    194     4630580     E     4/8/2005
    193     4631309     E     4/8/2005
    192     4631308     E     4/8/2005
    191     4631307     E     4/8/2005
    167     4630012     E     4/8/2005
    166     4630011     E     4/8/2005
    165     4629997     E     4/8/2005
    164     4629996     E     4/8/2005
    163     4629989     E     4/8/2005
    162     4630574     E     4/8/2005
    67     4631289     E     4/8/2005
    65     4631287     E     4/8/2005
    63     4631259     E     4/8/2005
    And then when retrieving one by one sorts by rownum (or unique #)

  • Dynamically changing the WHERE clause in detail VO in Master Detail

    Hi, I want to develop a search functionality, results will be in a table, which will have an inline table displaying the details per row found.
    I have a MD defined trough viewlink. I do change the master VO at runtime (set the entire SQL), based on the criteria entered by the user.
    Is there a way to change the VO at the detail end of the link at runtime - that is what I haven't been able to do.
    I have read that the ADF framework creates internal VO for each master row, whenever accessed trough accessor (which is not I am trying to do). I haven't been able to find a way to get a hold of the REAL VO at the detail end and have its WHERE clause changed.
    Changes to the "VO instance in AM" (same one used as a definition in the detail end in the ViewLink def) does not seem to reflect the detail VO.
    I have a MasterView, DetailView, MasterDetailLink (MasterView->DetailView).
    MasterDetailLink is used to create a table with inline detail table. At runtime:
    1.get MasterView (from AM), change query trough setQuesry() - works.
    2.get DetailView (from AM), change query trough addWhereClause() - does not work (no exceptions) - the results I am getting DO NOT reflect the conditions of the where clause, I mean the clause have not been addedd.
    I 've looked at the logs (debug enabled) and it seems to me that there no "activities" related to the detail VO, even after the where clause of the VO from step 2 is changed.
    Looks like there is a separate VO which I would like to get a hold of :)
    Thanks, and sorry for the long explanation

    After you have added a new where clause on the detail VO, try re-executing VO's query by DetailVO.executeQuery()
    If it doesn't work try re-executing the MasterVO's query after you have added the where clause on the detail

  • Improve the performance in stored procedure using sql server 2008 - esp where clause in very big table - Urgent

    Hi,
    I am looking for inputs in tuning stored procedure using sql server 2008. l am new to performance tuning in sql,plsql and oracle. currently facing issue in stored procedure - need to increase the performance by code optmization/filtering the records using where clause in larger table., the requirement is Stored procedure generate Audit Report which is accessed by approx. 10 Admin Users typically 2-3 times a day by each Admin users.
    It has got CTE ( common table expression ) which is referred 2  time within SP. This CTE is very big and fetches records from several tables without where clause. This causes several records to be fetched from DB and then needed processing. This stored procedure is running in pre prod server which has 6gb of memory and built on virtual server and the same proc ran good in prod server which has 64gb of ram with physical server (40sec). and the execution time in pre prod is 1min 9seconds which needs to be reduced upto 10secs or so will be the solution. and also the exec time differs from time to time. sometimes it is 50sec and sometimes 1min 9seconds..
    Pl provide what is the best option/practise to use where clause to filter the records and tool to be used to tune the procedure like execution plan, sql profiler?? I am using toad for sqlserver 5.7. Here I see execution plan tab available while running the SP. but when i run it throws an error. Pl help and provide inputs.
    Thanks,
    Viji

    You've asked a SQL Server question in an Oracle forum.  I'm expecting that this will get locked momentarily when a moderator drops by.
    Microsoft has its own forums for SQL Server, you'll have more luck over there.  When you do go there, however, you'll almost certainly get more help if you can pare down the problem (or at least better explain what your code is doing).  Very few people want to read hundreds of lines of code, guess what's it's supposed to do, guess what is slow, and then guess at how to improve things.  Posting query plans, the results of profiling, cutting out any code that is unnecessary to the performance problem, etc. will get you much better answers.
    Justin

  • 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

  • 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 and order by to DAO classes

    Hi
    Is it ok(I mean design wise) to pass the 'where clause' conditions and order by clause as a parameter to the method of DAO class?

    Well, I would suggest you write seperate methods in your dao , one to select data without the where clause and one to select data with the where clause thrown in. If you have different 'where' clauses for selecting different kinds of data, have that many dao methods. The dao methods being specific know exactly what is the data that's coming in.
    Lets assume you have a list of purchase orders and each purchase order is indetified by a unique id called PURCHASE_ORDER_ID.
    1. The following code would populate a purchase order's details given an id.
    private statis final String QUERY_1 = "select * from PURCHASE_ORDERS where PURCHASE_ORDER_ID = ? ";
    PurchaseOrderModel getPurchaseOrderData(long poId){
         //get a prepared statement from your connection
         PreparedStatement pst = conn.prepareStatement(QUERY_1);
         //set the poId passed as params to your query
         pst.setLong(1, poId);
         ResultSet rs = pst.executeQuery();
         if(rs.next()){
              //populate data into a model          
         finally{
              //clean up resources
         return model;    
    }2. The following code would return a list of PurchaseOrderModel's whose shipping date falls between a set of dates selected by the user.
    private statis final String QUERY_2 = "select * from PURCHASE_ORDERS where SHIPPING_DATE between ? and ? ";
    PurchaseOrderModel getPurchaseOrdersBetweenDates(list bindValues){
         //get a prepared statement from your connection
         PreparedStatement pst = conn.prepareStatement(QUERY_1);
         //set the dates passed as params to your query
         //we know that the List ought to contain only 2 dates
         pst.setDate(1, (Date)bindValues.get(0));
         pst.setDate(2, (Date)bindValues.get(1));
         ResultSet rs = pst.executeQuery();
         if(rs.next()){
              //iterate and populate data into a model          
              //add model to a list
         finally{
              //clean up resources
         return list;    
         3. This is more interesting - the dao method searches a list of Purchase Orders starting with a set of specific words. The words themselves may be one or many. This means that the number of '?' in your prepared statement may be dynamic. Each element of the list is a String that contains the start substring of a purcahse order name. For example - the list may contain elements like ["a", "ab", "c", "gh"] and the dao method returns all purchase order starting with these names.
    private statis final String QUERY_3 = "select * from PURCHASE_ORDERS where ";
    PurchaseOrderModel getPurchaseOrderNameMatches(list bindValues){
         //construct the query dynamically
         StringBuffer query = new StringBuffer(QUERY_3);
         int count = 0;
         for(Iterator itr = bindValues.iterator(); itr.hasNext();;){
              String value = (String)itr.next();
              query.append ("name like 'value%' ");
              if (count != 0 and (count+1 != bindValues.length)){
                   query.append(" or ");
              count ++;          
         //get a prepared statement from your connection
         PreparedStatement pst = conn.prepareStatement(query.toString());     
         ResultSet rs = pst.executeQuery();
         if(rs.next()){
              //iterate and populate data into a model          
              //add model to a list
         finally{
              //clean up resources
         return list;    
    To sum up,
    1. You need as many methods as you have different kinds of searches (one method for each kind of 'where' clause).
    2. The ejb/business layer would examine the data and decide on which method to call.
    3. Increases coding effort, but makes the code clean and readable. Each layer does it's job. Thus we dont have ejbs forming 'where' clauses and so on.
    Having said that, it really is your decision - you should take into consideration the following factors -
    1. How big is the project ? If its a huge codebase developed by many people, then segregate the responsibilities clearly in each layer as I have outlined. For a small scale project, you could go with your approach.
    2. Whats the take on maintenance and future add-ons ? Do you see the codebase growing with time ?
    3. Is your project a commercial one - is it a product that needs to be maintained or is it a one-off development - develop once and you are done with it.
    4. What are the design considerations ? Is somebody going to audit code for quality ? Or is it a academic one ?
    You should take into account all these before deciding to go one way or the other.
    A general thumb rule should be that you should be convinced that your code readable (maintainable), scalable and efficient. Anything that you do towards these ends is good code/design despite what people/books/patterns say, IMO.
    cheers,
    ram.

  • Is it possible to use LONG columns in WHERE clause or ORDER BY?

    Is it possible to use LONG columns in WHERE clause or ORDER BY?

    Hi,
    LONG data type is deprecated, maybe could you change your column type to LOB ?
    Nonetheless below is a workaround which may fit your needs if forced to use LONG.
    It uses a function which returns you a CLOB. It allows you to use the converted "LONG" column in a WHERE clause.
    Then if you want to order by you have to convert the CLOB to a VARCHAR using DBMS_LOB.SUBSTR.
    SQL> CREATE TABLE my_table (id NUMBER, description LONG);
    Table created.
    SQL> INSERT INTO my_table VALUES (1, 'FIRST LONG');
    1 row created.
    SQL> INSERT INTO my_table VALUES (2, 'ANOTHER LONG');
    1 row created.
    SQL> COMMIT;
    Commit complete.
    SQL> CREATE TYPE my_type_row AS OBJECT (id INTEGER, description CLOB);
      2  /
    Type created.
    SQL> CREATE TYPE my_type_table AS TABLE OF my_type_row;
      2  /
    Type created.
    SQL> CREATE OR REPLACE FUNCTION get_my_long
      2     RETURN my_type_table
      3     PIPELINED
      4  AS
      5     v_tab   my_type_table := my_type_table ();
      6  BEGIN
      7    FOR cur IN (SELECT id, description FROM my_table)
      8  LOOP
      9        PIPE ROW (my_type_row (cur.id, cur.description));
    10  END LOOP;
    11  RETURN;
    12  END;
    13  /
    Function created.
    SQL> SELECT
      2     id,
      3     description
      4  FROM
      5     TABLE (get_my_long ())
      6  WHERE
      7     description LIKE '%LONG'
      8  ORDER BY
      9     DBMS_LOB.SUBSTR(description);
      ID DESCRIPTION
       2 ANOTHER LONG
       1 FIRST LONG
    SQL> SELECT
      2     id,
      3     description
      4  FROM
      5     TABLE (get_my_long ())
      6  WHERE
      7     description LIKE 'FI%';
      ID DESCRIPTION
       1 FIRST LONG
    SQL>Kind regards,
    Ludovic

  • Filter not being generated into where clause

    Hi,
    I have a simple mapping that has a source table, a filter, and a target table that is set to DELETE. The source table has many rows, but the filter would narrow down these rows by a lot. When I generate the code, the cursor that gets created SELECTs the whole table then there is an IF statement that is applied to each row with the filter condition. A lot less processing would be required if the filter was implemented as a WHERE clause in the cursor, but I can't get it to generate this way. I realize that deletes automatically generate row-based code but it would still be row-based if the WHERE clause was in the cursor.
    Is there any way to get it to generate the filter as a WHERE clause in the cursor?

    Hi,
    In general, Warehouse Builder gives you a number of different operating modes:
    - set-based: which does everything in (one) SQL statement. This method is most performant, but has some limitations. Warehouse Builder today does not support set-based deletes (arguably, deletes are not the most common operation in a data warehouse).
    - row-based: which is optimal for debugging. In row-based mode, you get as many records as possible and all operations/transformations take place in PL/SQL. This option gives you most debugging capabilities.
    - row-based bulk: which is the previous method fetching rows in bulk (e.g. 100 by 100). Bulk processing speeds up the overall processing.
    - row-based target only: in this mode we push as many of the operations/transformations as possible into the query (cursor). I.e. your filter (in your case) would be implemented as a restriction on the filter.
    - row-based target only in bulk: see previous.
    Warehouse Builder's default operation is set-based fail over to row-based. I.e. because we do not support set-based delete statements, I suspect you fall back to the row-based method of execution, which is not ideal in your case. I suggest you use the row-based target only option in order to get optimal performance for your scenario.
    Note that for the deletes that are common in DW scenarios the row-based bulk deletes that we generate are often faster than set-based deletes. Also note that if you perform a complete delete (or even truncate) followed by an insert that Warehouse Builder does issue one statement for emptying the table.
    Thanks,
    Mark.

  • Using regexp_instr in a where clause - invalid relational operator

    Whey I try to run this query in TOAD I get an ORA-00920: invalid relational operator error. It's part of a 10g stored procedure. When I highlight it and run it it prompts me for the missing values and then the error pops up. The AND in line 4 is highlighted.
    select CRIME_CLASSIFICATION_ID, crime_type, nvl(count(CRIME_CLASSIFICATION_ID),0) as CRIMECNT
    From vaps.vw_offenses
        where  regexp_instr(valoc,to_char(location_id))
            AND ( fromdate is null or
             offense_date between to_date(fromdate, 'mm/dd/yyyy')  AND to_date(todate,'mm/dd/yyyy')
    group by crime_classification_id, crime_type

    Hi,
    Review what REGEXP_INSTR does: it returns a NUMBER.
    Your WHERE clause couldn't make any sense if you used any other kind of NUMBER expression in that place, e.g. a NUMBER literal such as 12:
    select CRIME_CLASSIFICATION_ID, crime_type, nvl(count(CRIME_CLASSIFICATION_ID),0) as CRIMECNT
    From vaps.vw_offenses
        where  12     -- This is obviously wrong
            AND ( fromdate is null or
             offense_date between to_date(fromdate, 'mm/dd/yyyy')  AND to_date(todate,'mm/dd/yyyy')
    group by crime_classification_id, crime_type
    It's not going to work any better with a function (like REGEXP_INSTR) that returns a NUMBER.
    How can you fix it?  That depends on what you want to do.  Why are you calling REGEXP_INSTR?  What is that condition checking?
    Whenever you have a problem, please post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) from all tables involved, so that the people who want to help you can re-create the problem and test their ideas.
    Also post the results you want from that data, and an explanation of how you get those results from that data, with specific examples.
    Always say which version of Oracle you're using (for example, 11.2.0.2.0).
    See the forum FAQ: https://forums.oracle.com/message/9362002

Maybe you are looking for

  • Open Hub Destination transports

    Hi Experts.. We have crated Open Hub destinations to pull data from ODS to DB table in BI 7.0. But while transport the transformations for OHD are failing with transformation becoming inactive with error messageu201D Target ODSO ZODS*** does not exis

  • ICE Offer Target Path

    Hello, We are trying to use the ICE service to pull a KM folder and its contents (xml docs) from a source portal into another "slave" portal. When we configure the offer from the syndicator portal it automatically enters a Target Path. For example We

  • Strange Oracle---- ORA-00904

    I have below query.. it looks fine but still getting error as shown below ... Breaking my head to identify error but couldn't.. its prompting me as 'ora-00904: "Y"."TRANSACTION_NUMBER": invalid identifier' in short my query is of form... SELECT * FRO

  • Eclipse-AXIS2 : Generating the stub

    hi, i implemented a POJO business service, and use the eclipse web service wizard to generate the server and client side code. everything is OK, but i want to do a customisation, i would like to force the generated stub to extends a custom class ant

  • 30 Business Days Back

    Hi All, I need to find the calendar date 30 business days back from SYSDATE: Formula: Calendar Date = SYSDATE - "30 business days" I have a table contains: cal_dt,bus_day,holiday 7/1/10,1,NULL 7/2/10,1,NULL 7/3/10,0,NULL 7/4/10,0,NULL 7/5/10,0,'Y' 7/