Subquery in the Where clause

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

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

Similar Messages

  • Subquery in the From Clause

    I have a query the contains a subquery in the from clause. The problem is how to join one of the tables in the subquery to one of the main tables. If I hard a value, the query runs, but using a table.column produced an "invalid column name" error.
    Examples of both are below.
    This one works
    SELECT a.pay_rate, a.bill_rate, a.frequency, c.value
    FROM SYSADM.ps_pb_wkord_sq_rte a, SYSADM.ps_md_erncd_action b,
    SELECT DISTINCT z.value
    FROM SYSADM.ps_md_erncd_action z
    WHERE z.md_action = 'CALC_BURD' AND
    z.system_id = 'PB' AND
    z.erncd = 'REG' AND **This is the line in question**
    z.effdt = (
    SELECT MAX(z_ed.effdt)
    FROM SYSADM.ps_md_erncd_action z_ed
    WHERE z.setid = z_ed.setid AND
    z.erncd = z_ed.erncd AND
    z.effdt = z_ed.effdt AND
    z.system_id = z_ed.system_id AND
    z.md_action = z_ed.md_action AND
    z_ed.effdt <= TO_DATE('04/01/2001','MM/DD/YYYY'))) c
    WHERE a.erncd = b.erncd AND
    b.effdt = (
    SELECT MAX(b_ed.effdt)
    FROM SYSADM.ps_md_erncd_action b_ed
    WHERE b.setid = b_ed.setid AND
    b.erncd = b_ed.erncd AND
    b.effdt = b_ed.effdt AND
    b.system_id = b_ed.system_id AND
    b.md_action = b_ed.md_action AND
    b_ed.effdt <= TO_DATE('04/01/2001','MM/DD/YYYY')) AND
    a.group_id = 'PSD01' AND
    a.workorder_no = 'H00034758' AND
    a.assignment_no = 'H00034758-001' AND
    b.system_id = 'PB' AND
    b.md_action = 'EARN_TYPE' AND
    b.value = 'R';
    This one produces the error
    SELECT a.pay_rate, a.bill_rate, a.frequency, c.value
    FROM SYSADM.ps_pb_wkord_sq_rte a, SYSADM.ps_md_erncd_action b,
    SELECT DISTINCT z.value
    FROM SYSADM.ps_md_erncd_action z
    WHERE z.md_action = 'CALC_BURD' AND
    z.system_id = 'PB' AND
    z.erncd = a.erncd AND **This is line in question**
    z.effdt = (
    SELECT MAX(z_ed.effdt)
    FROM SYSADM.ps_md_erncd_action z_ed
    WHERE z.setid = z_ed.setid AND
    z.erncd = z_ed.erncd AND
    z.effdt = z_ed.effdt AND
    z.system_id = z_ed.system_id AND
    z.md_action = z_ed.md_action AND
    z_ed.effdt <= TO_DATE('04/01/2001','MM/DD/YYYY'))) c
    WHERE a.erncd = b.erncd AND
    b.effdt = (
    SELECT MAX(b_ed.effdt)
    FROM SYSADM.ps_md_erncd_action b_ed
    WHERE b.setid = b_ed.setid AND
    b.erncd = b_ed.erncd AND
    b.effdt = b_ed.effdt AND
    b.system_id = b_ed.system_id AND
    b.md_action = b_ed.md_action AND
    b_ed.effdt <= TO_DATE('04/01/2001','MM/DD/YYYY')) AND
    a.group_id = 'PSD01' AND
    a.workorder_no = 'H00034758' AND
    a.assignment_no = 'H00034758-001' AND
    b.system_id = 'PB' AND
    b.md_action = 'EARN_TYPE' AND
    b.value = 'R';
    Any help is greatly appreciated.
    Thanks,
    JD Lippard

    Hi JD,
    your code is very difficult to read to i will give you some general information.
    SELECT t1.c1,t1.c2
    FROM table t1
    , (SELECT t2.col1 alias1
    , t2.col2 alias2
    , a.s.o.
    FROM anytable t2
    ) tablealias
    WHERE t1.c1 = tablealias.alias1
    You can select any columns inside this 'dynamic view' whichever you need for a join. Independent if you print them or not.
    But you cannot join INSIDE this dynamic view to outer tables like
    SELECT t1.c1,t1.c2
    FROM table t1
    , (SELECT t2.col1 alias1
    , t2.col2 alias2
    , a.s.o.
    FROM anytable t2
    WHERE t1.c2 = t2.col2
    ) tablealias
    WHERE bla
    Maybe it helps a bit.
    Cheers,
    Udo

  • Subquery in the Select Clause

    Can a subquery in the select clause return more than one field?
    Something like this:
    select ename,
    (select dname, loc from dept where e.deptno = deptno) as (dname,loc)
    from emp e

    A simple way to find out is to test it. In my tests below, the original query produces an error that says it didn't find FROM where it expected. Eliminating "as (dname,loc)" produces an error about too many values. Putting only one value in the subquery in the select clause works, whether it is dname or loc. Concatenating the two columns as dname || ' ' || loc to produce one value in the subquery in the select clause works. Using two separate subqueries, one for dname and one for loc works. And, lastly, a cursor statement with both values works, although the output is a little hard to read. This may be different in newer versions. I am using Oracle 8.1.7. It may be different in 9i. I was unable to locate any documentation on the cursor statement or cursor operator which I have also heard it called. I only knew to try it because I have seen it used. I looked up the SELECT syntax in the 9i SQL Reference and there was no mention of cursor in the select clause. Can anyone provide a link to some documentation on this? I vaguely recall reading something that said that, other than outputting from SQL*Plus as below, it wasn't yet compatible with anything else, like you can't use it in PL/SQL, but I can't remember where I read it.
    SQL> -- 2 values in subquery in select clause:
    SQL> select ename,
      2  (select dname, loc from dept where e.deptno = deptno) as (dname,loc)
      3  from emp e
      4  /
    (select dname, loc from dept where e.deptno = deptno) as (dname,loc)
    ERROR at line 2:
    ORA-00923: FROM keyword not found where expected
    SQL> select ename,
      2  (select dname, loc from dept where e.deptno = deptno)
      3  from emp e
      4  /
    (select dname, loc from dept where e.deptno = deptno)
    ERROR at line 2:
    ORA-00913: too many values
    SQL> -- 1 value in subquery in select clause:
    SQL> select ename,
      2  (select dname from dept where e.deptno = deptno)
      3  from emp e
      4  /
    ENAME      (SELECTDNAMEFR                                                      
    SMITH      RESEARCH                                                            
    ALLEN      SALES                                                               
    WARD       SALES                                                               
    JONES      RESEARCH                                                            
    MARTIN     SALES                                                               
    BLAKE      SALES                                                               
    CLARK      ACCOUNTING                                                          
    SCOTT      RESEARCH                                                            
    KING       ACCOUNTING                                                          
    TURNER     SALES                                                               
    ADAMS      RESEARCH                                                            
    JAMES      SALES                                                               
    FORD       RESEARCH                                                            
    MILLER     ACCOUNTING                                                          
    14 rows selected.
    SQL> select ename,
      2  (select loc from dept where e.deptno = deptno)
      3  from emp e
      4  /
    ENAME      (SELECTLOCFRO                                                       
    SMITH      DALLAS                                                              
    ALLEN      CHICAGO                                                             
    WARD       CHICAGO                                                             
    JONES      DALLAS                                                              
    MARTIN     CHICAGO                                                             
    BLAKE      CHICAGO                                                             
    CLARK      NEW YORK                                                            
    SCOTT      DALLAS                                                              
    KING       NEW YORK                                                            
    TURNER     CHICAGO                                                             
    ADAMS      DALLAS                                                              
    JAMES      CHICAGO                                                             
    FORD       DALLAS                                                              
    MILLER     NEW YORK                                                            
    14 rows selected.
    SQL> select ename,
      2  (select dname || ' ' || loc from dept where e.deptno = deptno)
      3  from emp e
      4  /
    ENAME      (SELECTDNAME||''||LOCFROMDEP                                        
    SMITH      RESEARCH DALLAS                                                     
    ALLEN      SALES CHICAGO                                                       
    WARD       SALES CHICAGO                                                       
    JONES      RESEARCH DALLAS                                                     
    MARTIN     SALES CHICAGO                                                       
    BLAKE      SALES CHICAGO                                                       
    CLARK      ACCOUNTING NEW YORK                                                 
    SCOTT      RESEARCH DALLAS                                                     
    KING       ACCOUNTING NEW YORK                                                 
    TURNER     SALES CHICAGO                                                       
    ADAMS      RESEARCH DALLAS                                                     
    JAMES      SALES CHICAGO                                                       
    FORD       RESEARCH DALLAS                                                     
    MILLER     ACCOUNTING NEW YORK                                                 
    14 rows selected.
    SQL> select ename,
      2  (select dname from dept where e.deptno = deptno),
      3  (select loc from dept where e.deptno = deptno)
      4  from emp e
      5  /
    ENAME      (SELECTDNAMEFR (SELECTLOCFRO                                        
    SMITH      RESEARCH       DALLAS                                               
    ALLEN      SALES          CHICAGO                                              
    WARD       SALES          CHICAGO                                              
    JONES      RESEARCH       DALLAS                                               
    MARTIN     SALES          CHICAGO                                              
    BLAKE      SALES          CHICAGO                                              
    CLARK      ACCOUNTING     NEW YORK                                             
    SCOTT      RESEARCH       DALLAS                                               
    KING       ACCOUNTING     NEW YORK                                             
    TURNER     SALES          CHICAGO                                              
    ADAMS      RESEARCH       DALLAS                                               
    JAMES      SALES          CHICAGO                                              
    FORD       RESEARCH       DALLAS                                               
    MILLER     ACCOUNTING     NEW YORK                                             
    14 rows selected.
    SQL> -- cursor statement:
    SQL> select ename,
      2  cursor (select dname, loc from dept where e.deptno = deptno)
      3  from emp e
      4  /
    ENAME      CURSOR(SELECTDNAME,L                                                
    SMITH      CURSOR STATEMENT : 2                                                
    CURSOR STATEMENT : 2
    DNAME          LOC                                                             
    RESEARCH       DALLAS                                                          
    1 row selected.
    ALLEN      CURSOR STATEMENT : 2                                                
    CURSOR STATEMENT : 2
    DNAME          LOC                                                             
    SALES          CHICAGO                                                         
    1 row selected.
    WARD       CURSOR STATEMENT : 2                                                
    CURSOR STATEMENT : 2
    DNAME          LOC                                                             
    SALES          CHICAGO                                                         
    1 row selected.
    JONES      CURSOR STATEMENT : 2                                                
    CURSOR STATEMENT : 2
    DNAME          LOC                                                             
    RESEARCH       DALLAS                                                          
    1 row selected.
    MARTIN     CURSOR STATEMENT : 2                                                
    CURSOR STATEMENT : 2
    DNAME          LOC                                                             
    SALES          CHICAGO                                                         
    1 row selected.
    BLAKE      CURSOR STATEMENT : 2                                                
    CURSOR STATEMENT : 2
    DNAME          LOC                                                             
    SALES          CHICAGO                                                         
    1 row selected.
    CLARK      CURSOR STATEMENT : 2                                                
    CURSOR STATEMENT : 2
    DNAME          LOC                                                             
    ACCOUNTING     NEW YORK                                                        
    1 row selected.
    SCOTT      CURSOR STATEMENT : 2                                                
    CURSOR STATEMENT : 2
    DNAME          LOC                                                             
    RESEARCH       DALLAS                                                          
    1 row selected.
    KING       CURSOR STATEMENT : 2                                                
    CURSOR STATEMENT : 2
    DNAME          LOC                                                             
    ACCOUNTING     NEW YORK                                                        
    1 row selected.
    TURNER     CURSOR STATEMENT : 2                                                
    CURSOR STATEMENT : 2
    DNAME          LOC                                                             
    SALES          CHICAGO                                                         
    1 row selected.
    ADAMS      CURSOR STATEMENT : 2                                                
    CURSOR STATEMENT : 2
    DNAME          LOC                                                             
    RESEARCH       DALLAS                                                          
    1 row selected.
    JAMES      CURSOR STATEMENT : 2                                                
    CURSOR STATEMENT : 2
    DNAME          LOC                                                             
    SALES          CHICAGO                                                         
    1 row selected.
    FORD       CURSOR STATEMENT : 2                                                
    CURSOR STATEMENT : 2
    DNAME          LOC                                                             
    RESEARCH       DALLAS                                                          
    1 row selected.
    MILLER     CURSOR STATEMENT : 2                                                
    CURSOR STATEMENT : 2
    DNAME          LOC                                                             
    ACCOUNTING     NEW YORK                                                        
    1 row selected.
    14 rows selected.

  • Function-based index with OR in the wher-clause

    We have some problems with functin-based indexes and
    the or-condition in a where-clause.
    --We use Oracle 8i (8.1.7)
    create table TPERSON(ID number(10),NAME varchar2(20),...);
    create index I_NORMAL_TPERSON_NAME on TPERSON(NAME);
    create index I_FUNCTION_TPERSON_NAME on TPERSON(UPPER(NAME));
    The following two statements run very fast on a large table
    and the execution-plan asure the usage of the indexes
    (-while the session is appropriate configured and the table is analyzed):
    1)     select count(ID) FROM TPERSON where upper(NAME) like 'MIL%';
    2)     select count(ID) from TPERSON where NAME like 'Mil%' or (3=5);
    In particular we see that a normal index is used while the where-clause contains
    an OR-CONDITION.
    But if we try the similarly select-statement
    3)     select count(ID) FROM TPERSON where upper(NAME) like 'MIL%' or (3=5);
    the CBO will not use the function-index I_FUNCTION_TPERSON_NAME and we have a full table scan in the execution-plan.
    (This behavior we only expect with views but not with indexes.)
    We ask for an advice like a hint, which enable the CBO-usage
    of function-based indexes in connection with OR.
    This problem seems to be artificial because it contains this dummy logic:
         or (3=5).
    This steams from an prepared statement, where this kind of boolean
    flag reduce the amount of different select-statements needed for
    covering the hole business-logic, while using bind-variables for the
    concrete query-parameters.
    A more realistic (still boild down) version of our select-statement is:
    select * FROM TPERSON
    where (upper(NAME) like 'MIL%' or (NAME is null))
    and (upper(FIRSTNAME) like 'MICH% or (FIRSTNAME is null))
    and ...;
    thank you for time..
    email: [email protected]

    In the realistic statement you write :
    select * FROM TPERSON
    where (upper(NAME) like 'MIL%' or (NAME is null))
    and (upper(FIRSTNAME) like 'MICH% or (FIRSTNAME is null))
    and ...;
    as far as i know, NULL values are not indexed, "or (NAME is NULL)" have to generate a full table scan.
    HTH
    We have some problems with functin-based indexes and
    the or-condition in a where-clause.
    --We use Oracle 8i (8.1.7)
    create table TPERSON(ID number(10),NAME varchar2(20),...);
    create index I_NORMAL_TPERSON_NAME on TPERSON(NAME);
    create index I_FUNCTION_TPERSON_NAME on TPERSON(UPPER(NAME));
    The following two statements run very fast on a large table
    and the execution-plan asure the usage of the indexes
    (-while the session is appropriate configured and the table is analyzed):
    1)     select count(ID) FROM TPERSON where upper(NAME) like 'MIL%';
    2)     select count(ID) from TPERSON where NAME like 'Mil%' or (3=5);
    In particular we see that a normal index is used while the where-clause contains
    an OR-CONDITION.
    But if we try the similarly select-statement
    3)     select count(ID) FROM TPERSON where upper(NAME) like 'MIL%' or (3=5);
    the CBO will not use the function-index I_FUNCTION_TPERSON_NAME and we have a full table scan in the execution-plan.
    (This behavior we only expect with views but not with indexes.)
    We ask for an advice like a hint, which enable the CBO-usage
    of function-based indexes in connection with OR.
    This problem seems to be artificial because it contains this dummy logic:
         or (3=5).
    This steams from an prepared statement, where this kind of boolean
    flag reduce the amount of different select-statements needed for
    covering the hole business-logic, while using bind-variables for the
    concrete query-parameters.
    A more realistic (still boild down) version of our select-statement is:
    select * FROM TPERSON
    where (upper(NAME) like 'MIL%' or (NAME is null))
    and (upper(FIRSTNAME) like 'MICH% or (FIRSTNAME is null))
    and ...;
    thank you for time..
    email: [email protected]

  • Using if logic in the where clause of a select statement

    I have a select clause. And in the select clause there is a variable all_off_trt that can be 'Y' or 'N'.
    In the where clause I want to make it so that if a form variable is checked and all_off_trt is 'Y' then
    exclude it else if the form variable isn't checked then select it no matter what all_off_trt is.
    Is there any way to include either and if statement or a case statement within the where clause to acheive this? If not is there another way of doing it?
    Basically I am looking for a case statement like this
    case
    when all_off_trt = 'Y' and mail_para.code = 'Y' then false
    else true
    end
    Message was edited by:
    Tugnutt7

    Ok, so that really doesn't solve my problem. I have 3 different fields that I need to do that with. Each combining in a select statement to print an email list, as well as other thing limiting the where clause.
    This is currently what I have, tested and working 100%.
    cursor email_cur is
         select unique p.email,s.all_off_trt,s.all_deceased,s.no_enroll
    from participant p, trialcom t, ethics s
    where p.status='A'
    and p.surname=t.surname
    and p.initials=t.initials
    and s.trial_cd = t.tricom
    and s.centre = t.centre
    and p.email is not null
    and (t.centre in (select code from mail_parameters where user_name=user and mail_para='CENTRE')
    or 'XX' in (select code from mail_parameters where user_name=user and mail_para='CENTRE'))
    and (t.tricom in (select code from mail_parameters where user_name=user and mail_para='TRIAL')
    or 'XX' in (select code from mail_parameters where user_name=user and mail_para='TRIAL'))
    and (t.role in (select code from mail_parameters where user_name=user and mail_para='ROLE')
    or 'XX' in (select code from mail_parameters where user_name=user and mail_para='ROLE'))
    and (p.country in (select code from mail_parameters where user_name=user and mail_para='COUNTRY')
    or 'XX' in (select code from mail_parameters where user_name=user and mail_para='COUNTRY'))
    and (t.represent in (select code from mail_parameters where user_name=user and mail_para='REPRESENT')
    or 'XX' in (select code from mail_parameters where user_name=user and mail_para='REPRESENT'));
    This is in a program unit that runs when a button is clicked. At the end of that I need to add on the 3 case statements that help further narrow down the selection of emails to be printed. Then it prints the emails selected from this statement into a file. So it has to be done right in the select statement. The three table variables are the all_off_trt, all_deceased, and no_enroll. The form has 3 checkboxes. One for each, that when checked (giving the variable associated with the checkboxes a value of 'Y') excludes all emails that have a 'Y' in the coresponding table variable.

  • Values from a Multi-Select in the where clause of a Select statement

    I have a web page that solicits query parameters from the user.
    The selections that the user makes will populate the WHERE clause of a Select statement.
    One of the controls on the page is a multi-select control.
    When this page posts, I would like to execute a Select statement wherein the selected values from this control appear in the .. Column IN ( <list here> ) portion of the WHERE clause.
    This is an extremely common scenario, but I cannot seem to locate a how-to or message thread that addresses this specific case.
    I have an idea that it may involve dynamic SQL or Execute Immediate, but cannot seem to pin down the answer.
    Any help would be greatly appreciated!

    anonymous - As illustrated here: Re: Search on a typed in list of values
    Scott

  • Re: [iPlanet-JATO] How to make an OR in the WHERE clause of a SELECT

    Harry,
    If you get a reference to your model, you can set the
    whereClauseOverride with exactly the string you want to use. Keep in
    mind that you are dealing with a the raw SQL where clause, therefore,
    you must use the actual table column names and not the model's logical
    field names as they could be different.
    QueryModelBase queryModel = (QueryModelBase)getModel(PersonModel.class);
    // you must add the "WHERE" as well
    String whereClause = "WHERE firstName LIKE '%max' OR lastName LIKE '%max%'";
    queryModel.setWhereClauseOverride(whereClause);
    Keep in mind that this will override all where criteria: static and
    dynamic where criteria. Static criteria can be declared in your model
    class: setStaticWhereCriteriaString(STATIC_WHERE_CRITERIA).
    You could optionally get the entire SQL statement and replace the
    __WHERE__ token yourself with a string replace technique. In fact, if
    you want to add an ORDER BY, you will need to get the SQL and append to
    the end.
    queryModel.getSelectSQL();
    Hope this helps. Let me know if you have any questions
    craig
    hlamer wrote:
    Hi,
    if I add criterias to my model
    with "SelectQueryModel.addUserWhereCriterion()" they will be concated
    with AND.
    How can I add a criteria with OR?
    I want something like:
    SELECT personId, firstName, lastName
    FROM Person
    WHERE firstName LIKE "%max"
    OR lastName LIKE "%max%"
    Thanks.
    Harry
    For more information about JATO, including download information, please visit:
    http://developer.iplanet.com/tech/appserver/framework/index.jsp

    Rewritten your query wuth tags as well
    &#123;code&#125;select  "P_CIRCUITS_FIBER"."PORTS_1",
            "P_CIRCUITS_FIBER"."PORTS_2",
            CASE WHEN CPORT.ID = (select REGEXP_SUBSTR(ports_1,'[^,]+',1,1) from p_circuits_fiber)
                 THEN "CPORT"."PORT_NO" END PORT_NO_1,
            CASE WHEN CPORT.ID = (select REGEXP_SUBSTR(ports_2,'[^,]+',1,1) from p_circuits_fiber)
                 THEN "CPORT"."PORT_NO" END PORT_NO_2
    from    "CPORT",
            "P_CIRCUITS_FIBER"
    where   p_circuits_fiber.fiber_id = :P4000_CIRCUIT_NO
    and     (select REGEXP_SUBSTR(ports_1,'[^,]+',1,1) from p_circuits_fiber) = "CPORT"."PORT_NO"  "PORT_NO_1"
    and     (select REGEXP_SUBSTR(ports_2,'[^,]+',1,1) from p_circuits_fiber) = "CPORT"."PORT_NO"  "PORT_NO_2"&#123;code&#125;
    Now we can see two columns references which should not be there.
    I even not sure to understand why those two conditions are in the WHERE clause. But for sure, CPORT.ID cannot be equal to two values unless they are same.
    Is there only one row in p_circuits_fiber ?
    Nicolas.

  • Performance with dates in the where clause

    Performance with dates in the where clause
    CREATE TABLE TEST_DATA
    FNUMBER NUMBER,
    FSTRING VARCHAR2(4000 BYTE),
    FDATE DATE
    create index t_indx on test_data(fdata);
    query 1: select count(*) from TEST_DATA where trunc(fdate) = trunc(sysdate);
    query 2: select count(*) from TEST_DATA where fdate between trunc(sysdate) and trunc(SYSDATE) + .99999;
    query 3: select count(*) from TEST_DATA where fdate between to_date('21-APR-10', 'dd-MON-yy') and to_date('21-APR-10 23:59:59', 'DD-MON-YY hh24:mi:ss');
    My questions:
    1) Why isn't the index t_indx used in Execution plan 1?
    2) From the execution plan, I see that query 2 & 3 is better than query 1. I do not see any difference between execution plan 2 & 3. Which one is better?
    3) I read somewhere - "Always check the Access Predicates and Filter Predicates of Explain Plan carefully to determine which columns are contributing to a Range Scan and which columns are merely filtering the returned rows. Be sceptical if the same clause is shown in both."
    Is that true for Execution plan 2 & 3?
    3) Could some one explain what the filter & access predicate mean here?
    Thanks in advance.
    Execution Plan 1:
    SQL> select count(*) from TEST_DATA where trunc(fdate) = trunc(sysdate);
    COUNT(*)
    283
    Execution Plan
    Plan hash value: 1486387033
    | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
    | 0 | SELECT STATEMENT | | 1 | 9 | 517 (20)| 00:00:07 |
    | 1 | SORT AGGREGATE | | 1 | 9 | | |
    |* 2 | TABLE ACCESS FULL| TEST_DATA | 341 | 3069 | 517 (20)| 00:00:07 |
    Predicate Information (identified by operation id):
    2 - filter(TRUNC(INTERNAL_FUNCTION("FDATE"))=TRUNC(SYSDATE@!))
    Note
    - dynamic sampling used for this statement
    Statistics
    4 recursive calls
    0 db block gets
    1610 consistent gets
    0 physical reads
    0 redo size
    412 bytes sent via SQL*Net to client
    380 bytes received via SQL*Net from client
    2 SQL*Net roundtrips to/from client
    0 sorts (memory)
    0 sorts (disk)
    1 rows processed
    Execution Plan 2:
    SQL> select count(*) from TEST_DATA where fdate between trunc(sysdate) and trunc(SYSDATE) + .99999;
    COUNT(*)
    283
    Execution Plan
    Plan hash value: 1687886199
    | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
    | 0 | SELECT STATEMENT | | 1 | 9 | 3 (0)| 00:00:01 |
    | 1 | SORT AGGREGATE | | 1 | 9 | | |
    |* 2 | FILTER | | | | | |
    |* 3 | INDEX RANGE SCAN| T_INDX | 283 | 2547 | 3 (0)| 00:00:01 |
    Predicate Information (identified by operation id):
    2 - filter(TRUNC(SYSDATE@!)<=TRUNC(SYSDATE@!)+.9999884259259259259259
    259259259259259259)
    3 - access("FDATE">=TRUNC(SYSDATE@!) AND
    "FDATE"<=TRUNC(SYSDATE@!)+.999988425925925925925925925925925925925
    9)
    Note
    - dynamic sampling used for this statement
    Statistics
    7 recursive calls
    0 db block gets
    76 consistent gets
    0 physical reads
    0 redo size
    412 bytes sent via SQL*Net to client
    380 bytes received via SQL*Net from client
    2 SQL*Net roundtrips to/from client
    0 sorts (memory)
    0 sorts (disk)
    1 rows
    Execution Plan 3:
    SQL> select count(*) from TEST_DATA where fdate between to_date('21-APR-10', 'dd-MON-yy') and to_dat
    e('21-APR-10 23:59:59', 'DD-MON-YY hh24:mi:ss');
    COUNT(*)
    283
    Execution Plan
    Plan hash value: 1687886199
    | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
    | 0 | SELECT STATEMENT | | 1 | 9 | 3 (0)| 00:00:01 |
    | 1 | SORT AGGREGATE | | 1 | 9 | | |
    |* 2 | FILTER | | | | | |
    |* 3 | INDEX RANGE SCAN| T_INDX | 283 | 2547 | 3 (0)| 00:00:01 |
    Predicate Information (identified by operation id):
    2 - filter(TO_DATE('21-APR-10','dd-MON-yy')<=TO_DATE('21-APR-10
    23:59:59','DD-MON-YY hh24:mi:ss'))
    3 - access("FDATE">=TO_DATE('21-APR-10','dd-MON-yy') AND
    "FDATE"<=TO_DATE('21-APR-10 23:59:59','DD-MON-YY hh24:mi:ss'))
    Note
    - dynamic sampling used for this statement
    Statistics
    7 recursive calls
    0 db block gets
    76 consistent gets
    0 physical reads
    0 redo size
    412 bytes sent via SQL*Net to client
    380 bytes received via SQL*Net from client
    2 SQL*Net roundtrips to/from client
    0 sorts (memory)
    0 sorts (disk)
    1 rows processed

    Hi,
    user10541890 wrote:
    Performance with dates in the where clause
    CREATE TABLE TEST_DATA
    FNUMBER NUMBER,
    FSTRING VARCHAR2(4000 BYTE),
    FDATE DATE
    create index t_indx on test_data(fdata);Did you mean fdat<b>e</b> (ending in e)?
    Be careful; post the code you're actually running.
    query 1: select count(*) from TEST_DATA where trunc(fdate) = trunc(sysdate);
    query 2: select count(*) from TEST_DATA where fdate between trunc(sysdate) and trunc(SYSDATE) + .99999;
    query 3: select count(*) from TEST_DATA where fdate between to_date('21-APR-10', 'dd-MON-yy') and to_date('21-APR-10 23:59:59', 'DD-MON-YY hh24:mi:ss');
    My questions:
    1) Why isn't the index t_indx used in Execution plan 1?To use an index, the indexed column must stand alone as one of the operands. If you had a function-based index on TRUNC (fdate), then it might be used in Query 1, because the left operand of = is TRUNC (fdate).
    2) From the execution plan, I see that query 2 & 3 is better than query 1. I do not see any difference between execution plan 2 & 3. Which one is better?That depends on what you mean by "better".
    If "better" means faster, you've already shown that one is about as good as the other.
    Queries 2 and 3 are doing different things. Assuming the table stays the same, Query 2 may give different results every day, but the results of Query 3 will never change.
    For clarity, I prefer:
    WHERE     fdate >= TRUNC (SYSDATE)
    AND     fdate <  TRUNC (SYSDATE) + 1(or replace SYSDATE with a TO_DATE expression, depending on the requirements).
    3) I read somewhere - "Always check the Access Predicates and Filter Predicates of Explain Plan carefully to determine which columns are contributing to a Range Scan and which columns are merely filtering the returned rows. Be sceptical if the same clause is shown in both."
    Is that true for Execution plan 2 & 3?
    3) Could some one explain what the filter & access predicate mean here?Sorry, I can't.

  • How to change recordset bahaviour to accept dynamic column names in the where clause

    Hi
    im using php-mysql and i make a recordset and i want to make the column names in the where clause to be dynamic like
    "select id,name from mytable where $tablename-$myvar";
    but when i do this my i break the recordset and it disappear
    and when i use variables from advanced recordset it only dynamic for the value of the column not for the column name
    and when i write the column name to dynamic as above by hand it truns a red exclamation mark on the server behaviour panel
    so i think the only way is to change the recordset behaviour is it? if so How to make it accept dynamic column names?
    thanks in advance.

    As bregent has already explained to you, customizing the recordset code will result in Dreamweaver no longer recognizing the server behavior. This isn't a problem, but it does mean that you need to lay out your dynamic text with the Bindings panel before making any changes. Once you have changed the recordset code, the Bindings panel will no longer recognize the recordset fields.
    Using a variable to choose a column name is quite simple, but you need to take some security measures to ensure that the value passed through the query string isn't attempting SQL injection. An effective way of doing this is to create an array of acceptable column names, and check that the value matches.
    // create array of acceptable values
    $valid = array('column_name1', 'column_name2', 'column_name3');
    // if the query string contains an acceptable column name, use it
    if (isset($_GET['colname']) && in_array($_GET['colname'], $valid)) {
      $col = $GET['colname'];
    } else {
      // set a default value if the submitted one was invalid
      $col = 'column_name1'
    You can then use $col directly in the SQL query.

  • JSP, Data Web Bean, BC4J: Setting the where clause of a View Object at run time

    Hi,
    I am trying to develop a data web bean in which the where clause of a View Object will be set at run time and the results of the query then displayed.
    My BC4J components are located in one project while the coding for the data web bean is in another project. I used the following code bu t it does not work. Could you please let me know what I am doing wrong?
    public void populateOSTable(int P_EmpId)
    String m_whereString = "EmpView.EMP_ID = " + P_EmpId;
    String m_OrderBy = "EmpView.EMP_NAME";
    oracle.jbo.ApplicationModule appModule = null;
    ViewObject vo = appModule.findApplicationModule("EMPBC.EMPAppModule").findViewObject("EMPBC.EMPView");
    vo.setWhereClause(m_whereString);
    vo.setOrderByClause(m_OrderBy);
    vo.executeQuery();
    vo.next();
    String empName numAttrs = vo.getAttribute(EmpName);
    System.out.println(empName);
    Thanks.

    <BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by JDev Team (Laura):
    Here is how I have usually done mine:
    1. In the JSP, use a RowsetNavigator bean to set the where clause and execute the query.
    2. Use a custom web bean to process the results of the query (print to HTML).
    for example:
    <jsp:useBean class="oracle.jbo.html.databeans.RowsetNavigator" id="rsn" scope="request" >
    <%
    // get the parameter from the find form
    String p = request.getParameter("p");
    String s = request.getParameter("s");
    // store the information for reference later
    session.putValue("p", p);
    session.putValue("s", s);
    // initialize the app module and view object
    rsn.initialize(application,session, request,response,out,"wt_bc_WT_bcModule.wtjoinView");
    // set the where clause string
    String theclause = "presname = '" + p + "' AND slideno=" + s;
    // set the where clause for the VO
    rsn.getRowSet().getViewObject().setWhereClause(theclause);
    rsn.getRowSet().getViewObject().executeQuery();
    rsn.getRowSet().first();
    %>
    </jsp:useBean>
    <jsp:useBean class="wt_bc.walkthruBean" id="wtb" scope="request" >
    <%
    // initialize the app module and VO
    wtb.initialize(application,session, request,response,out,"wt_bc_WT_bcModule.wtjoinView");
    wtb.render();
    %>
    In this case, the render method of my custom web bean mostly gets some session variables, and prints various content depending on the session variable values.
    Hope this helps.
    </jsp:useBean><HR></BLOCKQUOTE>
    Laura can you give the code of your walkthru bean? i wna't to initialize a viewobject, set the where clause and give that viewobject back to initialize my navigatorbar.
    Nathalie
    null

  • Trouble using a function in the where clause

    Hello,
    I am using a function found at ask.tom.oracle.com which converts a long data type to a character. The function is returning an error when it is placed in the where clause. The sql statement , error message and the function from ask tom are shown below. Does anyone know how to fix this?
    <pre>
    SELECT A.FLDPHYSICAL,
    A.FLDEXPOSURE,
    A.FLDDATEDUE,
    A.FLDDATELAST,
    A.FLDEMPLOYEE,
    B.FLDBDATE,
    B.FLDMAILSTOP,
    B.FLDREC_NUM,
    B.FLDLNAME,
    B.FLDMI,
    B.FLDFNAME,
    B.FLDBDATE,
    B.FLDDEPT,
    B.FLDSTATUS,
    B.FLDSSN,
    B.FLDHOMEPHON,
    B.FLDWORKPHON,
    B.FLDID,
    B.FLDDIVISION
    FROM REQEXAM A,
    EMPLOYEE B,
    EMPLOYEE_MEMO C
    WHERE A.FLDEMPLOYEE = B.FLDREC_NUM
    AND b.flduserstr = c.fldrec_num
    AND OHM_PKG.GET_LONG('EMPLOYEE_MEMO', 'FLDDATA', C.ROWID) LIKE '%CDL YES%'
    AND A.FLDDATEDUE > '01/01/1900'
    AND A.FLDPHYSICAL ='CDP'
    ORDER BY B.FLDDIVISION,
    B.FLDLNAME,
    B.FLDFNAME,
    B.FLDMI,
    A.FLDDATEDUE
    The error message
    Error at Command Line:26 Column:4
    Error report:
    SQL Error: ORA-00904: "OHM_PKG"."GET_LONG": invalid identifier
    00904. 00000 - "%s: invalid identifier"
    create or replace
    PACKAGE OHM_PKG AS
    /* TODO enter package declarations (types, exceptions, methods etc) here */
    function getlong( p_tname in varchar2,p_cname in varchar2,p_rowid in rowid ) return varchar2;
    END OHM_PKG;
    create or replace
    PACKAGE BODY OHM_PKG AS
    function getlong( p_tname in varchar2,p_cname in varchar2,p_rowid in rowid ) return varchar2 as
    l_cursor integer default dbms_sql.open_cursor;
    l_n number;
    l_long_val varchar2(4000);
    l_long_len number;
    l_buflen number := 4000;
    l_curpos number := 0;
    begin
    dbms_sql.parse( l_cursor,
    'select ' || p_cname || ' from ' || p_tname ||
    ' where rowid = :x',
    dbms_sql.native );
    dbms_sql.bind_variable( l_cursor, ':x', p_rowid );
    dbms_sql.define_column_long(l_cursor, 1);
    l_n := dbms_sql.execute(l_cursor);
    if (dbms_sql.fetch_rows(l_cursor)>0)
    then
    dbms_sql.column_value_long(l_cursor, 1, l_buflen, l_curpos ,
    l_long_val, l_long_len );
    end if;
    dbms_sql.close_cursor(l_cursor);
    return l_long_val;
    end getlong;
    END OHM_PKG;
    </prev>

    Remove the '_' from the function's name as below:
    AND OHM_PKG.GETLONG('EMPLOYEE_MEMO', 'FLDDATA', C.ROWID) LIKE '%CDL YES%'

  • Not able to set the where clause params

    Hi,
    My version of apps is 12.1.3.
    I created a page with a searchRN and resultRN (LinesVO). (Not a query/view link) . I am passing the id from header to the VO to restrict the linesVO
    The controller correctly passes the id from searchRN to AM, but in AM, the where clause is not set and I am not getting the desired result:
    My AM Code:
        public void InvokeGo(String Hdrval)
                    LineVOImpl LineVO1 = getLineVO1();
                    LineVO1.setWhereClauseParams(null); // Always reset
                     System.out.println("AMIMPL:Hdrval = "+ Hdrval);
                    <prints the header_Value which is passed from CO>
                       if (Hdrval           == null        
                                            System.out.println("Inside Null If");  
                                            String message = "Please provide atleast one input to any of these search field";
                                            throw new OAException(message, OAException.ERROR);
                                    else   
                                        System.out.println("Not All Parameters are Null.Building Where Clause");
                                         < prints the line above>
                                        LineVO1.setWhereClause
                                        ("Header_name = :1");
                        System.out.println("Paremeter Set are: Header_name:"+Hdrval);
                        <prints the above line like :   Paremeter Set are: Header_name:Hdr_Name_1
                        LineVO1.setWhereClauseParam(0,Hdrval);
                        System.out.println("Inside MainAM invokeGO Method:"+LineVO1.getQuery());
                        < prints:Inside MainAM invokeGO Method:SELECT * FROM (select LINE_ID,hdr.HEADER_ID,LINE_NUMBER,LINE_NAME,Attach,hdr.header_name from xxtr_hdr hdr, xxtr_line line
    where hdr.header_id=line.header_id) QRSLT  WHERE (Header_name = :1)>
                        LineVO1.executeQuery();
    The issue is in the SQL build. I guess after setting the where clause, it should appear like :
    QRSLT  WHERE (Header_name = "Hdr_Name_1"
    Thanks

    Hu Sumit,
    I am doing that:
    LineVO1.setWhereClauseParam(0,Hdrval);
    before executequery. I even hard coded
    LineVO1.setWhereClauseParam(0,"XXXX");
    but still it din't work. I guess I am missing something small. because I have done this thing a lot of times earlier and it had worked.

  • How to retrieve the 'Where Clause' text?

    Hello all,
    I have created a package to retrieve all the DML's executed against the database for the day, for a particular user. DBMS_LOGMNR package was used to retrieve DMLs. But the DMLs retrieved have their 'WHERE' clause text converted to ROWID's. I need to find out the 'WHERE' clause with the parameters.
    I tried retrieving values from the v$sql views, but that information is cryptic and very volatile.
    Is there a way to retrieve the 'Where' clause? If not, is there a way to retrieve the 'WHERE' clause information using a trigger against the corresponding table.
    I am desparately lookin'for a solution. Hope someone out there can help me out.
    Regards,
    Prabu Raghav.

    Hi Andrew,
    Thanks for the suggestion.
    I am using Oracle 8i not 9i.FGA using DBMS_RLS let's me add policies and retrieve all other information about a user except the SQL statement that's executed by the user.
    I want to retrieve the Current sql statement executed against the table by a particular user and record it.
    Any suggestions?
    Regards,
    Prabu Raghav.

  • How do I modify the WHERE clause in my SQL query?

    This seems like such a straight-forward part of the report design, but I'm fairly new to Crystal Reports and I only have experience with modifying reports someone else has already written.  In this particular case, I just need to modify the WHERE clause of the SQL query.  I can select Show SQL Query and see what statement is being used to select data, but I can't find where to modify it since it's grayed out.  I see how to change the selection criteria, parameters, grouping, etc...just not the WHERE clause.  The report is linked to a database used for reporting with a table created and populated by a stored procedure.  I don't need to modify the stored procedure because the data I want to filter by is currently in the table--I just don't know how to filter by what I need.  Here's part of the query:
    SELECT "rpt_dist"."startdate", "rpt_dist"."transtype", "rpt_dist"."laborcode", "rpt_dist"."crewid", "rpt_dist"."regularhrs" FROM   "Reporting"."dbo"."rpt_dist" "rpt_dist"
    WHERE  (rpt_dist."transtype" <> 'WORK' AND rpt_dist."transtype" <> 'WMATL') AND rpt_dist."laborcode" LIKE 'S%' AND (rpt_dist."crewid" = 'HOUS' OR rpt_dist."crewid" = 'HOUS2' ...
    I would like to add another crewid to the WHERE clause.  Thanks for any input.

    1.Open the report in the crystal designer
    2.Go to the field explorer(if hidden go to view menu->field explorer)
    3.Rt. click on the database fields->choose database expert
    4.Now you will see 2 columns-Available DataSource  and Selected Tables
    5.Rt. click on the object(ex.command) available in the Selected Tables column->Choose Edit command
    6.A new Modify Command window will appear,here you can edit your SQL Query
    I get to step 4 and I see the two columns including my database and the report table, but there is no command object available.  If I right-click on my table, I can just view the Properties. ??
    As for the other tip to modify the record selection:  I don't see anywhere the other crewid values are set and if I add the one I'm missing, it doesn't modify the existing SQL Query and when I preview the report it throws off the results so that no data displays??
    I'm using Crystal Reports 11.5 if that makes a difference.  Thanks again.

  • 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

Maybe you are looking for