To_Date function in the Where Clause

Hello All,
I'm having an issue using the to_date function that has me quite perplexed.
I have two varchar2 fields, one with a date value in the format Mon, DD YYYY, the other has a time value in the format HH:MI PM.
When I run my query one of the columns I retrieve looks like this TO_DATE (d4.adate || e4.atime, 'Mon DD, YYYYHH:MI PM'). The two fields are concatenated together and converted to a date. This works fine.
My problem occurs when I attempt to apply the same logic to the where clause of the aforementioned query. e.g. when I add the following criteria to my query and TO_DATE (d4.adate || e4.atime, 'Mon DD, YYYYHH:MI PM') <= sysdate I get an ORA-01843: not a valid month error.
To further illustrate my problem here are the two queries:
Select d4.adate, e4.atime, TO_DATE (d4.adate || e4.atime, 'Mon DD, YYYYHH:MI PM')
from ....
where ....
The above query works.
Select d4.adate, e4.atime, TO_DATE (d4.adate || e4.atime, 'Mon DD, YYYYHH:MI PM')
from ....
where ....
and TO_DATE (d4.adate || e4.atime, 'Mon DD, YYYYHH:MI PM') <= sysdate
The second query does not work.
The tables used and the limiting criteria are identical, except for the last one.
Does anyone have any ideas why this could be happening.
er

Hello,
Check this out. It does work. Do cut n paste sample
data from your tables.
SQL> desc test
Name Null? Type
ID NUMBER
DDATE VARCHAR2(20)
DTIME VARCHAR2(20)
SQL> select * from test;
ID DDATE DTIME
1 Jan, 10 2006 12:32 PM
2 Mar, 11 2005 07:10 AM
3 Apr, 13 2006 03:12 AM
4 Nov, 15 2003 11:22 PM
5 Dec, 20 2005 09:12 AM
6 Oct, 30 2006 10:00 AM
7 Jan, 10 2006 12:32 PM
8 Apr, 11 2005 07:10 AM
9 May, 13 2006 03:12 AM
10 Sep, 15 2003 11:22 PM
11 Oct, 20 2005 09:12 AM
12 Dec, 30 2006 10:00 AM
12 rows selected.
SQL> select id, ddate, dtime,
2 to_date(ddate||dtime,'Mon, DD YYYYHH:MI PM') AA,
A,
3 to_char(to_date(ddate||dtime,'Mon, DD YYYYHH:MI
MI PM'),'Mon, DD YYYYHH:MI PM') BB
4 from test;
ID DDATE DTIME
DTIME AA BB
1 Jan, 10 2006 12:32 PM
12:32 PM 10-JAN-06 Jan, 10 200612:32 PM
2 Mar, 11 2005 07:10 AM
07:10 AM 11-MAR-05 Mar, 11 200507:10 AM
3 Apr, 13 2006 03:12 AM
03:12 AM 13-APR-06 Apr, 13 200603:12 AM
4 Nov, 15 2003 11:22 PM
11:22 PM 15-NOV-03 Nov, 15 200311:22 PM
5 Dec, 20 2005 09:12 AM
09:12 AM 20-DEC-05 Dec, 20 200509:12 AM
6 Oct, 30 2006 10:00 AM
10:00 AM 30-OCT-06 Oct, 30 200610:00 AM
7 Jan, 10 2006 12:32 PM
12:32 PM 10-JAN-06 Jan, 10 200612:32 PM
8 Apr, 11 2005 07:10 AM
07:10 AM 11-APR-05 Apr, 11 200507:10 AM
9 May, 13 2006 03:12 AM
03:12 AM 13-MAY-06 May, 13 200603:12 AM
10 Sep, 15 2003 11:22 PM
11:22 PM 15-SEP-03 Sep, 15 200311:22 PM
11 Oct, 20 2005 09:12 AM
09:12 AM 20-OCT-05 Oct, 20 200509:12 AM
12 Dec, 30 2006 10:00 AM
10:00 AM 30-DEC-06 Dec, 30 200610:00 AM
12 rows selected.
SQL> select id, ddate, dtime,
to_date(ddate||dtime,'Mon, DD YYYYHH:MI PM')
2 from test
3 where id > 3
4 and to_date(ddate||dtime,'Mon, DD YYYYHH:MI PM')
') <= trunc(sysdate);
ID DDATE DTIME
DTIME TO_DATE(D
4 Nov, 15 2003 11:22 PM
11:22 PM 15-NOV-03
5 Dec, 20 2005 09:12 AM
09:12 AM 20-DEC-05
7 Jan, 10 2006 12:32 PM
12:32 PM 10-JAN-06
8 Apr, 11 2005 07:10 AM
07:10 AM 11-APR-05
10 Sep, 15 2003 11:22 PM
11:22 PM 15-SEP-03
11 Oct, 20 2005 09:12 AM
09:12 AM 20-OCT-05
6 rows selected.
SQL> select id, ddate, dtime,
to_date(ddate||dtime,'Mon, DD YYYYHH:MI PM')
2 from test
3 where id > 3
4 and to_date(ddate||dtime,'Mon, DD YYYYHH:MI PM')
') <= sysdate;
ID DDATE DTIME
DTIME TO_DATE(D
4 Nov, 15 2003 11:22 PM
11:22 PM 15-NOV-03
5 Dec, 20 2005 09:12 AM
09:12 AM 20-DEC-05
7 Jan, 10 2006 12:32 PM
12:32 PM 10-JAN-06
8 Apr, 11 2005 07:10 AM
07:10 AM 11-APR-05
10 Sep, 15 2003 11:22 PM
11:22 PM 15-SEP-03
11 Oct, 20 2005 09:12 AM
09:12 AM 20-OCT-05
6 rows selected.
-SriSorry Sri, but I fail to see what you mean. How is what you're doing any different than what I'm doing?

Similar Messages

  • SUBSTR function in the where clause

    HI
    I want to get a number of 15 digits from a column where the user only know the last 10 digits.
    So that when the user enter a number with 10 digits, only the record of that specific number should be displayed.
    And then when the user did not enter any number all the records in the table should be displayed.(this part works fine)
    The problem is: when the user enters any last digits( last, second last, thirth last and so on) the records which satisfy this are retrieved, which is not supose to be the case.
    I' am trying to use the substr function in the where clause but I'm not sure if it's working or not becasue the result of the query is just the same as before i used the substr.
    Thanks

    better to pad with '*' me thinks in case u have a number ending with 0's:
      1  select empno,ename
      2  from emp
      3* where empno like '%'||lpad('&1',2,'*')
    SQL> /
    Enter value for 1: 0
    old   3: where empno like '%'||lpad('&1',2,'*')
    new   3: where empno like '%'||lpad('0',2,'*')
    no rows selected
    SQL> /
    Enter value for 1: 00
    old   3: where empno like '%'||lpad('&1',2,'*')
    new   3: where empno like '%'||lpad('00',2,'*')
         EMPNO ENAME
          7900 JAMES
    SQL> /
    Enter value for 1:
    old   3: where empno like '%'||lpad('&1',2,'*')
    new   3: where empno like '%'||lpad('',2,'*')
         EMPNO ENAME
          7369 SMITH
          7499 ALLEN
          7521 WARD
          7566 JONES
          7654 MARTIN
          7698 BLAKE
          7782 CLARK
          7788 SCOTT
          7839 KING
          7844 TURNER
          7876 ADAMS
         EMPNO ENAME
          7900 JAMES
          7902 FORD
          7934 MILLER
    14 rows selected.

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

  • CBO and functions in the WHERE clause

    Hi,
    Can anyone point me to any documents describing how the cost based optimizer treats functions in a WHERE clause?
    For example, in
    select ...
    from   ...
    where  ...
    and    my_package.my_function( t.some_column ) = 'Y'
    ...does the CBO treat "my_package.my_function" as a black box or does it go into the body of "my_package.my_function" and take into consideration the associated costs of all the SELECT statements in the function?
    I've tried a few simple tests to answer the question, but I've received conflicting results. Has anyone had any experience with this?
    Thanks in advance for your help.

    Thanks for the info. Justin.
    <br><br>
    I think I've solved my problem, but I'll repeat it here in case it helps anyone else. Here is a very simplified example of what I was seeing.
    <br><br>
    A query like this:
        select
          a.party_id, b.cust_account_id
        from
          hz_parties a,
          hz_cust_accounts b
        where
          a.party_id = b.party_id
          and mis_hz_merge_veto_pkg.party_merge_will_be_vetoed(a.party_id) = 'N'was returning a drastically different execution plan than this
        select
          a.party_id, b.cust_account_id
        from
          hz_parties a,
          hz_cust_accounts b
        where
          a.party_id = b.party_id
          and mis_hz_merge_veto_pkg.account_merge_will_be_vetoed(b.cust_account_id) = 'N'I initially thought the difference was due to the fact that I was using different functions in the last line, but then I tried this version
        select
          a.party_id, b.cust_account_id
        from
          hz_parties a,
          hz_cust_accounts b
        where
          a.party_id = b.party_id
          and mis_hz_merge_veto_pkg.party_merge_will_be_vetoed(b.party_id) = 'N'and found that it gave me a different execution plan than the first SELECT as well, even though it used the same function. The difference seems to stem from the columns I use in the function parameter and not the choice of function.

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

  • Function-based Index and an OR-condition in the WHERE-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.
    (This behavior we only expect with views but not with indexes.)
    We ask for an advice like an 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 prepared select-statement run in
    SQL Plus:
    define x_name = 'MIL%';
    define x_firstname = '';
    select * FROM TPERSON
    where (upper(NAME) like '&x_name' or ( '&x_name' = ''))
    and (upper(FIRSTNAME) like '&x_firstname' or ('&x_firstname' = ''))
    and ...;
    In particular we dont refernce the tablecolumn , but the QUERY-Parameter
    yield the second boolean value in the or-condition.
    The problem is that this condition ('&x_name' = '') dont use any index.
    thanks a lot for spending your time with this problem

    Try
    SELECT /*+ RULE */
    as your hint. I don't have the book with me, but this last weekend I read a section about your very problem. The book was a Oracle Press gold cover about Oracle 8i Performance tuning. If you e-mail me I can quote you the chapter when I get home Friday.

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

  • Pass values dynamically to the WHERE clause in SFAPI

    Hi there
    We have a requirement to pass values dynamically (in the run-time of the interface) to the WHERE condition to our SFAPI query.
    Eg -
    SELECT person, personal_information, address_information, phone_information, email_information, employment_information, job_information, compensation_information, paycompensation_recurring, paycompensation_non_recurring, job_relation, accompanying_dependent,         global_assignment_information, direct_deposit, national_id_card, person_relation
              FROM CompoundEmployee
              WHERE last_modified_on &gt;= to_date('LAST_RUN_DATE')  AND
                           last_modified_on &lt;= to_date('CURRENT_RUN_TIME') 
    LAST_RUN_DATE is stored in a custom entity for which we execute another OData query. The custom entity is updated with the CURRENT_RUN_TIME once the interface has been executed successfully. So the next time the interface is run it picks up the LAST_RUN_DATE from the custom OData entity.
    SAP PO has the functionality to run a dynamic query for OData adapters. Refer to Note 2051137 - PI Successfactors adapter : Dynamic odata query and single synchronous sfapi query
    Eg - select fields from position (this is what you state in OData query path in the comms channel; this is static); and you have an advanced tab in comms channel where you mention dynamicquery and set it to true (this points to a XSD which has the keyword TOP, SKIP & FILTER in it).
    This gets the filter values passed from the BPM from another query (from a OData cust_table).
    So the whole query is - select fields from position filter field a = x field b = y etc. Field a field b are fields in position that are you passing values x and y in run time of the interface.
    SAP PO also has the advanced tab feature for SFAPI for dynamic query.
    Question is -
    how to use it?
    has anyone implemented this before?
    What does XSD will look like?
    How do we pass values to the fields to the Where clause for SFAPI.
    Any ideas are welcome!
    Regards
    Arijit Das

    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

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

  • 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

  • Query Tuning - using CASE statement in the WHERE clause

    Hi All,
    My query has been modified to use a CASE statement in the WHERE clause to consider data from certain columns based on a parameter value. This modified query is doing a full table scan and running endlessly. Please suggest what may be done to improve its performance:
    Query:
    SELECT LAST_DAY(TRUNC(TO_TIMESTAMP(os.requestdatetime, 'yyyymmddhh24:mi:ss.ff4'))) AS summary_date,
    os.acctnum,
    os.avieworigin_refid,
    COUNT(1) cnt_articleview,
    SUM(NVL(autocompletedterm,0)) cnt_autocompletedterm
    FROM TABLE1 os
    WHERE os.acctnum IS NOT NULL
    AND os.avieworigin_refid IS NOT NULL
    AND os.requestdatetime IS NOT NULL
    AND UPPER(os.success_ind) = 'S'
    AND CASE WHEN
    Param_ValueToCheck  = 'FULL' AND get_date_timestamp(os.requestdatetime)  BETWEEN
    TO_DATE('01-MAY-2011 00:00:00','DD-MON-YYYY HH24:MI:SS') AND
    TO_DATE('31-MAY-2011 00:00:00','DD-MON-YYYY HH24:MI:SS')
    THEN 1
    WHEN
    Param_ValueToCheck  = 'INCR' AND os.entry_createddate  BETWEEN
    TO_DATE('01-MAY-2011 00:00:00','DD-MON-YYYY HH24:MI:SS') AND
    TO_DATE('31-MAY-2011 00:00:00','DD-MON-YYYY HH24:MI:SS')
    THEN 1
    END = 1
    AND CASE WHEN
    Param_ValueToCheck  = 'FULL' AND os.entry_CreatedDate BETWEEN
    TO_DATE('01-APR-2011 00:00:00','DD-MON-YYYY HH24:MI:SS') AND
    TO_DATE('07-JUN-2011 00:00:00','DD-MON-YYYY HH24:MI:SS')
    THEN 1
    WHEN
    Param_ValueToCheck  = 'INCR' THEN 1
    END = 1
    GROUP BY LAST_DAY(TRUNC(TO_TIMESTAMP(os.requestdatetime, 'yyyymmddhh24:mi:ss.ff4'))), os.acctnum,os.avieworigin_refid;Table Description:
    (Number of rows : approx > 600,000,000)
    Name                           Null     Type      
    ARTICLEID                      NOT NULL NUMBER(20)
    USERKEY                                 NUMBER(10)
    AVIEWORIGIN_REFID                       VARCHAR2(10)
    SUCCESS_IND                             VARCHAR2(2)
    ENTRY_CREATEDDATE                       DATE      
    CREATED_BY                              VARCHAR2(10)
    FILENUMBER                              NUMBER(10)
    LINENUMBER                              NUMBER(10)
    ACCTNUM                                 VARCHAR2(10)
    AUTOCOMPLETEDTERM                       NUMBER(2) 
    REQUESTDATETIME                         VARCHAR2(19)Explain Plan
    SQL> select * from table(dbms_xplan.display);
    PLAN_TABLE_OUTPUT
    Plan hash value: 2224314832
    | Id  | Operation            | Name              | Rows  | Bytes | Cost (%CPU)| Time     | Pstart| Pstop |
    |   0 | SELECT STATEMENT     |                   |   590 | 33040 |  2501K  (1)| 08:20:15 |       |       |
    |   1 |  HASH GROUP BY       |                   |   590 | 33040 |  2501K  (1)| 08:20:15 |       |       |
    |   2 |   PARTITION RANGE ALL|                   |   590 | 33040 |  2501K  (1)| 08:20:15 |     1 |1048575|
    |*  3 |    TABLE ACCESS FULL | TABLE1 |   590 | 33040 |  2501K  (1)| 08:20:15 |     1 |1048575|
    PLAN_TABLE_OUTPUT
    Predicate Information (identified by operation id):
       3 - filter(UPPER("OS"."SUCCESS_IND")='S' AND CASE  WHEN ('FULL'='FULL' AND
                  "OS"."ENTRY_CREATEDDATE">=TO_DATE(' 2011-04-01 00:00:00', 'syyyy-mm-dd hh24:mi:ss') AND
                  "OS"."ENTRY_CREATEDDATE"<=TO_DATE(' 2011-06-07 00:00:00', 'syyyy-mm-dd hh24:mi:ss')) THEN 1 WHEN
                  'FULL'='INCR' THEN 1 END =1 AND "OS"."REQUESTDATETIME" IS NOT NULL AND CASE  WHEN ('FULL'='FULL'
                  AND "ODS"."GET_DATE_TIMESTAMP"("REQUESTDATETIME")>=TO_DATE(' 2011-05-01 00:00:00', 'syyyy-mm-dd
                  hh24:mi:ss') AND "ODS"."GET_DATE_TIMESTAMP"("REQUESTDATETIME")<=TO_DATE(' 2011-05-31 00:00:00',
                  'syyyy-mm-dd hh24:mi:ss')) THEN 1 WHEN ('FULL'='INCR' AND "OS"."ENTRY_CREATEDDATE">=TO_DATE('
                  2011-05-01 00:00:00', 'syyyy-mm-dd hh24:mi:ss') AND "OS"."ENTRY_CREATEDDATE"<=TO_DATE('
    PLAN_TABLE_OUTPUT
                  2011-05-31 00:00:00', 'syyyy-mm-dd hh24:mi:ss')) THEN 1 END =1 AND "OS"."ACCTNUM" IS NOT NULL AND
                  "OS"."AVIEWORIGIN_REFID" IS NOT NULL)Edited by: Chaitanya on Jun 9, 2011 2:44 AM
    Edited by: Chaitanya on Jun 9, 2011 2:47 AM

    Hi Dom,
    Modified Query:
    SELECT LAST_DAY(TRUNC(TO_TIMESTAMP(os.requestdatetime, 'yyyymmddhh24:mi:ss.ff4'))) AS summary_date,
    os.acctnum,
    os.avieworigin_refid,
    COUNT(1) cnt_articleview,
    SUM(NVL(autocompletedterm,0)) cnt_autocompletedterm
    FROM TABLE1 os
    WHERE os.acctnum IS NOT NULL
    AND os.avieworigin_refid IS NOT NULL
    AND os.requestdatetime IS NOT NULL
    AND UPPER(os.success_ind) = 'S'
    AND (('FULL'  = 'FULL'
    AND  (get_date_timestamp(os.requestdatetime)  BETWEEN TO_DATE('01-MAY-2011 00:00:00','DD-MON-YYYY HH24:MI:SS')
                   AND TO_DATE('31-MAY-2011 00:00:00','DD-MON-YYYY HH24:MI:SS')
    AND   os.entry_CreatedDate BETWEEN TO_DATE('01-APR-2011 00:00:00','DD-MON-YYYY HH24:MI:SS')
                   AND TO_DATE('07-JUN-2011 00:00:00','DD-MON-YYYY HH24:MI:SS')
    OR ('FULL'  = 'INCR'
    AND os.entry_createddate  BETWEEN TO_DATE('01-MAY-2011 00:00:00','DD-MON-YYYY HH24:MI:SS')
                   AND TO_DATE('31-MAY-2011 00:00:00','DD-MON-YYYY HH24:MI:SS') ))
    GROUP BY LAST_DAY(TRUNC(TO_TIMESTAMP(os.requestdatetime, 'yyyymmddhh24:mi:ss.ff4'))), os.acctnum,os.avieworigin_refid;Execute Plan:
    PLAN_TABLE_OUTPUT
    Plan hash value: 3615447714
    | Id  | Operation                 | Name              | Rows  | Bytes |TempSpc| Cost (%CPU)| Time     | Pstart| Pstop |
    |   0 | SELECT STATEMENT          |                   | 25125 |  1374K|       |   407K  (1)| 01:21:36 |       |       |
    |   1 |  HASH GROUP BY            |                   | 25125 |  1374K|  3768K|   407K  (1)| 01:21:36 |       |       |
    |   2 |   PARTITION RANGE ITERATOR|                   | 25125 |  1374K|       |   407K  (1)| 01:21:32 |    29 |    31 |
    |*  3 |    TABLE ACCESS FULL      | TABLE1 | 25125 |  1374K|       |   407K  (1)| 01:21:32 |    29 |    31 |
    PLAN_TABLE_OUTPUT
    Predicate Information (identified by operation id):
       3 - filter("OS"."ENTRY_CREATEDDATE">=TO_DATE(' 2011-04-01 00:00:00', 'syyyy-mm-dd hh24:mi:ss') AND
                  UPPER("OS"."SUCCESS_IND")='S' AND "OS"."REQUESTDATETIME" IS NOT NULL AND
                  "ODS"."GET_DATE_TIMESTAMP"("REQUESTDATETIME")>=TO_DATE(' 2011-05-01 00:00:00', 'syyyy-mm-dd hh24:mi:ss') AND
                  "ODS"."GET_DATE_TIMESTAMP"("REQUESTDATETIME")<=TO_DATE(' 2011-05-31 00:00:00', 'syyyy-mm-dd hh24:mi:ss') AND
                  "OS"."ACCTNUM" IS NOT NULL AND "OS"."AVIEWORIGIN_REFID" IS NOT NULL AND "OS"."ENTRY_CREATEDDATE"<=TO_DATE('
                  2011-06-07 00:00:00', 'syyyy-mm-dd hh24:mi:ss'))Edited by: Chaitanya on Jun 9, 2011 4:51 AM

  • Query in the where clause is not allowed

    Hi all,
    I have a table m_vehicle that stores 1 or more than 1 rows of data for each person. But the partner's schema requires that 0 or 1 vehicle license plate data be sent with the xml file. I have the following nested select statement inside a bigger one and it does not work,
    select xmlelement("VehicleLicensePlate",
         (case when mv.lic_plate_state is not null then
              xmlelement("PlateState", mv.lic_plate_state)
         end), -- end of plate state
         (case when mv.lic_plate_no is not null then
              xmlelement("PlateNumber", xmlelement("ID", mv.lic_plate_no))
         end),
         (case when mv.lic_plate_year is not null then
              xmlelement("PlateExpiryYear", mv.lic_plate_year)                                                  
         end)
         ).extract('/*')
    from m_vehicle mv where mv.mni_id = 1083650
    and mv.seq_no = (select max(mv2.seq_no) from m_vehicle mv2
    where mv2.mni_id = mv.mni_id) and mv.lic_plate_no is not null
    But it works when I run it alone and gets the latest row for the person. It does not work either if I join this table with other tables. My root element select is from dual because I have to supply lots of SOAP and other artifacts in the xml. Is it because I have this root select from dual that the query in the where clause does not work? How do I make it work so that I get 0 or one row only from the table? My solution was to write a function that returns each part of the license plate data using dymanic sql and call it in the xmlelement function. It works but I would like to use plain sql instead.
    Thanks.
    Ben

    By the way, the error I get is this,
    ERROR:
    ORA-31011: XML parsing failed
    ORA-19202: Error occurred in XML processing
    LPX-00216: invalid character 3 (0x3)
    Error at line 1
    ORA-06512: at "SYS.XMLTYPE", line 111
    Ben

  • Function calls in WHERE clause

    Hello,
    I have several procedures that all share a similar snippet of code in the WHERE clause. I tried to make this a function but, using a function increases the execution time of the calling procedure by a factor of ten. I am currently on 8i and will be moving to 9i soon. Was just wondering if there will be any performance increase from this type of function call on 9i vs. 8i.
    Thanks
    :)

    sometimes a perforance hit it worth the maintability factor.I disagree, strongly. The developer's Prime Directive is to make the user's experience a good one. Inflicting poorly performing code on the user in the name of maintinability is not on.
    Q: Why does the code have to be maintained so much?
    A: Because the users' keep complaining about how slow it runs....
    [SOAPBOX]
    Of course in the real world things get confused and it can be quite difficult to distinguish programmers' issues - encapsulation, flexibility, maintainability - from users' issues - correctness, completeness, performance.
    But the relative worth of these things is easy to assess. A highly-modular parameter driven architecture that delivers the wrong answer and takes an age to do it ain't worth jack. Even if it is so maintainable that it's easy to fix every bug in it.
    [SOAPBOX]
    "Whatever waits for us behind those doors, we have a better chance of survival if we stick together." Gladiator
    Cheers, APC

  • Calling a function in the select clause.

    I am using Oracle 11g.
    I am trying to write a query like this
    select name,age, sal, avg = avg_salary(age)
    from customer
    where sal >= avg;
    However, I am not able to do so. What the query is trying to do is print the name, age and salary of every customer as well as the average salary for the customer's age where the customer's salary is greater than the average salary for his age.
    Please help. Thanks.

    Hi,
    The way to assign a column alias is to put the alais after the expression. It makes your code clearer if you put the keyword AS after the expression and before the alias, but this is not required.
    SELECT     name
    ,     age
    ,     sal
    ,     avg_salary (age)     AS avg_salary_age
    FROM     customer
    WHERE     sal     >= avg_salary (age)
    ;You can't reference a column alais in the same query where it is defined (except in an ORDER BY clause). If you want to reference the alias anywhere else (e.g., in the WHERE clause) you have to define it in a sub-query; then you can use it anywhere you want in the super-query, liek this:
    WITH     got_avg_salary_age     AS
         SELECT     name
         ,     age
         ,     sal
         ,     avg_salary (age)     AS avg_salary_age
         FROM     customer
    SELECT     *
    FROM     got_avg_salary_age
    WHERE     sal     >= avg_salary_age
    ;Since AVG is the name of a built-in function, there could be problems using it as a column alias. You could call it average, if you don't like avg_salary_age.

  • Table function sensitive to where clause?

    Hi-
    In Oracle SQL, you can use the results of a PL/SQL function as a table with the "TABLE()" syntax. Example: "SELECT * FROM TABLE(myfunction(param1,param2)) ..."
    Is there any (non-crazy) way for the function to be aware of the conditions in the WHERE clause of that SELECT statement? For example, if I wanted "myfunction" to know that I had specified "WHERE param3=10' without having to put param3 in the function call, could this be done?
    Other SQL implementations support this. I know of at least one where you can map a table on top of a function where the "in" parameters can correspond to columns on the mapped table. Does Oracle support a similar syntax or strategy?

    Not sure if it is too crazy for you ;)
    But again I rely on a helper function since I am not sure about the purpose of the whole thing:
    SQL> create or replace function set_param (p varchar2) return varchar2
    as
    begin
      dbms_application_info.set_client_info(p);
    return p;
    end set_param;
    Function created.
    SQL> create or replace function myfunction
       return sys.dbms_debug_vc2coll
    as
    begin
       return sys.dbms_debug_vc2coll (sys_context ('userenv', 'client_info'));
    end myfunction;
    Function created.
    SQL> select   *
      from   table (myfunction())
    where   set_param (3) is not null
    COLUMN_VALUE                                                                   
    3                     Hope you get the idea ....

Maybe you are looking for

  • Having a hard time selecting an iWeb website host

    Now that MobileMe is gone and my website is down (yes, i missed the memo)... im researching hosts and having a hard time choosing. I would like unlimited storage as I have a lot of photos on my site. RAGE sounds good but seems pricey. I'm looking for

  • Exporting a PDF

    I am attempting to export a typed manuscript in PDF, converting it to MS Word.  Each time the conversion times out and I receive a message that the conversion has failed.  I have tried using both Firefox and MS Explorer browsers, and neither works. 

  • Wireless keyboard function keys

    Hi, After replacing the batteries of my wireless keyboard I can no longer use any of the mac-specific functions of the function keys (adjusting volume, brightness, etc). I've checked this and other forums and have found people experiencing similar pr

  • Attach output type to invoice

    Hi All, Is there any function module to attach the output type to the header of billing document no. inspite of running the BDC for that. Waiting for your reply. Thanks in advanced. Regards, Dheeraj

  • Windows to MAC, file picks up errors

    Has anybody ever had this problem, I made my movie on a windows pc but now i am trying to put it on a MAC but for some reason when i put it on the MAC i get these problems: 1. My flash movies do not play 2. the buttons on my MIAW do not work 3. My da