Where-clause with the in-keyword. Query optimising.

Hi I have following question.
I have a query, e. g.
select x, y from tableA where y in (a_1, a_2, ..., a_n)
I have test it with n=1...5
1. 5-6 ms
2. 5-6 ms
3. 150 - 200 ms
4. 150 - 200 ms
5. 180 - 250 ms
There is a gap between n = 2 and n = 3. According to the execution plan the Oracle make a full table access if n >= 3. If n < 3 a an index is used. Is it possible to ensure that the index is always used?
Additionally I have test the equivalent query:
select x, y from tableA where y = a_1 or y = a_2 ... < = a_n
It showsthe same behaviour.

Hi,
I wouldn't say that the optimizer is wrong here. I would look on some more imputs.
How many values of y do you have in the table?
please post the result of:
select count(*),y
from tablea
group by y;
to see how many values of each y-value exists in the table.
For example, if there are only values 1..5 for y in the table a full table scan is the fastet answer for your query, because all values have to read!
Regards
Udo

Similar Messages

  • How can I pass multiple condition in where clause with the join table?

    Hi:
    I need to collect several inputs at run time, and query the record according to the input.
    How can I pass multiple conditions in where clause with the join table?
    Thanks in advance for any help.
    Regards,
    TD

    If you are using SQL-Plus or Reports you can use lexical parameters like:
    SELECT * FROM emp &condition;
    When you run the query it will ask for value of condition and you can enter what every you want. Here is a really fun query:
    SELECT &columns FROM &tables &condition;
    But if you are using Forms. Then you have to change the condition by SET_BLOCK_PROPERTY.
    Best of luck!

  • Creating a where clause in the LOV query box

    Hi guys is any able to help me with this one
    i have a page in my app where there is a LOV drop down now the values for this drop down comes from a table that looks like this
    users_for _form_TBL
    E_MAIL
    Vendor
    [email protected]
    oracle
    [email protected]
    sap
    [email protected]
    IBM
    [email protected]
    Oracle
    [email protected]
    intergraph
    So my syntax for the LOV i mentioned looks like this
    select VENDOR as display_value, VENDOR as return_value
      from form_user_tab where E_MAIL = :APP_USER
    order by 1 ;
    so if [email protected] logs onto the app and has to make a selection on the LOV it would only display the vendors relative to his E_MAIL like oracle ,sap, IBM then he hits the submit button on the page then the vendor that he selected is inserted into another table .What i did on the insert table was create a trigger that after a vendor is inserted the trigger inserts a 1 into a column called assessed .
    What i did after this was add a select in the where clause of the LOV so that it would check in the insert table if that vendor had been chosen before and not display it again to be selected  my syntax the second time around in the SQL query box was
    select VENDOR as display_value, VENDOR as return_value
      from users_for _form_TBL where E_MAIL = :APP_USER
    and (select 'vendor' , 'ASSESSD' from inserted _tbl_imp is null);
    order by 1 ;
    But im getting an error any ideas guys .Thank you

    Hay man thanks for that info on the Tom Kyte Blog 
    --(the code you gave me )
    select 
        u.vendor display_value 
      , u.vendor return_value
    from 
        users_for_form_tbl u 
    where 
        u.e_mail = :app_user 
    and not exists (select null from inserted_tbl_imp i where u.vendor = i.vendor) 
    order by 
        u.vendor 
    --(After the error i tried )Then when i got the error i try'd using 'or exists'  like this
    --(code)
    where 
        u.e_mail = :app_user 
    and not exists (select null from inserted_tbl_imp i where u.vendor = i.vendor) 
                          or exists (select null from inserted_tbl_imp i where u.vendor = i.vendor)
    order by 
        u.vendor 
    But the all the vendors that where in the  same in the insert table came up in the drop down list  example is oracle was assessed before then only oracle would appear in the drop down list  and if it was assessed 3 times it would come up 3 times
    --Then i tried to select where 'Assessed' is null   ('Assessed' is a column in the insert table  which i created a trigger on to insert 1 in the 'ASSESSED' column  when a vendor is begin assessed  )  
    --(code)
    where 
        u.e_mail = :app_user 
    and not exists (select 'ASSESSED' from inserted_tbl_imp i where 'ASSESSED' is null ) 
    order by 
        u.vendor 
    This try didnt return any vendors at all
    --Then i tried distinct
    --(code)
    where 
        u.e_mail = :app_user 
    and not exists (select distinct 'VENDOR',  from inserted_tbl_imp i where u.vendor = i.vendor) 
    order by 
        u.vendor 
    This gave me a LOV ERROR
    This is what i have tried so far there where others syntax's i tried last night as well  but most of them came back as errors . Thanks again for you time and help  fac586  

  • SQL query in SQL_REDO Logminor showing where clause with ROWID

    SQL query in SQL_REDO Logminor showing where clause with ROWID. I dont wanted to use rowid but wanted to use actual value.
    OPERATION SQL_REDO SQL_UNDO
    DELETE delete from "OE"."ORDERS" insert into "OE"."ORDERS"
    where "ORDER_ID" = '2413' ("ORDER_ID","ORDER_MODE",
    and "ORDER_MODE" = 'direct' "CUSTOMER_ID","ORDER_STATUS",
    and "CUSTOMER_ID" = '101' "ORDER_TOTAL","SALES_REP_ID",
    and "ORDER_STATUS" = '5' "PROMOTION_ID")
    and "ORDER_TOTAL" = '48552' values ('2413','direct','101',
    and "SALES_REP_ID" = '161' '5','48552','161',NULL);
    and "PROMOTION_ID" IS NULL
    and ROWID = 'AAAHTCAABAAAZAPAAN';
    DELETE delete from "OE"."ORDERS" insert into "OE"."ORDERS"
    where "ORDER_ID" = '2430' ("ORDER_ID","ORDER_MODE",
    and "ORDER_MODE" = 'direct' "CUSTOMER_ID","ORDER_STATUS",
    and "CUSTOMER_ID" = '101' "ORDER_TOTAL","SALES_REP_ID",
    and "ORDER_STATUS" = '8' "PROMOTION_ID")
    and "ORDER_TOTAL" = '29669.9' values('2430','direct','101',
    and "SALES_REP_ID" = '159' '8','29669.9','159',NULL);
    and "PROMOTION_ID" IS NULL
    and ROWID = 'AAAHTCAABAAAZAPAAe';
    Please let me know solution/document which will convert SQL redo rowid value with actual value.
    Thanks,

    Please enclose your output within tag so that people here can read it easily and help you. Also the reason that why you want to remove rowid?
    Salman
    Edited by: Salman Qureshi on Mar 20, 2013 3:53 PM                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Generate a where clause with outer join criteria condition: (+)=

    Hi,
    In my search page, I use Auto Customization Criteria mode, and I build where clause by using get Criteria():
    public void initSrpQuery(Dictionary[] dic, String userName) {
    int dicSize = dic.length;
    StringBuffer whereClause = new StringBuffer(100);
    Vector parameters = new Vector(5);
    int clauseCount = 0;
    int bindCount = 1;
    for(int i=0; i < dicSize; i++){
    String itemName = (String)(dic.get(OAViewObject.CRITERIA_ITEM_NAME));
    Object value = dic[i].get(OAViewObject.CRITERIA_VALUE);
    String joinCondition = (String)dic[i].get(OAViewObject.CRITERIA_JOIN_CONDITION);
    String criteriaCondition = (String)dic[i].get(OAViewObject.CRITERIA_CONDITION);
    String criteriaDataType = (String)dic[i].get(OAViewObject.CRITERIA_DATATYPE);
    String viewAttributename = (String)dic[i].get(OAViewObject.CRITERIA_VIEW_ATTRIBUTE_NAME);
    String columnName = findAttributeDef(viewAttributename).getColumnNameForQuery();
    if((value != null) /*&& (!("".equals((String).trim())))*/){
    if(clauseCount > 0){
    whereClause.append(" AND ");
    whereClause.append(columnName + " " + criteriaCondition + " :");
    whereClause.append(++bindCount);
    parameters.addElement(value);
    clauseCount++;
    If I want to generate following where clause:
    select
    ,emp.name
    ,emp.email
    ,emp.salesrep_number
    ,comp.name
    ,gs.srp_goal_header_id
    ,gs.status_code
    ,gs.start_date
    ,gs.end_date
    from g2c_goal_shr_emp_assignments_v emp
    ,jtf_rs_salesreps rs
    ,xxg2c_srp_goal_headers_all gs
    ,cn_comp_plans_all comp
    where 1 = 1
    and rs.salesrep_id = gs.salesrep_id (+)
    and gs.comp_plan_id = comp.comp_plan_id (+)
    and gs.period_year (+) = :1 -- :1 p_fiscal_year
    How can I generate a where clause with outer join : gs.period_year (+) = :1 ? Will I get '(+)=' from get(OAViewObject.CRITERIA_CONDITION)?
    thanks
    Lei

    If you are using SQL-Plus or Reports you can use lexical parameters like:
    SELECT * FROM emp &condition;
    When you run the query it will ask for value of condition and you can enter what every you want. Here is a really fun query:
    SELECT &columns FROM &tables &condition;
    But if you are using Forms. Then you have to change the condition by SET_BLOCK_PROPERTY.
    Best of luck!

  • How to set Where clause in the View Object of the MessageChoice ?

    Hi,
    How to set Where clause in the View Object of the
    MessageChoice ?
    Example:
    <bc4j:rootAppModuleDef name="EdEscolaCampusView1AppModule"
    definition="ed00050.Ed00050Module"
    releaseMode="stateful" >
    <bc4j:viewObjectDef name="EdEscolaCampusView1" >
    <bc4j:rowDef name="CreateEdEscolaCampusView1" autoCreate="true" >
    <bc4j:propertyKey name="key" />
    </bc4j:rowDef>
    </bc4j:viewObjectDef>
    <bc4j:viewObjectDef name="ListaTipLocalView1"
    rangeSize="9999">
    </bc4j:viewObjectDef>
    </bc4j:rootAppModuleDef>
    </bc4j:registryDef>
    messageChoice declaration:
    <bc4j:messageChoice name="SeqTipoLocalCampus"
    attrName="SeqTipoLocalCampus"
    prompt="Local do Campus">
    <contents>
    <bc4j:optionList attrName="SeqTipoBasico"
    textAttrName="NomTipoBasico"
    voName="ListaTipLocalView1"/>
    </contents>
    </bc4j:messageChoice>
    I would like set where clause of ViewObject, with dinamic parameters (using attribute1 = :1), before populate messageChoice.
    thanks...
    Danilo

    Hi Andy,
    I try set a where clause using the message:
    Set where Clause parameter using UIX , but my UIX Page have 2 messageChoice's of different ViewObject's, then I need implement this Java Class:
    //Nome da Package da Tela Detail
    package br.com.siadem.siaed.ed00050;
    // Importa as Bibliotecas necessárias
    import oracle.jbo.ViewObject;
    import oracle.jbo.ApplicationModule;
    import oracle.jbo.client.Configuration;
    import oracle.cabo.servlet.BajaContext;
    import oracle.cabo.servlet.Page;
    import oracle.cabo.servlet.event.PageEvent;
    import oracle.cabo.servlet.event.EventResult;
    import oracle.cabo.data.jbo.servlet.bind.*;
    import oracle.cabo.ui.data.BoundValue;
    import oracle.cabo.ui.data.DataBoundValue;
    import javax.servlet.http.HttpServletRequest;
    import br.com.siadem.siaed.util.*;
    import javax.servlet.http.Cookie;
    import oracle.cabo.data.jbo.def.NestedAppModuleDef;
    import oracle.cabo.data.jbo.def.ViewObjectDef;
    import oracle.cabo.data.jbo.def.AppModuleDef;
    // Classe que configura os parametros para a execução da Query,
    // utilizando variáveis de Sessao
    public class FunPreQueryLista
    public static EventResult FunConfiguraQuery(BajaContext context, Page page, PageEvent event) throws Throwable
    // TrataDadosSessao - Classe utilizada para retornar os valores das variáveis de sessão genéricas
    // Ex: CodCliente, CodMunicipio etc...
    TrataDadosSessao varDadosSessao = new TrataDadosSessao();
    // 1o. Parametro Configurado - Através da classe TrataDadosSessao, utilizando um método Get
    // <alterar>
    String valor1 = varDadosSessao.getCodCliente();
    String valor2 = varDadosSessao.getCodMunicipio();
    //Cria o objeto que retorna o ApplicationModule
    ApplicationModule am = ServletBindingUtils.getApplicationModule(context);
    // Início das Configurações da Query da Lista
    //Cria o objeto que retorna o view object da lista desejada
    //alterar
    ViewObject TipoLocal = am.findViewObject("ListaTipoLocalView1");
    //Configuração dos parametros definidos na query do view Object
    //alterar
    TipoLocal.setWhereClauseParam(0,valor1);
    TipoLocal.setWhereClauseParam(1,valor2);
    // Executa a Query
    TipoLocal.executeQuery();
    // Fim das Configurações da Query da Lista
    // Início das Configurações da Query da Lista
    //Cria o objeto que retorna o view object da lista desejada
    //alterar
    ViewObject TipoDestLixo = am.findViewObject("ListaDestinoLixoView1");
    //Configuração dos parametros definidos na query do view Object
    //alterar
    TipoDestLixo.setWhereClauseParam(0,valor1);
    TipoDestLixo.setWhereClauseParam(1,valor2);
    // Executa a Query
    TipoDestLixo.executeQuery();
    // Fim das Configurações da Query da Lista
    // Retorna o Resultado para a Página
    return new EventResult(page);
    The code works very well...
    And, I'm sorry for my two repost's in UIX Forum about this in a few time.
    Thank very much...
    Danilo

  • Where-Clause with function(entered static parameter)

    Hello,
    I have no clue on the way to deal with this issue.
    Basically, for performance, I removed a join with a table, and replaced it by a call to a function within the where clause. This function only convert the entered date into an id, in order to compare with the id in the selected table.
    I knew (I think I'm right!!) that if I put a function into a where-clause, then the function is called at each row.
    As the parameter of this function is a Discoverer parameter, and therefore, it's a static value, I wanted to know whether with Discoverer, there would be a way to convert the entered Discoverer parameter value into a constant that I could use within my where-clause.
    To summarise, hete is the face of my query, at the moment:
    SELECT myColumns
    FROM myTables
    WHERE thisID < myConvertedDate(:RefDate);
    I would like to do this :
    The User enters the :RefDate, I convert it and save the result into a constant.
    Then, my query would look like :
    SELECT myColumns
    FROM myTables
    WHERE thisID < myConstantFromDate;
    I hope that my explanation is clear, and that one of you will be able to advise me.
    Thanks,
    Olivier

    Hello Nigel,
    I am not too sure that the function is called at each row. This is just my thought, from my "average" knowledge of SQL. We cannot run tkprof at the office, in order to get a better understanding.
    And also, the fact that goes towards this direction is that, when I add the call to my function in the where-clause, I have the impression that the query runs more slowly than without the call.
    I reckon that it would be great if the optimizer notices that the function is called with the same value, and returns always the same result.
    Thanks for your comments,
    Olivier

  • Expenditure Type LOV-- Adding where clause with controller extension- help

    Hi Gurus,
    I'm new to OA Framework and Java and I need to extend the controller for the expenditure type lov in iProcurement. I need to add a where clause to the VO to show only those expenditure
    types that will pass transactions controls based on the project and task.
    Name of the VO:ExpenditureTypeNoAwardLOVVO
    controller:oracle.apps.icx.lov.webui.ExpenditureTypeLovCO
    Original Query from the VO:
    select * from (SELECT et.expenditure_type, et.sys_link_start_date_active,
    et.sys_link_end_date_active, 1 as dummy_number
    FROM pa_expenditure_types_expend_v et
    WHERE et.system_linkage_function = 'VI'
    and (trunc(sysdate) between et.expnd_typ_start_date_active and
    nvl(et.expnd_typ_end_date_active, trunc(sysdate+1)))
    and (trunc(sysdate) between et.sys_link_start_date_active and
    nvl(et.sys_link_end_date_active, trunc(sysdate+1))) QRSLT
    ((WHERE UPPER(EXPENDITURE_TYPE) like UPPER(:1)
    AND (UPPER(EXPENDITURE_TYPE) like :2 or UPPER(EXPENDITURE_TYPE) like :3
    or UPPER(EXPENDITURE_TYPE) like :4 or UPPER(EXPENDITURE_TYPE) like :5)))
    I created a custom database function xxpa_check_txnctl which takes project_id, task_id and expenditure type as parameters and returns "Y" if that expenditure type is valid or
    returns "N" if it is not valid.
    What I need to add to the where clause of the above query is
    and *'Y' = ( select xxpa_check_txnctl(project_id,task_id,et.expenditure_type) from dual)* to the standard VO query so that only valid expenditure types will show up in the LOV for that
    project/task combination.
    I enabled the Debug Log from Diagnostics and able to see the values of project_id and task_id in the controller attached to the LOV (oracle.apps.icx.lov.webui.ExpenditureTypeLovCO) as shown
    below. Please tell me how I can add the where condition to the custom controller .
    I really appreciate your help.
    Thanks in Advance,
    Shree.
    ==========================================================================================
    [28]:STATEMENT:[icx.lov.webui.ExpenditureTypeLovCO]:#Param# ProjectId=13
    [28]:STATEMENT:[icx.lov.webui.ExpenditureTypeLovCO]:lov criteria item from dictionary in getLovItemNumber():
    [28]:STATEMENT:[icx.lov.webui.ExpenditureTypeLovCO]:#Param# TaskId=796
    [28]:STATEMENT:[icx.lov.webui.ExpenditureTypeLovCO]:VO used in ExpenditureTypeLovCO.java:
    [28]:STATEMENT:[icx.lov.webui.ExpenditureTypeLovCO]:#Param# voName=ExpenditureTypeNoAwardLovVO
    ==========================================================================================
    Here is the code for the standard controller:
    ==========================================================================================
    package oracle.apps.icx.lov.webui;
    import com.sun.java.util.collections.ArrayList;
    import oracle.apps.fnd.common.VersionInfo;
    import oracle.apps.fnd.framework.OAApplicationModule;
    import oracle.apps.fnd.framework.OAViewObject;
    import oracle.apps.fnd.framework.webui.OAPageContext;
    import oracle.apps.fnd.framework.webui.beans.OAWebBean;
    import oracle.apps.fnd.framework.webui.beans.form.OAFormValueBean;
    import oracle.apps.fnd.framework.webui.beans.layout.OAListOfValuesBean;
    import oracle.apps.fnd.framework.webui.beans.message.OAMessageStyledTextBean;
    import oracle.apps.icx.por.req.webui.CheckoutInfoBaseCO;
    import oracle.jbo.domain.Number;
    public class ExpenditureTypeLovCO extends CheckoutInfoBaseCO
    public static final String RCS_ID = "$Header: ExpenditureTypeLovCO.java 120.1 2006/07/25 06:33:16 sudsubra noship $";
    public static final boolean RCS_ID_RECORDED = VersionInfo.recordClassVersion("$Header: ExpenditureTypeLovCO.java 120.1 2006/07/25 06:33:16 sudsubra noship $",
    "oracle.apps.icx.lov.webui");
    public ExpenditureTypeLovCO()
    public void processRequest(OAPageContext oapagecontext, OAWebBean oawebbean)
    super.processRequest(oapagecontext, oawebbean);
    java.util.Dictionary dictionary = oapagecontext.getLovCriteriaItems();
    Number number = getLovItemNumber(oapagecontext, dictionary, "ReqAwardId");
    Number number1 = getLovItemNumber(oapagecontext, dictionary, "ProjectId");
    Number number2 = getLovItemNumber(oapagecontext, dictionary, "TaskId");
    String s = null;
    if(number == null)
    s = "ExpenditureTypeNoAwardLovVO";
    } else
    ArrayList arraylist = new ArrayList(1);
    arraylist.add("getDefaultAwardId");
    Number number3 = (Number)executeServerCommand(oapagecontext, oapagecontext.getApplicationModule(oawebbean), "CheckoutLovSvrCmd", arraylist);
    if(isLoggingEnabled(oapagecontext, 1))
    logParam(this, oapagecontext, "defaultAwardId", number3, 1);
    if(number.equals(number3))
    s = "ExpenditureTypeWithDefaultAwardLovVO";
    OAViewObject oaviewobject = (OAViewObject)oapagecontext.getApplicationModule(oawebbean).findViewObject("ExpenditureTypeWithDefaultAwardLovVO");
    oaviewobject.setWhereClauseParam(0, number1);
    oaviewobject.setWhereClauseParam(1, number2);
    } else
    s = "ExpenditureTypeWithAwardLovVO";
    OAViewObject oaviewobject1 = (OAViewObject)oapagecontext.getApplicationModule(oawebbean).findViewObject("ExpenditureTypeWithAwardLovVO");
    oaviewobject1.setWhereClauseParam(0, number);
    if(isLoggingEnabled(oapagecontext, 1))
    logMsg(this, oapagecontext, "VO used in ExpenditureTypeLovCO.java:", 1);
    logParam(this, oapagecontext, "voName", s, 1);
    OAMessageStyledTextBean oamessagestyledtextbean = (OAMessageStyledTextBean)oawebbean.findIndexedChildRecursive("ExpenditureType");
    oamessagestyledtextbean.setViewUsageName(s);
    OAMessageStyledTextBean oamessagestyledtextbean1 = (OAMessageStyledTextBean)oawebbean.findIndexedChildRecursive("StartDate");
    oamessagestyledtextbean1.setViewUsageName(s);
    OAMessageStyledTextBean oamessagestyledtextbean2 = (OAMessageStyledTextBean)oawebbean.findIndexedChildRecursive("EndDate");
    oamessagestyledtextbean2.setViewUsageName(s);
    OAFormValueBean oaformvaluebean = (OAFormValueBean)oawebbean.findIndexedChildRecursive("ReqAwardId");
    oaformvaluebean.setViewUsageName(s);
    OAFormValueBean oaformvaluebean1 = (OAFormValueBean)oawebbean.findIndexedChildRecursive("ProjectId");
    oaformvaluebean1.setViewUsageName(s);
    OAFormValueBean oaformvaluebean2 = (OAFormValueBean)oawebbean.findIndexedChildRecursive("TaskId");
    oaformvaluebean2.setViewUsageName(s);
    ((OAListOfValuesBean)oawebbean).setViewUsageName(s);
    public void processFormRequest(OAPageContext oapagecontext, OAWebBean oawebbean)
    super.processFormRequest(oapagecontext, oawebbean);
    ==========================================================================================

    Hi, I will try to look into the issue. I have also done customizations like this in past.
    To achieve this, we must read the Process request of CO properly and understand the places, where you have to make changes. In my case, I identify such places and also I couldn't extend the controller class. SO I took the code from standard CO, changed it at couple of places and created a class file with same code as standard CO but with changed at some places. After that I gave newly created CO name in personalization property, so that the page will follow newly created custom CO.
    So I would suggest to read the CO properly, to understand which line is doing what......

  • Using where clause  with like

    Hi all,
    im trying to set a block default where clause in the pre-query trigger of my block "customer_settlement" , to query the records that exist in a customers table like this, where the customer_name is variable based on the value entered by the user in enter-query mode before hitting the F8 key , the statement is :
    set_block_property( 'customer_settlement' , default_where ,
    ' fk_cust_code in ( select customer_code from customers where customer_name like %' || :customer_settlement.customer_name ||'% )' );
    the query doesnt work and giving me an error " unable to perform query" , notice that :customer_settlement.customer_name is an item in the block , the user change it and would like to query upon it , and its not a base table item on customer_settlement block its on customers table only . I tried all combinations of '%' and || but it seems that oracle can't see the value In the customer_name field.
    any help is highly thanked.
    im using Oracle form 9.0.4 and Oracle 10g Db.
    Regards,
    IKQ

    Hi,
    does this work ?
    set_block_property( 'customer_settlement' , default_where ,
    ' fk_cust_code in ( select customer_code from customers where customer_name like '''%' || :customer_settlement.customer_name ||'%''' )' );
    Frank

  • Where Clause in the Forms doesn't work

    Hi,
    I am trying to execute a query in base table block. The block property 'Query allowed' is TRUE and WHere clause is null;
    I used 'SET_BLOCK_PROPERTY' and set the where clause. Did a GO_BLOCK and EXECUTE_QUERY;
    The block brings all records as if there is no where clause. TO make sure I put up a message 'GET_BLOCK_PROPERTY' to see the where clause. It showed correct where clause.
    null

    Setting the where clause the way you did usually works, and it worked fine for me several times.
    Yet, a couple of days ago I ran into something that defies my logic:
    1) when using the "=" operator, it fetched me several records that satisfied the condition
    2) when using the "<=" or ">=" operator it fetched only one of the records that satisfied the condition: the one that is strictly equal.
    I tried using the pre-query trigger, but to no avail.
    I'm looking forward for your succes.
    null

  • Where clause with a combination of And and Or statements - Basic question

    Hi,
    I have a where clause with a combination of And and Or statements... May I know which one would run first
    Here is the sample
    WHERE SITE_NAME = 'Q' AND ET_NAME IN ('12', '15') AND TEST_DATE > DATE OR SITE_NAME = 'E' AND ET_NAME IN ('19', '20')
    can you please explain how this combination works
    Thanks in advance

    Hi,
    This reminds me of a great story. It's so good, it probably didn't really happen, but it's so good, I'm going to repeat it anyway.
    IBM once had an "executive apptitude test" that they would give to job applicants. There were some questions you might call general knowlege or trivia questions, and each question had a weight (for example, answering an unimportant queestion might score one point, an important question might be 5 points.) One of the questions was "What is the standard width of a mobile home?", and the weight of the question was -20: answering the question correctly did serious harm to your score. The reasoning was that the more you knew about mobile homes, the less likely you were to be their kind of executive.
    Now, as to your question, the correct answer is: I don't know. I don't want to know. Mixing ANDs and ORs without grouping them in parentheses is a really bad idea. Even if you get it right, it's going to confuse the next person who has to look at that code. Use parentheses to make sure the code is doing what you want it to do.
    If you really want to find out, it's documented in the SQL language manual. Look up "Operators, prcedence"
    http://docs.oracle.com/cd/E11882_01/server.112/e26088/operators001.htm#sthref815
    You can easily do an experiment, using scott.emp, or even dual, where
    WHERE  (x AND y)
    OR      zproduces different results from
    WHERE   x
    AND     (y OR z)

  • Dynamic where clause with loop statement

    Hi all,
    is it possible to use a dynamic where clause with a loop statement?
    Can you please advise me, how the syntax needs to be?
    Thanks for your suggestions,
    kind regards, Kathrin!

    Hi Kathrin,
               If u are in ECC 6.0, please go through the code...
              REPORT  zdynamic_select.
    TYPES:
      BEGIN OF ty_sales,
        vbeln  TYPE vbak-vbeln,            " Sales document
        posnr  TYPE vbap-posnr,            " Sales document item
        matnr  TYPE vbap-matnr,            " Material number
        arktx  TYPE vbap-arktx,            " Short text for sales order item
        kwmeng TYPE vbap-kwmeng,           " Order quantity
        vkorg TYPE vbak-vkorg,             " Sales organization
        kunnr TYPE vbak-kunnr,             " Sold-to party
        netwr TYPE vbak-netwr,             " Net Value of the Sales Order
      END OF ty_sales.
    DATA :
      gt_sales TYPE STANDARD TABLE OF ty_sales,
      wa_sales TYPE ty_sales.
    DATA: ob_select TYPE REF TO cl_rs_where.
    DATA: ob_from   TYPE REF TO cl_rs_where.
    DATA: ob_where  TYPE REF TO cl_rs_where,
          gv_source TYPE abapsource.
    START-OF-SELECTION.
    *Step 1 : Prepare the select fields.
      PERFORM zf_build_select.
    *Step 2 : Build the from clause for the select
      PERFORM zf_build_from.
    *Step 3 : Build the where clause for the select
      PERFORM zf_build_where.
    *Step 4 : Execute the dynamic select
      SELECT (ob_select->n_t_where)
          FROM (ob_from->n_t_where)
            INTO CORRESPONDING FIELDS OF TABLE gt_sales
            WHERE (ob_where->n_t_where).
      LOOP AT gt_sales INTO wa_sales.
        WRITE :   /5 wa_sales-vbeln,
                  15 wa_sales-vkorg,
                  20 wa_sales-kunnr,
                  40 wa_sales-netwr,
                  50 wa_sales-posnr,
                  60 wa_sales-matnr,
                  70 wa_sales-arktx,
                  90 wa_sales-kwmeng.
      ENDLOOP.
    *&      Form  zf_build_select
    FORM zf_build_select .
      CREATE OBJECT ob_select.
    *Build the table name/field name combination
    *Add Sales order header fields
      CLEAR gv_source.
      CALL METHOD cl_rs_where=>build_tabname_fieldname
        EXPORTING
          i_tabname   = 'VBAK'
          i_fieldname = 'VBELN'
          i_sign      = '~'
        IMPORTING
          e_combined  = gv_source.
    *Add the where line
      CALL METHOD ob_select->add_line
        EXPORTING
          i_line = gv_source.
      CLEAR gv_source.
      CALL METHOD cl_rs_where=>build_tabname_fieldname
        EXPORTING
          i_tabname   = 'VBAK'
          i_fieldname = 'VKORG'
          i_sign      = '~'
        IMPORTING
          e_combined  = gv_source.
    *Add the where line
      CALL METHOD ob_select->add_line
        EXPORTING
          i_line = gv_source.
      CLEAR gv_source.
      CALL METHOD cl_rs_where=>build_tabname_fieldname
        EXPORTING
          i_tabname   = 'VBAK'
          i_fieldname = 'KUNNR'
          i_sign      = '~'
        IMPORTING
          e_combined  = gv_source.
    *Add the where line
      CALL METHOD ob_select->add_line
        EXPORTING
          i_line = gv_source.
      CLEAR gv_source.
      CALL METHOD cl_rs_where=>build_tabname_fieldname
        EXPORTING
          i_tabname   = 'VBAK'
          i_fieldname = 'NETWR'
          i_sign      = '~'
        IMPORTING
          e_combined  = gv_source.
    *Add the where line
      CALL METHOD ob_select->add_line
        EXPORTING
          i_line = gv_source.
    *Add Sales order item fields
      CALL METHOD cl_rs_where=>build_tabname_fieldname
        EXPORTING
          i_tabname   = 'VBAP'
          i_fieldname = 'POSNR'
          i_sign      = '~'
        IMPORTING
          e_combined  = gv_source.
    *Add the where line
      CALL METHOD ob_select->add_line
        EXPORTING
          i_line = gv_source.
      CLEAR gv_source.
      CALL METHOD cl_rs_where=>build_tabname_fieldname
        EXPORTING
          i_tabname   = 'VBAP'
          i_fieldname = 'MATNR'
          i_sign      = '~'
        IMPORTING
          e_combined  = gv_source.
    *Add the where line
      CALL METHOD ob_select->add_line
        EXPORTING
          i_line = gv_source.
      CLEAR gv_source.
      CALL METHOD cl_rs_where=>build_tabname_fieldname
        EXPORTING
          i_tabname   = 'VBAP'
          i_fieldname = 'ARKTX'
          i_sign      = '~'
        IMPORTING
          e_combined  = gv_source.
    *Add the where line
      CALL METHOD ob_select->add_line
        EXPORTING
          i_line = gv_source.
      CLEAR gv_source.
      CALL METHOD cl_rs_where=>build_tabname_fieldname
        EXPORTING
          i_tabname   = 'VBAP'
          i_fieldname = 'KWMENG'
          i_sign      = '~'
        IMPORTING
          e_combined  = gv_source.
    *Add the where line
      CALL METHOD ob_select->add_line
        EXPORTING
          i_line = gv_source.
    ENDFORM.                    " zf_build_select
    *&      Form  zf_build_from
    FORM zf_build_from .
      CREATE OBJECT ob_from.
    *Add opening bracket
      CALL METHOD ob_from->add_opening_bracket
      CLEAR gv_source.
    *Add the join condition.This can be made
    *fully dynamic as per your requirement
      gv_source = 'VBAK AS VBAK INNER JOIN VBAP AS VBAP'.
    *Add the where line
      CALL METHOD ob_from->add_line
        EXPORTING
          i_line = gv_source.
      CLEAR gv_source.
    *Add the join condition.This can be made
    *fully dynamic as per your requirement
      gv_source = 'ON VBAKVBELN = VBAPVBELN'.
    *Add the where line
      CALL METHOD ob_from->add_line
        EXPORTING
          i_line = gv_source.
    *Add the closing bracket
      CALL METHOD ob_from->add_closing_bracket
    ENDFORM.                    " zf_build_from
    *&      Form  zf_build_where
    FORM zf_build_where .
      DATA :
      lv_field TYPE REF TO data,
      lv_field_low TYPE REF TO data,
      lv_field_high TYPE REF TO data.
      CREATE OBJECT ob_where.
    *Add the field VBELN : Sales Document
    *Use this method if you want to assign a single value to a field
    *Set the value for VBELN : Sales Document Number
    CALL METHOD ob_where->add_field
       EXPORTING
         i_fieldnm  = 'VBAK~VBELN'
         i_operator = '='
         i_intlen   = 10
         i_datatp   = 'CHAR'
       IMPORTING
         e_r_field  = lv_field.
    CALL METHOD ob_where->set_value_for_field
       EXPORTING
         i_fieldnm = 'VBAK~VBELN'
         i_value   = '0000120020'.
    *Use this method if you want to assign a range of values
    *Set a range for the Sales Document number
      CALL METHOD ob_where->add_field_between_2values
        EXPORTING
          i_fieldnm      = 'VBAK~VBELN'
          i_intlen       = 10
          i_datatp       = 'CHAR'
        IMPORTING
          e_r_field_low  = lv_field_low
          e_r_field_high = lv_field_high.
      CALL METHOD ob_where->set_2values_for_field
        EXPORTING
          i_fieldnm    = 'VBAK~VBELN'
          i_value_low  = '0000120020'
          i_value_high = '0000120067'.
    *Set the 'AND' Clause
      CALL METHOD ob_where->add_and.
    *Add the field MATNR : Material
      CALL METHOD ob_where->add_field
        EXPORTING
          i_fieldnm  = 'MATNR'
          i_operator = '='
          i_intlen   = 18
          i_datatp   = 'CHAR'
        IMPORTING
          e_r_field  = lv_field.
    *Set the value for the Material field
      CALL METHOD ob_where->set_value_for_field
        EXPORTING
          i_fieldnm = 'MATNR'
          i_value   = '000000000050111000'.
    *Set the 'AND' Clause
      CALL METHOD ob_where->add_and
    *Add the field VKORG
      CALL METHOD ob_where->add_field
        EXPORTING
          i_fieldnm  = 'VKORG'
          i_operator = '='
          i_intlen   = 4
          i_datatp   = 'CHAR'
        IMPORTING
          e_r_field  = lv_field.
    *Set the value for VKORG : Sales Organization
      CALL METHOD ob_where->set_value_for_field
        EXPORTING
          i_fieldnm = 'VKORG'
          i_value   = 'GMUS'.
    ENDFORM.                    " zf_build_where

  • Mysterious where clause with japanese

    enviroment:
    PL/SQL Develope, Version 7.1.0.1337, Windows XP Professional 5.1 Build 2600 (Service Pack 2)
    Here is the problem, when i add a where clause with japanese, the data evaporated:
    SQL> select * from ja_test;
    EXECUTABLE_NAME DESCRIPTION
    XX00MRP0411C 需要供給データ作成マネージャ
    SQL> select * from ja_test j where j.description = '需要供給データ作成マネージャ';
    EXECUTABLE_NAME DESCRIPTION
    SQL>
    thanks in advance!

    Thanks for replies and Sorry for my rashness, maybe the following
    scripts could explain the problem more well. I create a table named
    ja_test with two fields(EXECUTABLE_NAME and DESCRIPTION), both of the
    type is varchar2, and there is only one record in the table,
    but the DESCRIPTION contains JAPANESE characters, when i use a where
    clause like this "where j.executable_name = 'XX00MRP0411C';", everything
    seems work fine, but when the where clase include JAPANESE characters
    like this "j.description = '需要供給データ作成マネージャ';", even if
    the "j.description" is copied form database, no records returned:
    SQL> select * from ja_test j where j.executable_name = 'XX00MRP0411C';
    EXECUTABLE_NAME DESCRIPTION
    XX00MRP0411C 需要供給データ作成マネージャ
    SQL> select * from ja_test j where j.description = '需要供給データ作成マネージャ';
    EXECUTABLE_NAME DESCRIPTION
    SQL> desc ja_test;
    Name Type Nullable Default Comments
    EXECUTABLE_NAME VARCHAR2(30)
    DESCRIPTION VARCHAR2(240) Y
    SQL>

  • How to use where clause with get statement in LDB programs

    Hi All,
    I am using logical databse in my report program.I am not getting how to use the where clause in the get statement is it possible to use?or if not possible only option is we should filter it after get statment is right?Can you please some body throw some idea on this?
    Regards
    Mahesh

    Hi,
    Reffer these links
    http://help.sap.com/saphelp_nw04/helpdata/en/9f/db9bfa35c111d1829f0000e829fbfe/content.htm
    http://help.sap.com/saphelp_nw04/helpdata/en/9f/db9b5e35c111d1829f0000e829fbfe/frameset.htm
    http://help.sap.com/saphelp_nw04/helpdata/en/c6/8a15381b80436ce10000009b38f8cf/frameset.htm
    /people/srivijaya.gutala/blog/2007/03/05/why-not-logical-databases
    reward if helpful
    Thanks,
    Suma.

  • How Do I Sort a Group of Photos on the Same Page with the same Keyword Tag?

    I want to group similar photos on the same page with the same keyword tag.  I have tried dragging and dropping without any success.  Can anyone help?

      Create an album, then search using a keyword. Select all the photos produced by the search and drag them into the album.
    You can drag photos into any order in Albums and they remain in your chosen order.
     

Maybe you are looking for

  • Inventory Program Pt 2 - I have most of it, but I can't get it finished.

    Hello. I am currently stumped. I am already a day late with this assignment and I cannot figure out the logic to use to calculate the overall value of the entire inventory. I'm pasting my code here in the hopes that someone can tell me what it is I'm

  • Link to a new site that opens within my site

    Can someone tell me how I can create a link to an external site, where the site opens up within the body of my site? Do I need a javascript for this? Thanks in advance.

  • Video Still Playing After Swipe

    Hey Guys, I have a video in one page, but It continues to play when I swipe to the second page. Is there a way to stop this from happening?

  • WS-I Tools - Major Bug in JDeveloper 11g

    Hello, I've tried tro run the WS-I analyzer from JDeveloper (11.1.1 - 2 - 3 ) but have the following error: An error occcured when writing the temporaryWS-I Analyzer configuration file After spending couple of hours and finally gave up, and I believe

  • PAL - NTSC Conversion question

    I have some PAL DV footage at 25fps which I need to convert to NTSC to match some existing NTSC footage. The NTSC originated footage, when played in Quicktime diisplays the following info: FPS: 23.98 Playing FPS: 24 I need to convert the PAL footage