SQL query optimization by changinf the WHERE clause

Hi all,
I need to know about the SQL query performance improvement by changing the WHERE clause. Consider a query :
select * from student where country ='India' and age = 20
Say, country = 'India' filters 100000 records and age = 20 filters 2000 records if given one by one. Now can anyone tell if the performance of the query can be changed by changing the query like this :
select * from student where age = 20 and country ='India'
as first where clause will give 2000 results and next filter will be applicable on only 2000 rows. While in the former query first where clause would give 100000 rows and seconde filter, hence, would be applicable on 100000 rows???
Kindly explain.
Thanks in advance.
Abhideep

in general the order of the where condition should not be important. However there are a few exeptions where sometimes it might play a role. Sometimes this is called order of filter conditions. Among others it depends on RBO or CBO used, Oracle Version, Indexes on the columns, statistic information on the table and the columns, CPU statistics in place etc.
If you want to make this query fast and you know that the age column has much better selectivity then you can simply put an index on the age column. An index on the country column is probably not useful at all, since to little different values are in this column. If you are already in 11g I would suggest to use a composite index on both columns with the more selective in first position.
Edited by: Sven W. on Nov 17, 2008 2:23 PM
Edited by: Sven W. on Nov 17, 2008 2:24 PM

Similar Messages

  • SQL query in SQL_REDO Logminor showing where clause with ROWID

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

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

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

  • 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

  • Can I use SYSDATE in the WHERE clause to limit the date range of a query

    Hi,
    Basicaly the subject title(Can I use SYSDATE in the WHERE clause to limit the date range of a query) is my question.
    Is this possible and if it is how can I use it. Do I need to join the table to DUAL?
    Thanks in advance.
    Stelios

    As previous poster said, no data is null value, no value. If you want something, you have nvl function to replace null value by an other more significative value in your query.<br>
    <br>
    Nicolas.

  • Query Tuning - using CASE statement in the WHERE clause - Duplicate Post

    Duplicate Post by mistake.
    Please check
    Query Tuning - using CASE statement in the WHERE clause
    Edited by: Chaitanya on Jun 9, 2011 2:45 AM
    Edited by: Chaitanya on Jun 9, 2011 2:46 AM

    Duplicate Post by mistake.
    Please check
    Query Tuning - using CASE statement in the WHERE clause
    Edited by: Chaitanya on Jun 9, 2011 2:45 AM
    Edited by: Chaitanya on Jun 9, 2011 2:46 AM

  • Regarding  dynamically assigning the where clause to select query

    hi,
      Please send the code regarding how to dynamically assign the where clause to select query.
    thanks in advance

    SELECT <fileds>
            INTO TABLE itab
            FROM dbase
            WHERE  condition.

  • Query Builder won't apply chosen date to the where clause

    Does anybody know why when I chose a date field, in the where clause, when using Query Builder, it won't actually write the chosen date to the actual query?
    If I select the "View Query" tab, no date shows up. Also if I press the "Run Report" button in the "View Result" tab, I get this error:
    "An error was encountered performing requested operation: ORA-00936: missing expression"
    This is because actual date data is missing.
    After I hit the "Apply" button, I have to manually type the date data.
    I thought this was a bug of the previous version, but I just installed version 1.5.4 and I have no different result.
    Thanks.

    I just wanted to add my name to the list of people having this issue.
    Oracle Techies, please help.

  • The query does not reference any table when attempting to build the WHERE clause.  (IES 00022)

    Hi
    I am getting below error.
    The query does not reference any table when attempting to build the WHERE clause.  (IES 00022)
    This error is in Validating Measue object in IDT.
    It is not throwing error for dimensions objects but only for measure objects.
    My BO version is 4.1
    Backend is Teradata 14.1.
    Regards
    Gaurav.

    Hi
    In the dimension/Measure definition, you can select the table. Find the below screenshot.
    If you still getting the issue…Can you please share your screenshot, for better understanding the issue?

  • JSP, DataWebBean: How to dynamically set the where clause of query and display record

    Hi,
    I am reposting this question as per suggestions made by Mr. Dwight.
    I have used ViewCurrentRecord web bean to display records from EMP table. I have to use the Dept_Id_FK from the current
    record of the EMP table to display corresponding records of Dept table. I have a view object called DeptView in my Business
    Components which selects all the records from the Dept table.
    How do I get the value of Dept_Id_FK and use it to display the required records of the Dept table?
    I tried to declare a variable and get the value of Dept_Id_FK but it did not work. My code is as follows:
    <%! String m_DeptId = null; %>
    <jsp:useBean id="RowViewer" class="oracle.jbo.html.databeans.ViewCurrentRecord" scope="request">
    <%
    RowViewer.initialize(pageContext, "EMPApp_EMP_EMPAppModule.EMPView1");
    RowViewer.setReleaseApplicationResources(false);
    RowViewer.getRowSet().next();
    m_DeptId = (String)RowViewer.getRowSet().getCurrentRow().getAttribute("DeptIdFk");
    %>
    </jsp:useBean>
    Thanks.
    null

    First of all, Thank you very much for making use of the new topic format. It is very much appreciated.
    As for your question, I think there are several different ways to accomplish what I think you want to do.
    1. Create a view object that includes both Emp and Dept entities and join them there. In this case, your query would look something like this:
    Select e.empno,e.name,...,d.dname,d.loc from emp e, dept d
    where e.deptno = d.deptno
    You should be able to create a JSP off of this view object that contains both the employee and department information. In this case, BC4J takes care of the foreign key to primary key coordination.
    2. In order to set a dynamic where clause for a view, you need to do the following in your usebean tag:
    rsn.initialize(application,session, request,response,out,"DeptView");
    rsn.getRowSet().getViewObject().setWhereClause("deptno=" &#0124; &#0124; m_DeptId);
    rsn.getRowSet().getViewObject().executeQuery();
    rsn.getRowSet().first();
    You will need to do this in a separate usebean tag from the EmpView, since the usebean can only initialize one view object.
    In other words, you would have your ViewCurrentRecord bean tag for the EmpView, then a separate one for the DeptView where you use the above code to set the where clause to display just the information for the department you want.
    Another option, but one I'm not sure would work as well, is to create a master-detail JSP to do this for you. Usually a master-detail is a one-to-many (one department to many employees). Your request appears to be the reverse, but might still be doable using the same mechanism.
    You set up relationships between views in your BC4J project using View Links. If you used the BC4J project wizard and created default views, some of these links may have been created for you. They are created when BC4J detects a foreign key to primary key relationship in the database.
    You can create your own View Links using the View Link wizard. Select your BC4J project node and choose Create View Link... from the context menu. You will be asked to select a source view (Emp), and a target view (Dept), then select the attribute in each view that related the two of them (deptno).
    Next, you need to reflect this new relationship setting in your application module. Select your app module and choose Edit from the context menu. On the data model page, select the EmpView node in the Selected list. Now select the DeptView node in the available list and shuttle it over. You should see DeptView1 via yourlink appear indented under the EmpView node. Save and rebuild your BC4J project to reflect the changes.
    In your JSP project, you can now have the wizard create a master-detail form for you based on DeptView1.
    Let me know if the above answers your question, or if I have misunderstood what it is you wanted to do.
    null

  • 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

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

Maybe you are looking for

  • Error while deploying the mapping in owb 10gR2

    Hi friends, when i tried to deploy the mapping firstly i got the  below error like Name Action Status Log COPY_OF_ORG_FINAL_MAPPING Create Warning ORA-06550: line 11, column 3: PL/SQL: SQL Statement ignored          COPY_OF_ORG_FINAL_MAPPING Create W

  • Install R12 on vmware

    I want to install R12 vision on vmware running windows 2003. I want to know that while installation it asks for "Do you want to use a virtual hostname"--here do i have to specify "yes"? Thanks

  • App store billing issue (prob not the right place for this but i couldn't find a better one)

    I have been using the same card for my itunes account for as long as i have had an itunes account and a personal credit card, all of a sudden about a week or so ago while trying to update some applications on my iphone it asked me to sign in and conf

  • 5800 date/time

    Got a 5800 with the latest firmware 20.x. Every time i power it on, it asks for date and time. Is this normal for Nokia phones?

  • Blue Cube & "?" in forwarded email images

    I have searched and searched for this topic and have found no answers. In the hope that I am simply missing something key, I am posting and begging your forgiveness for duplicating this question if it has already been answered. I receive emails that