Expressions in where clause (old puzzle)

hi all. It's an old puzzle and I am lazy to do it myself. I want Oracle database to do it for me:)
I have 6 tables: people,houses,numbers,pets,drinks and sigars. Each table has one column with 5 raws.
I have view:
create or replace view info as(
select *
from people, houses,numeration,animals,drinks,sigars )
then I am filtering the view according with conditions of the puzzle. For example I know that british lives in a red house. And I did it as follows:
select * from info
where
((person<>'british')or(person='british' and color='red')) and
((color <>'red')or(color='red' and person='british'))
How to do it easier?

From Wikipedia, the free encyclopedia
The original puzzle
1. There are five houses.
2. The Englishman lives in the red house.
3. The Spaniard owns the dog.
4. Coffee is drunk in the green house.
5. The Ukrainian drinks tea.
6. The green house is immediately to the right of the ivory house.
7. The Old Gold smoker owns snails.
8. Kools are smoked in the yellow house.
9. Milk is drunk in the middle house.
10. The Norwegian lives in the first house.
11. The man who smokes Chesterfields lives in the house next to the man with the fox.
12. Kools are smoked in the house next to the house where the horse is kept.
13. The Lucky Strike smoker drinks orange juice.
14. The Japanese smokes Parliaments.
15. The Norwegian lives next to the blue house.
Now, who drinks water? Who owns the zebra?
In the interest of clarity, it must be added that each of the five houses is painted a different color, and their inhabitants are of different national extractions, own different pets, drink different beverages and smoke different brands of American cigarettes. One other thing: In statement 6, right means your right.

Similar Messages

  • Qualifying Expression and WHERE CLAUSE Extension

    I would like to know the exact difference between 'Qualifying Expression and WHERE CLAUSE Extension'. Since both are meant to contain some CONDITION that would facilitate the Edit Check's success, So I am sometimes a bit confused with these too as to when to use what.
    Can someone help Please??

    As you can tell from my previous posts (requests!) - I'm a newbie to OC.
    From the documentation - it appears that both Qualifying expression and Where Clause work the same way but the way they execute is different.
    Qualifying expression is applied after the fetch (key fields and question response data from DCM cursor i.e., after the cursor fetches the data) and Where clause filters before QG fetch.
    HTH

  • Case expression in where clause

    I have requirement to select a columns based on condition Datacode should (when the column id=1 THEN 'GILL' ELSE WHEN ID=11 THEN IT Should be 'HEL'
    how can i write in case statment
    AND DATA_CD =CASE WHEN  ID=1  THEN 'GIL'
                             WHEN  ID=11 THEN 'HEL'
                        END ) my question is above code is corrrect for where clause?
    what happens to the ELSE PART?
    Please clarify
    S

    oraclehema wrote:
    I have requirement to select a columns based on condition Datacode should (when the column id=1 THEN 'GILL' ELSE WHEN ID=11 THEN IT Should be 'HEL'
    how can i write in case statment
    AND DATA_CD =CASE WHEN  ID=1  THEN 'GIL'
    WHEN  ID=11 THEN 'HEL'
    END ) my question is above code is corrrect for where clause?
    what happens to the ELSE PART?It is for you to tell what happens to the ELSE part.
    If the ID is not 1 or 11, then your AND condition fails and probably your query will not retrieve any records for you (Assuming this query is not a part of OR condition, because there is no query provided.).
    Because, without ELSE, the default shall be set to NULL and since you used "DATA_CD =", NULL shall not equate with it resulting in failure of condition. Hence, I would suggest you to add some default value in the ELSE part.

  • Order of expression in where clause matters

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

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

  • SSRS Expression & a WHERE clause for a report

    Sorry if this is stupid but can' t get it to work.
    What I want to do is if the field OPERATION is a 'U' then sum the fields CONTNRSIZE.
    So:
    OPERATION          CONTNRSIZE
         U                            2
         R                            5
         U                            1
     Total                           3
    This is what I have tried but it won't work.
    =iif(Fields!OPERATION.Value='U',Sum(Fields!CONTNRSIZE.Value),"No")
    Thank you

    Sorry if this is stupid but can' t get it to work.
    What I want to do is if the field OPERATION is a 'U' then sum the fields CONTNRSIZE.
    So:
    OPERATION          CONTNRSIZE
         U                            2
         R                            5
         U                            1
     Total                           3
    This is what I have tried but it won't work.
    =iif(Fields!OPERATION.Value='U',Sum(Fields!CONTNRSIZE.Value),"No")
    Thank you
    Try it like this...
    =Sum(IIf(Fields!OPERATION.Value='U', Fields!CONTNRSIZE.Value, 0))
    I typically try to avoid mixing text and numeric values but if you feel the need to have "No" instead of "0", you can try this...
    =IIf(Sum(IIf(Fields!OPERATION.Value='U', Fields!CONTNRSIZE.Value, 0)) = 0, "No", Sum(IIf(Fields!OPERATION.Value='U', Fields!CONTNRSIZE.Value, 0)))
    Jason Long

  • Where clause as expression value for parameter?

    Is it possible to put a where clause in a expression so I could use as a parameter? I have 3 documents I was going to make as available values, but not sure how to put all of this in the expression. 
    Where clause:
    where document = 'doc1'
    and sentdate = (Select max(sentdate) from Communication where document = 'doc1')

    Hi Lezgettdrunk,
    According to your description, you want to specify available values for a report parameter.
    In Reporting Services, if we want to specify the available values for a report parameter in Report Parameter Properties, we should get those values from specified values or a dataset. When we select the “Specify values” option, we can give each label corresponding
    value. When we select the “Get values from a query” option, we should select a dataset which contains documents values. In your scenario, you could create a dataset with where clause to get document values, then specify parameter available values use this
    dataset.
    Reference:
    Lesson 2: Adding Parameters to Create a List of Available Values (SSRS)
    If you have any question, please feel free to ask.
    Best regards,
    Qiuyun Yu
    Qiuyun Yu
    TechNet Community Support
    Thank you! This worked for me.

  • WHERE clause in a SMARTFORM loop, problems with parenthesis

    Hi all gurus,
    a simple question: I'm coding a LOOP in the form builder for a smartform ... this simple loop should bind text elements to every position of a purchase order. The WHERE clause should be as follows:
    WHERE GUID = WA_ITEM-GUID
    AND ( TDID EQ 'ZDES' OR TDID EQ 'ZDST' ).
    Anyway, in the Form Builder I didn't find a way to add parenthesis; I workarounded the problem with the following query:
    (conditions in lines are in AND conjunction)
    GUID EQ     WA_ITEM-GUID
    TDID      EQ   'ZDES'
    OR
    GUID EQ     WA_ITEM-GUID                                                                               
    TDID      EQ 'ZDST'.
    It's quite a 'bad' way, but it works. I wonder if there's a way to express "complex" WHERE clauses (with addiction of parenthesis) in Form Builder.
    Thanks in advance

    In this case, your solution is the one that works. However in more complex cases with more variables, this can proove difficult to make or mantain.
    What I usually do is use the first part of the condition in the where and then add a condition to the printing area with the rest of the formula. Just remember to document this so that you'll find it easy and it's way more amintainable.
    In this case the loop would contain WHERE GUID = WA_ITEM-GUID and the inside condition TDID EQ 'ZDES' OR TDID EQ 'ZDST. This creates the and between the two blocks.

  • Where Clause SQL Loader

    Hi,
    Please could someone give me the syntax for expressing a where clause in SQL Loader control file? as an example i only want the data in the columns to be uploaded where person_id matches the person_id already present in the table.
    My control file is below which needs amending to include a 'Where'. The append will also need changing i assume.
    load data
    infile '/app/DEV/appl/xxcpp/11.5.0/bin/TEST.csv'
    APPEND
    into table XXCPP_SQL_LOADER_TEST
    fields terminated by "," optionally enclosed by '"'
    ( PERSON_ID, EMP_NAME, EMP_NUMBER, START_DATE DATE "fmDD/MM/RRRR" )
    Many Thanks

    SQL*Loader has very limited conditional load capabilities. WHEN clause does not support OR (and it is documented). Anyway, you could do the following. Control file:
    load data
    infile *
    APPEND
    into table XXCPP_SQL_LOADER_TEST
    When Person_id = '1'
    fields terminated by "," optionally enclosed by '"'
    ( PERSON_ID POSITION(1), EMP_NAME, EMP_NUMBER, START_DATE DATE "fmDD/MM/RRRR" )
    into table XXCPP_SQL_LOADER_TEST
    When Person_id = '2'
    fields terminated by "," optionally enclosed by '"'
    ( PERSON_ID POSITION(1), EMP_NAME, EMP_NUMBER, START_DATE DATE "fmDD/MM/RRRR" )
    into table XXCPP_SQL_LOADER_TEST
    When Person_id = '3'
    fields terminated by "," optionally enclosed by '"'
    ( PERSON_ID POSITION(1), EMP_NAME, EMP_NUMBER, START_DATE DATE "fmDD/MM/RRRR" )
    begindata
    1,A,11,13/01/2011
    2,B,12,13/01/2011
    3,C,13,13/01/2011
    4,D,14,13/01/2011
    5,D,15,13/01/2011
    {code}
    Now:
    {code}
    SQL> select * from XXCPP_SQL_LOADER_TEST;
    no rows selected
    SQL> host sqlldr scott/tiger control=c:\temp\XXCPP_SQL_LOADER_TEST.CTL log=c:\temp\XXCPP_SQL_LOADER_TEST.LOG
    SQL> select * from XXCPP_SQL_LOADER_TEST;
    PERSON_ID EMP_NAME   EMP_NUMBER START_DAT
             1 A                  11 13-JAN-11
             2 B                  12 13-JAN-11
             3 C                  13 13-JAN-11
    SQL>
    {code}
    SY.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Empty WHERE Clause with AND condition after

    I have a question concerning a SQL query that I am using for a report. I have converted an old report to Crystal Reports 2008 and the resulting SQL query no longer works.
    After the conversion all the inner joins that were previously used in the report were moved to the FROM clause.
    My resulting WHERE clause is as follows:
    WHERE   AND
    "TABLE"."TABLEKEY" IS NOT NULL
    I get this error message:
    ORA-00936 Missing expression
    As you can see there WHERE clause has nothing before the AND condition because all the inner joins have moved to the FROM clause in the new version of Crystal Reports. I am fine with these inner joins moving but how do I take care of this empty condition.
    Any help is appreciated.

    Hi Joshua
    Please go through the following SAP note which deals with similar type of issue.
    https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/oss_notes_boj/sdn_oss_boj_erq/sap(bD1lbiZjPTAwMQ==)/bc/bsp/spn/scn_bosap/notes%7B6163636573733d36393736354636443646363436353344333933393338323636393736354637333631373036453646373436353733354636453735364436323635373233443330333033303331333233313335333533393334%7D.do
    Thanks

  • Is this conditional WHERE clause possible?

    Let's say at the beginning of a stored procedure I do this:  DECLARE @hasActualHours BIT
    I'll then employ logic to set this local variable to either 0 or 1.
    I'm interested to know if I can then use it to either include or exclude entire "AND..." clauses within my WHERE clause?
    For example:
    SELECT ...
    FROM ...
    WHERE
      Clause 1... AND
      Clause 2... AND
    Now, I have a Clause 3 but I
    only want to include it if @hasActualHours = 1.
    Is it possible to do something like that in T-SQL?
    Robert

    >> Let's say at the beginning of a stored procedure I do this:  DECLARE @hasActualHours BIT
    I'll then employ logic to set this local variable to either 0 or 1.
    I'm interested to know if I can then use it to either include or exclude entire "AND..." clauses within my WHERE clause? <<
    No, no, no, no!  Your whole approach is totally wrong. Not a little wrong, but totally wrong. You just heard that from someone who helped write the SQL Standards, has 1200+ articles and 10 books on this topic. Please listen. 
    SQL is a declarative language, not a procedural flow control language. Declarative languages have no flow to control; there is no IF-THEN-ELSE, no loops. 
    SELECT ...
      FROM … 
     WHERE Clause 1... 
       AND Clause 2... 
       AND <expression for actual hour count> > 0.00;
    >> Is it possible to do something like that in T-SQL? <<
    Sure, we can kludge it! But first post a statement for your boss to see that you do not care about maintaining code, performance and professionalism. This would be bad for your career; like saying you eat babies on a parenting forum :) That is what the other
    replies are! 
    right now, you are the kid on a baseball diamond asking by which end do you hold the umpire. You are not thinking in SQL yet. My rule of thumb is you need a full year of SQL with a good mentor (read that last phrase again). It is a different mindset. 
    I wrote a book, THINKING IN SETS, to help with the change. See if that helps. 
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • Using decode to define "where" clause

    Gurus,
    Before, I was unioning several queries to get my desired results. Is there a way to utilize decode to define my "where" conditions?
    Thanks
    msi.global_attribute1               HTS_Number,           
    msi.global_attribute2               ECCN_Number  ,
    msi.market_price                    price,     --- double-check
    decode(msi.serial_number_control_code,5,'Serial','Lot') control_type,
    -- add item_type
    --Item Label Creation        At Receipt or At Sales Order Issue
    (case
    when enabled_flag = 'Y' and end_date_active is null then 'Active'
    when enabled_flag = 'Y' and end_date_active > sysdate then 'Active'
    when enabled_flag = 'Y' and end_date_active < sysdate then 'Inactive'
    when enabled_flag = 'N' then 'Inactive'
    else 'Active'
    end) status,
    from inv.mtl_system_items_b   msi,
         po_hazard_classes    phc,
        po_un_numbers        pun
    where msi.hazard_class_id = phc.hazard_class_id(+)  
    and   msi.un_number_id = pun.un_number_id(+)   
    and   msi.organization_id = 543
    and   msi.creation_date = msi.last_update_date
    --and   'New Items' = nvl(p_item_status,'All Items') --p_item_status
    and   decode('New Items', --p_item_status,
          'New Items', (msi.creation_date = msi.last_update_date),
          'Updated Items', (msi.creation_date <> msi.last_update_date),
          'All Items', (1=1), (1=1))
      and msi.segment2 = '14078'

    Hi,
    sreese wrote:
    Before, I was unioning several queries to get my desired results. Is there a way to utilize decode to define my "where" conditions?Depending on what you mean, yes.
    Whenever you have a problem, please post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) from all tables involved.
    Also post the results you want from that data, and an explanation of how you get those results from that data, with specific examples.
    Simplify the problem as much as possible. Remove all tables and columns that play no role in this problem.
    Always say which version of Oracle you're using.
    Here's an example of two UNIONed queries:
    SELECT       deptno
    ,       SUM (sal)     AS total_sal
    ,       'MANAGEMENT'     AS grp_name
    FROM       scott.emp
    WHERE       job     IN ('MANAGER', 'PRESIDENT')
    GROUP BY  deptno
         UNION ALL
    SELECT       deptno
    ,       SUM (sal)     AS total_sal
    ,       'OLD-TIMERS'     AS grp_name
    FROM       scott.emp
    WHERE       hiredate     < DATE '1984-01-01'
    GROUP BY  deptno
    ORDER BY  deptno
    ,            grp_name
    ;Output:
    `   DEPTNO  TOTAL_SAL GRP_NAME
            10       7450 MANAGEMENT
            10       8750 OLD-TIMERS
            20       2975 MANAGEMENT
            20       6775 OLD-TIMERS
            30       2850 MANAGEMENT
            30       9400 OLD-TIMERSA more efficient way to get the same information, without a UNION is:
    SELECT       deptno
    ,       SUM (CASE WHEN job IN ('MANAGER', 'PRESIDENT') THEN sal END)     AS management
    ,       SUM (CASE WHEN hiredate < DATE '1984-01-01'      THEN sal END)     AS old_timers
    FROM       scott.emp
    WHERE       job          IN ('MANAGER', 'PRESIDENT')
    OR       hiredate     < DATE '1984-01-01'
    GROUP BY  deptno
    ORDER BY  deptno
    ;Output:
    `   DEPTNO MANAGEMENT OLD_TIMERS
            10       7450       8750
            20       2975       6775
            30       2850       9400As you can see, the results aren't exactly the same. UNION makes it easy to get more rows in the output than there are in the original; CASE (or DECODE,you can use whichever you like) makes it easy to get fewer rows and more columns. If you reallt want one kind of output or the other, it can be done with a little more work using either UNION or CASE.
    When using CASE, the WHERE clause is typically more inclusive than any of the WHERE caluses in the UNION. Some of the conditions (in this example, all of the conditions) that were in the separate WHERE clauses of the UNION get changed to be conditions in separate CASE expressions.

  • The mechanics of the WHERE clause

    I’ve been out in industry for over 10 years now doing DB work most of that time. Lately I’ve been doing some work that is starting to challenge my long held assumptions about the internal workings of SQL Server, specifically what exactly is happening when
    I do joins and where clauses.
    I was explaining to someone that when doing a join putting in a where clause limits the amount of records that are available to do the join on thereby making the query faster. My thought was if a table has 100MM records but only 50MM of those meet the WHERE
    criteria then the JOIN clause wouldn’t try matching the 50MM records that don’t meet the WHERE clause.
    I did some work that afternoon and the empirical results didn’t match the expected outcome of a query I had written in terms of execution time. I don’t think my understanding of what goes on during a JOIN is correct. Can someone educate me?

    Here is how a SELECT works in SQL ... at least in theory.  Real products will optimize things, but the code has to produce the same results. 
     a) Effectively materialize the CTEs in the optional WITH clause. CTE's come into existence in the order they are declared so only backward references are
    alllowed. A CTE can be recursive. Think of them as VIEWs that exist only in the scope of the query. In practice, if they are used once then they are implemented as an in-line macro.
     b) Start in the FROM clause and build a working table from all of the joins, unions, intersections, and whatever other table constructors are there.  The <table expression> AS <correlation name> option allows you give a name to this working
    table which you then have to use for the rest of the containing query.  Ther are UNIONB, INTERSECT and EXCEPT set construtors, LATERAL tables, table-valued funcitosn and all kinds of things happening in here. 
     c) Go to the WHERE clause and remove rows that do not pass criteria; that is, that do not test to TRUE (i.e. reject UNKNOWN and FALSE).  The WHERE clause is applied to the working set in the FROM clause.  
     d) Go to the optional GROUP BY clause, partiton the original table into groups and reduce each grouping to a *single* row, replacing the original working table with the new grouped table. The rows of a grouped table must be only group characteristics:
    (1) a grouping column (2) a statistic about the group (i.e. aggregate functions) (3) a function or constant(4) an expression made up of only those three items.  The original table no longer exists and you cannot reference anything in it (this was an error
    in early Sybase products).  
     e) Go to the optional HAVING clause and apply it against the grouped working table; if there was no GROUP BY clause, treat the entire table as one group. 
     f) Go to the SELECT clause and construct the expressions in the list. This means that the scalar subqueries, function calls and expressions in the SELECT are done after all the other clauses are done.  The AS operator can also give names to expressions
    in the SELECT list.  These new names come into existence all at once, but after the WHERE clause, GROUP BY clause and HAVING clause have been executed; you cannot use them in the SELECT list or the WHERE clause for that reason. 
    If there is a SELECT DISTINCT, then redundant duplicate rows are removed.  For purposes of defining a duplicate row, NULLs are treated as matching (just like in the GROUP BY).  
     g) Nested query expressions follow the usual scoping rules you would expect from a block structured language like C, Pascal, Algol, etc.  Namely, the innermost queries can reference columns and tables in the queries in which they are contained.  
     h) The ORDER BY clause is part of a cursor, not a query. The result set is passed to the cursor, which can only see the names in the SELECT clause list, and the sorting is done there.  The ORDER BY clause cannot have expression in it, or references
    to other columns because the result set has been converted into a sequential file structure and that is what is being sorted.  
    As you can see, things happen "all at once" in SQL, not "from left to right" as they would in a sequential file/procedural language model. In those languages, these two statements produce different results:
      READ (a, b, c) FROM File_X;
      READ (c, a, b) FROM File_X;
    while these two statements return the same data:
    SELECT a, b, c FROM Table_X;
    SELECT c, a, b FROM Table_X;
    Think about what a confused mess this statement is in the SQL model.
    SELECT f(c2) AS c1, f(c1) AS c2 FROM Foobar;
    That is why such nonsense is illegal syntax.
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • Referencing Aggregated Column Value in Where Clause

    Hello -
    I'm trying to determine how I can accomplish the following in the most straightforward, efficient way.
    Among other things, I'm selecting the following value from my table:
    max(received_date) as last_received_dateI also need to evaluate the "last_received_date" value as a condition in my where clause. However, I can't reference my aliased "last_received_date" column value, and when I try to evaluate max(received_date) in the where clause, I get the "group function is not allowed here" error.
    Does anyone know of a good workaround?
    Thanks,
    Christine

    Hi,
    Column aliases can be used in the ORDER BY clause: aside from that, they cannot be used in the same query where they are defined. The workarounds are
    (a) define the alias in a sub-query, and use it in a super-query, like Someoneelse did, or
    (b) repeat the aliased expression, as in the HAVING-clause, below.
    Aggregate functions are computed after the WHERE-clause. (That explains why you can do things like
    SELECT  MAX (received_date) last_received_date_2008
    FROM    table_x
    WHERE   TO_CHAR (received_date, 'YYYY')  = '2008';).
    The HAVING-clause is like the WHERE-clause, but it is applied after the aggregate functions are computed, e.g.
    SELECT    deptno
    ,         MAX (recieved_date)  AS last_received_date
    FROM      table_x
    GROUP BY  deptno
    HAVING    MAX (received_date)    > SYSDATE - 7   -- Only show deptartments with activity in the last week
    ;

  • Difference between column_name is null and column_name (+) is null in where clause.

    Hi All,
    I found the below condition in one of the code of my project.
    Select *
    From table name
    Where column_name ( + )  is null .
    Could any one explain what does column_name ( + ) in where clause.
    Thanks in advance.
    Regards,
    Jagadeeah

    Hi,
    Jagadeesh R wrote:
    Hi All,
    I found the below condition in one of the code of my project.
    Select *
    From table name
    Where column_name ( + )  is null .
    Could any one explain what does column_name ( + ) in where clause.
    Thanks in advance.
    Regards,
    Jagadeeah
    The  ( + )  sign is an old way of doing outer joins.  In Oracle 8 and earlier, you couldn't say
    SELECT  *
    FROM             scott.dept  d
    LEFT OUTER JOIN  scott.emp   e   ON  e.deptno  = d.deptno
    Instead, you got those results by saying:
    SELECT  *
    FROM    scott.dept  d
    ,       scott.emp   e
    WHERE   e.deptno  ( + ) = d.deptno
    The 1 line you posted was probably part of a larger WHERE clause.  You'll have a better understanding of what that 1 line is doing if you look at it in context, considering all the join conditions between the tables involved.

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

Maybe you are looking for

  • New BT vision box appears to keep rebooting

    First, a big hello to everyone. I signed up recently for broadband and vision. Broadband was working from about Saturday although didn't get text from BT to confirm switch on till this morning. Yesterday Vision box said error C04 (wait till your acti

  • How do you turn off auto-reply/notify in iCal?

    I'm sure there's a simple answer to this because I've searched high and low and I just can't disable the auto-notify/auto-reply feature in iCal when I delete a meeting notice someone else invited me to. What's the process for turning off this great f

  • LED display for Imac

    I have a 09 imac with the larger dvi port I would like to hook up new Apple LED Cinema Display but dvi is smaller is there an adapter

  • Ical 5.0 syncing issues with iPhone 3G

    Hi, I have an 'old' but very functional iphone 3G.  I upgraded my mini mac recently which came with Lion and ical 5.0 The issue:  When I create a new event in ical using my iphone, it doesn't come up on my computer ical when syncing.  However, when I

  • Premiere Elements for commercial use

    Can I use Premiere Elements 12 for commercial use , like videos I make for training modules that I sell? I looked in the EULA and buried in section 16.14 and 16.15 is reference to non-commercial use due to encoder patents.  But nowhere is a straight