Order of Execution in WHERE clause

DB Version 10gR2
In a query like
SELECT sal from emp where empid=7891 and empname='JOHN';
What does Oracle evaluate first in the WHERE clause, is it empid=7891 or empname='JOHN'? I couldn't find this in 10G R2 documentation, hence this thread.

Hi,
You need to read the execution plan of a query to see which filtering condition is applied first or last.
For the sample "EMP" table from SCOTT schema, following is clear:
SQL> set autotrace on
SQL> SELECT sal from emp where empno=7891 and ename='JOHN';
no rows selected
Execution Plan
Plan hash value: 2949544139
| Id  | Operation                   | Name   | Rows  | Bytes | Cost (%CPU)| Time     |
|   0 | SELECT STATEMENT            |        |     1 |    14 |     1   (0)| 00:00:01 |
|*  1 |  TABLE ACCESS BY INDEX ROWID| EMP    |     1 |    14 |     1   (0)| 00:00:01 |
|*  2 |   INDEX UNIQUE SCAN         | PK_EMP |     1 |       |     0   (0)| 00:00:01 |
Predicate Information (identified by operation id):
   1 - filter("ENAME"='JOHN')
   2 - access("EMPNO"=7891)
Statistics
          0  recursive calls
          0  db block gets
          1  consistent gets
          0  physical reads
          0  redo size
        272  bytes sent via SQL*Net to client
        384  bytes received via SQL*Net from client
          1  SQL*Net roundtrips to/from client
          0  sorts (memory)
          0  sorts (disk)
          0  rows processed
SQL>Message was edited by:
Citrus
added complete autotrace output

Similar Messages

  • Order of expression in where clause matters

    Connected to:
    Oracle8i Release 8.1.5.0.0 - Production
    With the Java option
    PL/SQL Release 8.1.5.0.0 - Production
    SQL> select * from dual where 1 = 1 or 1/0 < 1;
    D
    X
    SQL> select * from dual where 1/0 < 1 or 1 = 1;
    select * from dual where 1/0 < 1 or 1 = 1
    ERROR at line 1:
    ORA-01476: divisor is equal to zero
    SQL>select * from dual where 1 / 0 > 1 and 1 <> 1
    no rows returned
    SQL>select * from dual where 1 <> 1 and 1 / 0 > 1
    ERROR at line 1:
    ORA-01476: divisor is equal to zero
    It seems that it values the conditions from:
    left to right in "or" clause (it stops at the first "true" condition)
    right to left in "and" clause (it stops at the first "false" condition)
    Why is it doing like this? What is the logic?

    It is for performance reasons.
    When you evaluate "a or b", if a is true,
    b must not be checked - why should the
    database do it?

  • Query Execution on Where Clause

    Hi I have the where cluase as below , I would like to know how does oracle decides which one to execute first,
    WHERE S.PERSPECTIVE='S'
    and s.shipment_gid=sb.shipment_gid
    AND SB.BILL_GID=CBIL.INVOICE_GID
    and inv.invoice_gid=cbil.invoice_gid
    AND S.SOURCE_LOCATION_GID=LC.LOCATION_GID
    and l.location_gid=lc.location_gid
    AND TRUNC(cbil.insert_date)=TRUNC(tc.tesco_cal_date)
    AND(lc.location_gid='N' OR lc.corporation_gid='TESCO.10719')
    AND s.source_location_gid=lc.location_gid
    AND tc.tesco_year='2013'
    AND tc.tesco_period=6
    AND tc.tesco_week_number=23     

    Hi,
    The optimizer usually goes for low-hanging fruit first.  If there is a condition that's easy to perform and narrows down the result set a lot, it will do that condition before another one that is harder to perform, or that doesn't rule out so many rows.  For example, if there are indexes on tc.tesco_period and tc.tesco_week_number, but not on tc.tesco_year, then it will probably perform one of the conditions that can be done with an index before it does the condition involving tc.tesco_year.  If there are 53 different possible values for tc.tesco_week_number, but only 6 possible values for tc_tesco_period, then it will probably to the condition on tc.tesco_week_number (and rule out about 52/53 of the rows) before it does the condition thatt involves tc.tesco_period (which only excludes about  5/6 of the rows.)
    There are always exceptions.  As others have said already, look at the execution plan if you really want to know.

  • How to construct the where clause for a nested xml target file

    Post Author: jlpete72
    CA Forum: Data Integration
    I'm having some problems getting the desired results creating a multi-level nested xml file.  Specifically, it does not seem that the where clause in the child schemas respects values from parent schemas.  I'm sure I'm constructing something incorrectly, but am running out of ideas. 
    I am working with the classic company/order/line hierarchy and there are three levels of output schemas in my target xml file, one for company, order header and order line information.
    For testing, I have hardcoded a restriction at the order header line to deal with only one order.  But unless I hardcode values into the where clause at the order line level of the schema, all values are returned for orders belonging to the company defined in the company level.
    I'm trying a where clause at the order line level similar to:
    order_line.customer = order_header.customer and order_line.order_num = order_header.order_num
    If the customer has more than one order in the data file, then all orders for that customer are placed in the detail for the order header.  Only if I hard code the order number in the where clause do I get only the lines for the order specified in the header section.  Not very practical. 
    What am I missing?

    An External Parsed Entity could be used to reference a schema.
    In your DTD:
    <!ENTITY datamodules SYSTEM "file:///c:/Datamodules/Datamodules.xsd">
    Refer the external entity in xml document:
    <datamodules>&datamodules;</datamodules>

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

  • Select Statement -- Where Clause Execution Order

    What is the order of execution of the "AND" and "OR" in the WHERE clause of a Select statement?
    Are the "AND"'s executed from the top down, left to right? Is it the same for the "OR"'s execution?
    Thanks for any help...

    Not clear why you care. There is an order in which the optimizer parses the SQL (which may change from ver to ver), but this is a fairly quick operation. The order in which tables are visited and predicates evaluated is dependent on what the op[timizer does with the SQL.
    Ken                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Sql order in where clause...

    i want to ask about
    how oracle deal with the order of where cluase
    as in select * from where tname = 'EMP'
    and tabtype = 'TABLE'
    oracle strat from down (tabtype) or from up (tname)
    and there is difference between this order
    if the where clause contains (and) or (or)
    i always need to know this thing but no place i found say about it in strait way..
    thanks..
    null

    I am sorry for the late reply.
    I guess that ORDER doesn't matter in the WHERE clause. We should take 2 cases:
    1) Say, in a WHERE clause, U have a limiting condition on one of the indexed field of the table, then definitely that will be executed first and the result set will be passed to the other conditions.
    2) Say, in the WHERE clause, U don't have any indexed field then ORACLE will go for cost based execution. In this case, it will first go to the column, for which the SELECTIVITY is the highest ( ORACLE does so internally ) and then the result set is passed to the other conditions.
    Hope this helps.
    Correct me, if I am wrong.

  • 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

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

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

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

  • Is  order in which the conditions given in the 'WHERE' clause are imortant

    Hi All,
    Is the order in which the conditions are given in the 'WHERE' clause are important for
    performance with regard to oracle query plan.
    Regards

    Short answer: no.
    Longer answer: Well. probably not. If you are using very old versions of the database or the rule-based optimizer, you can probably find some corner cases where it mattered. If you are using a vaguely recent version of the database with the cost based optimizer, it shouldn't matter-- the optimizer is free to evaluate the conditions in whatever order it would like and it chooses to do so in the order that it expects to be most efficient. That said, as the number of objects and conditions increases, the number of possible permutations the CBO tries to consider increase dramatically to the point that an exhaustive analysis of all possible conditions isn't feasible. In that case, the optimizer will have to make a reasonable effort to explore the set of possible plans rather than doing an exhaustive search-- the order of conditions is likely to matter slightly in the optimizer's choice of which branches to explore and which to prune if there are many conditions with similar (or identical) costs. Now, that being said, it is very unlikely that you could do anything useful with this knowledge that would be able to force the optimizer to do something that you'd want. It's possible to do, of course, it's just not a particularly useful way of influencing the optimizer.
    Justin

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

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

  • Order of Predicates and Joins in a where Clause

    I always specify the join conditions and then predicates in where clause . But when i placed the predicates first and then joins the response was quicker . I compared the execution plan and each has a different approach .
    Is it true in all cases or it doesn't matter ? Which one is better ? In the following examples I usually follow the first approach but when i tried the second one it was faster .
    Query 1
    select t1.something from
    table1 t1 , table2 t2
    where t1.id=t2.id
    and t1.year = 2009
    Query 2
    select t1.something from
    table1 t1 , table2 t2
    where t1.year = 2009and
    and t1.id=t2.id
    Edited by: user561066 on Sep 24, 2010 11:57 AM

    Welcome to the forum.
    As SomeoneElse already asked: mentioning your database version is crucial when it comes to these types of questions.
    So just be default always post the result of:
    SQL> select * from v$version;when asking a question.
    Find more information here, it explains clearly what information is needed from you to post:
    How to post a SQL statement tuning request HOW TO: Post a SQL statement tuning request - template posting
    Execution plans, database version, optimizer settings....

  • 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

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

Maybe you are looking for