Exist Clause

Helllo All,
One Order (table oe_order_headers_all ) can have mulitple lines(table oe_order_lines_all) associated with it.
Both tables are joined with header_id.
Now I need to run a query for a specific date range. suppose i gave both date parameters as 26-mar-10.
Then the orders that are shipped on 26th only should come.
Here let say few lines shipped on 26th and the final lines got shipped on 27th mar
So if i ran the query for 26th march then we should not get the data.
If i ran for 27th mar then i should get the data.
(Only when all lines got shipped then on that date i should get data)
Below is th sample query. which i wrote(only i need to modify the exist clause here)
Actually i have problem with Exist Clause.Exist clause should be written to meet the above said condition.
Select ooh.* from oe_order_headers_all ooh
where 1=1
and
EXISTS (
( SELECT 1
from apps.oe_order_lines l
where l.header_id = ooh.header_id and
trunc (l.shipment_date ) >= nvl (:DATE_FROM ,
trunc (l.shipment_date ) )
and trunc (l.shipment_date ) <= nvl ( :DATE_TO,
trunc ( l.shipment_date ) )
)

You do not need exists for that:
select  ooh.*
  from  oe_order_headers_all ooh,
         select  header_id
           from  apps.oe_order_lines
           group by header_id
           having max(shipment_date) < nvl(:DATE_TO,shipment_date) + 1
              and min(shipment_date) >= nvl(:DATE_FROM,shipment_date)
        ) l
  where l.header_id = ooh.header_id
/SY.

Similar Messages

  • Use of EXIST clause

    Need to seek advice on the use of EXISTS clause.
    What is this statement trying to do? What is the '1' in the inner SELECT statement means?
    DELETE FROM a
    WHERE NOT EXISTS (SELECT 1
    FROM b
    WHERE a.a_id = b.a_id);
    What about these 2 statements doing??
    SELECT * FROM a WHERE EXISTS (SELECT 1 FROM b WHERE a.a_id = b.a_id);
    DELETE FROM a
    WHERE EXISTS (SELECT 1 FROM b WHERE a.a_id = b.a_id);

    have a look at http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:953229842074 for a complete explanation of how an "exists" and an "in" is executed. For "not in" and "not exists", look here: http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:442029737684
    greetings
    Freek D
    Freek and Mona are correct in that the 1 is just a place holder, because you need to SELECT something. However, the EXISTS clause actually returns TRUE or FALSE depending on whether the SELECT statement finds a row.
    EXISTS is similar to IN using a SELECT statement. The advantage of EXISTS, particularly when you can use a correlated sub-query, is that it stops looking as soon as it finds a single row that matches the criteria in the SELECT statement, where an IN clause will return all the rows that match, including duplicates

  • Use of EXISTS clause in Interface

    I want to build an interface from one table but using an exist clause to check the data change in the same table.
    In SQL statement it can be expressed as follows
      SELECT PB.PROJECT_KEY, COUNT (DISTINCT DW_PROJECT_BUILDING_KEY)
        FROM DW_PROJECT_BUILDING PB
       WHERE     EXISTS
                    (SELECT 1
                       FROM DW_PROJECT_BUILDING PB1
                      WHERE     PB1.PROJECT_KEY = PB.PROJECT_KEY
                            AND PB1.RECORD_STATUS_ID = 1)
             AND PB.RECORD_STATUS_ID = 1
             AND TRUNC (PB.LOAD_DT) >= '03-OCT-2013'
    GROUP BY PB.PROJECT_KEY;
    How can I build this SQL with exists clause in the interface ?
    Thanks

    Create the interface with DW_PROJECT_BUILDING table and give this table a name PB.
    Now put one filter on the table with the conditions that you have just mentioned in the query above, with the exist statement.
    I assume data from this table is targeted into one more aggregated table: here is the definition for the table:
    CREATE TABLE PROJECT_BUILDING_AGGR
    (PROJ_BUILD_KEY VARCHAR2(20),
    PROJECT_KEY varchar2(20));
    perform mapping like :
    PROJECT_KEY=PB.PROJECT_KEY
    PROJ_BUILD_KEY=count(distinct PB.DW_PROJECT_BUILDING_KEY)
    Select IKM as IKM SQL control append.
    FLOW control as false.
    run the interface, it is giving something like this for me, I hope this is according to your requirement:
    insert into
    ORACLE_SOURCE.PROJECT_BUILDING_AGGR
    PROJ_BUILD_KEY,
    PROJECT_KEY
    select
        PROJ_BUILD_KEY,
    PROJECT_KEY  
    FROM (
    select
    count(distinct PB.DW_PROJECT_BUILDING_KEY) PROJ_BUILD_KEY,
    PB.PROJECT_KEY PROJECT_KEY
    from
    ORACLE_SOURCE.DW_PROJECT_BUILDING   PB
    where
    (1=1)
    And (EXISTS
                    (SELECT 1
                       FROM DW_PROJECT_BUILDING PB1
                      WHERE     PB1.PROJECT_KEY = PB.PROJECT_KEY
                            AND PB1.RECORD_STATUS_ID = 1)
             AND PB.RECORD_STATUS_ID = 1
             AND TRUNC (PB.LOAD_DT) >= '03-OCT-2013')
    Group By PB.PROJECT_KEY
    )    ODI_GET_FROM

  • Exists clause in query causes too much time to get back results

    We Are having the long query as follows which is taking so much time to respond.Is there any way to optimize the query.We see that there is exists clause in query which is taking long time .if it is so please suggest appropriate solution to remove exists clause.
    SELECT
    DISTINCT t0.JDOID,
    t0.JDOCLASS,
    t0.JDOVERSION,
    t0.ACTIVITY,
    t0.ADMINSTATE,
    t0.CREATEDDATE,
    t0.CREATEDUSER,
    t0.DESCRIPTION,
    t0.ENDDATE,
    t0.ID,
    t0.LASTMODIFIEDDATE,
    t0.LASTMODIFIEDUSER,
    t0.NAME,
    t0.NOSPEC,
    t0.OBJECTSTATE,
    t0.OWNER,
    t0.PARTITION,
    t0.PERMISSIONS,
    t0.SPECIFICATION,
    t0.STARTDATE
    FROM
    SERVINV.RESOURCESPECIFICATION t2,
    SERVINV.SPECIFICATION t3,
    SERVINV.TELEPHONENUMBER t0,
    SERVINV.TELEPHONENUMBERSPECIFICATION t1,
    SERVINV.TN_CHAR t4
    WHERE
    t3.NAME = 'usTelephoneNumber'
    AND
    t0.ID LIKE '0010210%'
    OR t0.ID LIKE '0010370%'
    OR t0.ID LIKE '0010690%'
    OR t0.ID LIKE '0010090%'
    OR t0.ID LIKE '0010610%'
    OR t0.ID LIKE '0010570%'
    OR t0.ID LIKE '0010330%'
    OR t0.ID LIKE '0010130%'
    OR t0.ID LIKE '0010410%'
    OR t0.ID LIKE '0010650%'
    OR t0.ID LIKE '0010730%'
    OR t0.ID LIKE '0010050%'
    OR t0.ID LIKE '0010450%'
    OR t0.ID LIKE '0010490%'
    OR t0.ID LIKE '0010530%'
    OR t0.ID LIKE '0010170%'
    OR t0.ID LIKE '0010290%'
    OR t0.ID LIKE '0010030%'
    OR t0.ID LIKE '0010250%'
    OR t0.ID LIKE '0010770%'
    AND t4.NAME = 'tnType'
    AND t4.VALUE = 'OWNED'
    AND NOT EXISTS (
    SELECT
    t5.JDOID
    FROM
    SERVINV.TNCONSUMER t5
    WHERE
    t5.TELEPHONENUMBER = t0.JDOID
    AND
    t5.ADMINSTATE IS
    NULL
    OR t5.ADMINSTATE <> 'UNASSIGNED'
    AND
    t0.OBJECTSTATE = 'ACTIVE'
    OR t0.OBJECTSTATE = 'INACTIVE'
    OR t0.OBJECTSTATE IS
    NULL
    AND t0.JDOCLASS = 'com.metasolv.impl.entity.TelephoneNumberDAO'
    AND t0.SPECIFICATION = t1.JDOID
    AND t0.JDOID = t4.TELEPHONENUMBER
    AND t1.JDOID = t2.JDOID
    AND t2.JDOID = t3.JDOID
    ORDER BY
    t0.ID ASC;
    Unable to post xplain plan as it is huge and exceeding 30000 characters.
    Pandu

    Hi Pandu,
    try something like this and check if it works:
    replace the OR conditions with substr function:
    AND substr(t0.ID,1,7) in
    ('0010210',
    '0010370',
    '0010690',
    '0010090',
    '0010610',
    '0010570',
    '0010330',
    '0010130',
    '0010410',
    '0010650',
    '0010730',
    '0010050',
    '0010450',
    '0010490',
    '0010530',
    '0010170',
    '0010290',
    '0010030',
    '0010250',
    '0010770')confirm if this reduces the time...will check further after your confirmation...
    Regards
    Imran

  • Not able to migrate a query with not exist clause

    Hi all,
    I'm using Toplink 10.1.3 and I am trying to rewrite the following query with Expression Framework:
    select distinct r.e_ogg_oper_k_oggetto
    FROM regola_accettazione_oper_banc r, oggetto_operazione_bancaria o
    where not exists (
    select 1
    FROM limitaz_ogg_tipo_oper_banc l
    where nvl(l.d_fine_validita,trunc(sysdate)+1)>trunc(sysdate)
    and l.d_inizio_validita <= trunc(sysdate)
    and l.e_tpodv_k_tipo_operazione=:appoggio.tipo_operaz
    and l.e_ogg_oper_k_oggetto=r.e_ogg_oper_k_oggetto
    and l.e_uni_oper_k_unita_oper_util= :appoggio.e_uni_oper_k_unita_oper_esegui )
    and r.e_oper_ban_k_operaz_bancaria=:appoggio.form
    and r.e_ogg_oper_k_oggetto=o.k_oggetto
    and o.e_ogg_oper_k_oggetto is null
    and o.k_oggetto != nvl(:appoggio.oggetto_autom,,'0')
    and o.k_oggetto like substr(:appoggio.oggetto,1,2)||'%'
    and r.d_inizio_validita <= :appoggio.d_contab
    and to_date(nvl(to_char(r.d_fine_validita,DD/MM/YYYY'),31/12/3999'),'DD/MM/YYYY')> :appoggio.d_contab
    and o.f_natura_oggetto in ('G','P') and r.f_oggetto_automatizzato!='S'
    I'm not able to "attach" the not exist clause to the rest of query.
    How can I do it?
    Thank you very much.

    Not exists can be used in an expression through using a ReportQuery sub-query.
    i.e.
    ExpressionBuilder outerBuilder = new ExpressionBuilder();
    ReadAllQuery outerQuery = new ReadAllQuery(Employee.class, outerBuilder);
    ExpressionBuilder subBuilder = new ExpressionBuilder();
    ReportQuery subQuery = new ReportQuery(Address.class, subBuilder);
    subQuery.addAttribute("id");
    subQuery.setSelectionCriteria(
    subBuilder.get("city").equal(outerBuilder.get("address").get("city")
    .and(subBuilder.notEqual(outerBuilder.get("address")))));
    outerQuery.setSelectionCriteria(
    outerBuilder.notExists(subQuery));
    List results = (List) session.executeQuery(outerQuery);
    Refer to the documentation section on sub-queries for more information.
    I would suggest simlpifying the where clause until you get the sub-query working to start.
    You can also always use a custom SQL query in TopLink.

  • Can any one tell me how to use EXISTS clause inplace of IN operator.

    Hi All,
    Can any one tell me how to use EXISTS clause AND (JC.EMPL_ID, JC.EMPL_RCD) inplace of IN operator.
    SELECT COUNT (1)
    FROM SYSADM.OHR_PERS_CURR PC
    , SYSADM.OHR_JOB_CURR JC
    WHERE PC.EMPL_ID = JC.EMPL_ID
    AND (JC.EMPL_ID, JC.EMPL_RCD) in (
    SELECT HS.EMPL_ID, HS.EMPL_RCD
    FROM SYSADM.HU_SCRTY_JOB HS, ODSHR.OHR_SCRTY_USER_CFG OS
    WHERE HS.HU_SCRTY_CFG_ID = OS.HU_SCRTY_CFG_ID
    AND OS.DB_LOGIN = USER)
    Thank you.

    SELECT COUNT (1)
    FROM SYSADM.OHR_PERS_CURR PC
    , SYSADM.OHR_JOB_CURR JC
    WHERE PC.EMPL_ID = JC.EMPL_ID
    AND EXISTS (
    SELECT null
    FROM SYSADM.HU_SCRTY_JOB HS, ODSHR.OHR_SCRTY_USER_CFG OS
    WHERE HS.HU_SCRTY_CFG_ID = OS.HU_SCRTY_CFG_ID
    AND OS.DB_LOGIN = USER
    AND HS.EMPL_ID = JS.EMPL_ID AND HS.EMPL_RCD = JC.EMPL_RCD)
    But why ?
    Rgds.

  • Exists clause in plsql query

    HI I see that by the use of exists clause while joining
    1) oralce provides a better execution plan ... and 2) it eliminates duplicates automatically
    but my question is how to access the columns of the inner tables in the select clause ?
    EG:
    select a.sno, b.course_name
    from a,b
    where a.cid=b.cid
    ----------------------in the below query How do i access b.course_name in the select clause? similarly even if it contains more tables nested, i should be able to access the column of the inner tables from the select clause . How to do this . hope i am clear
    select a.sno from a where exists ( select 1 from b where b.cid=a.cid)

    You cannot access columns from tables in an EXISTS (or NOT EXISTS) clause outside of that clause. You can only select data from tables (and other objects) that you are actually selecting from.
    Justin

  • Spatial query inside the exists clause return ora-13226

    The following does not work:
    select b.state, b.county from counties b where exists
    (select 's' from states a where a.state = 'New Jersey'
    and mdsys.sdo_relate (b.geom, a.geom, 'mask=INSIDE querytype=WINDOW' ) = 'TRUE');
    ERROR at line 1:
    ORA-13226: interface not supported without a spatial index
    ORA-06512: at "MDSYS.MD", line 1723
    ORA-06512: at "MDSYS.MDERR", line 8
    ORA-06512: at "MDSYS.SDO_3GL", line 302
    ORA-06512: at line 1
    The following does work:
    select b.* from states a,
    counties b where a.state = 'New Jersey'
    and mdsys.sdo_relate (b.geom, a.geom, 'mask=INSIDE querytype=WINDOW') = 'TRUE';
    I found bug 1243095 telling that this is not a bug but a limitation of the spatial operator. It cannot be invoked on a table that is not spatially indexed. In fact, the table is indexed but oracle cannot find the spatial index because table b(counties) is declared outside the EXISTS clause.
    In my case, I use object table. I cannot use the workaround specified above because I should use the DISTINCT clause but I cannot define the MAP and ORDER function (this is a general query).
    I've found another workaround :
    select b.state, b.county from counties b where exists
    (select 's' from states a where a.state = 'New Jersey'
    and mdsys.sdo_relate (a.geom, b.geom, 'mask=CONTAINS querytype=WINDOW') = 'TRUE');
    but sdo_relate still doesn't use the spatial index of table b (even if I specify it explicitely in the operator) and the query is very slow (more than 15 minutes).
    Is there a better workaround ?

    OK but I work in object model.
    And if I don't use the EXISTS clause, I must use the distinct clause.(I used the exists because of that)
    If I will to retrieve all the country that have at least a state beginning with the C letter, I will wrote :
    select c.* from country c, table(c.states) s where s.column_value.name like 'C%';
    (It is a simplified request to express the problem)
    In this case, I must use the distinct clause to select one occurence of each country objet (one country may contains more than one state beginning with C).
    select distinct c.* from country c, table(c.states) s where s.column_value.name like 'C%';
    For that, I must define a MAP or ORDER function for EACH type used in the country object.
    My first question is : I must retrieve all different country objects. Why the request doesn't use the MAP or ORDER function of the country type to distinct them ? Is there another syntax (or a hint) to express that ?
    In this case, it will make an ORA-00932 : incoherent datatype because the type of the nested table column cannot contain map or order method.
    Any suggestion ?
    Thanks in advance.

  • Execution of subquery of IN and EXISTS clause.

    Hi Friends,
    Suppose we have following two tables:
    emp
    empno number
    ename varchar2(100)
    deptno number
    salary number
    dept
    deptno number
    location varchar2(100)
    deptname varchar2(100)
    status varchar2(100)
    Where dept is the master table for emp.
    Following query is fine to me:
    SELECT empno, ename
    FROM emp,dept
    WHERE emp.deptno = dept.deptno
    AND emp.salary &gt;=5000
    AND dept.status = 'ACTIVE';
    But I want to understand the behaviour of inline query (Used with IN and EXISTS clause) for which I have used this tables as an example (Just as Demo).
    1)
    Suppose we rewrite the above query as following:
    SELECT empno, ename
    FROM emp
    WHERE emp.salary &gt;=5000
    AND deptno in (SELECT deptno FROM dept where status = 'ACTIVE')
    Question: as shown in above query, suppose in our where clause, we have a condition with IN construct whose subquery is independent (it is not using any column of master query's resultset.). Then, will that query be executed only once or will it be executed for N number of times (N= number of records in emp table)
    In other words, how may times the subquery of IN clause as in above query be executed by complier to prepared the subquery's resultset?
    2)
    Suppose the we use the EXISTS clause (or NOT EXISTS clause) with subquery where, the subquery uses the field of master query in its where clause.
    SELECT E.empno, E.ename
    FROM emp E
    WHERE E.salary &gt;=5000
    AND EXISTS (SELECT 'X' FROM dept D where status = 'ACTIVE' AND D.deptno = E.deptno)
    Here also, I got same confusion. For how many times the subquery for EXISTS will be executed by oracle. For one time or for N number of times (I think, it will be N number of times).
    3)
    I know we can't define any fix thumbrule and its highly depends on requirement and other factors, but in general, Suppose our main query is on heavily loaded large transaction table and need to check existance of record in some less loaded and somewhat smaller transaction table, than which way will be better from performance point of view from above three. (1. Use of JOIN, 2. Use of IN, 3. Use of EXISTS)
    Please help me get solutions to these confusions..
    Thanks and Regards,
    Dipali..

    Dipali,
    First, I posted the links with my name only, I don;t know how did you pick another handle for addressing it?Never mind that.
    >
    Now another confusion I got.. I read that even if we used EXISTS and , CBO feels (from statistics and all his analysis) that using IN would be more efficient, than it will rewrite the query. My confusion is that, If CBO is smart enough to rewrite the query in its most efficient form, Is there any scope/need for a Developer/DBA to do SQL/Query tuning? Does this means that now , developer need not to work hard to write query in best menner, instade just what he needs to do is to write the query which resluts the data required by him..? Does this now mean that now no eperts are required for SQL tuning?
    >
    Where did you read that?Its good to see the reference which says this.I haven't come across any such thing where CBO will rewrite the query like this. Have a look at the following query.What we want to do is to get the list of all teh departments which have atleast one employee working in it.So how would be we write this query? Theremay be many ways.One,out of them is to use distinct.Let's see how it works,
    SQL> select * from V$version;
    BANNER
    Oracle Database 11g Enterprise Edition Release 11.1.0.6.0 - Production
    PL/SQL Release 11.1.0.6.0 - Production
    CORE    11.1.0.6.0      Production
    TNS for 32-bit Windows: Version 11.1.0.6.0 - Production
    NLSRTL Version 11.1.0.6.0 - Production
    SQL> set timing on
    SQL> set autot trace exp
    SQL> SELECT distinct  D.deptno, D.dname
      2        FROM     scott.dept D,scott.emp E
      3  where e.deptno=d.deptno
      4  order by d.deptno;
    Elapsed: 00:00:00.12
    Execution Plan
    Plan hash value: 925733878
    | Id  | Operation                     | Name    | Rows  | Bytes | Cost (%CPU)| T
    ime     |
    |   0 | SELECT STATEMENT              |         |     9 |   144 |     7  (29)| 0
    0:00:01 |
    |   1 |  SORT UNIQUE                  |         |     9 |   144 |     7  (29)| 0
    0:00:01 |
    |   2 |   MERGE JOIN                  |         |    14 |   224 |     6  (17)| 0
    0:00:01 |
    |   3 |    TABLE ACCESS BY INDEX ROWID| DEPT    |     4 |    52 |     2   (0)| 0
    0:00:01 |
    |   4 |     INDEX FULL SCAN           | PK_DEPT |     4 |       |     1   (0)| 0
    0:00:01 |
    |*  5 |    SORT JOIN                  |         |    14 |    42 |     4  (25)| 0
    0:00:01 |
    |   6 |     TABLE ACCESS FULL         | EMP     |    14 |    42 |     3   (0)| 0
    0:00:01 |
    Predicate Information (identified by operation id):
       5 - access("E"."DEPTNO"="D"."DEPTNO")
           filter("E"."DEPTNO"="D"."DEPTNO")
    SQL>
    SQL> SELECT distinct  D.deptno, D.dname
      2        FROM     scott.dept D,scott.emp E
      3  where e.deptno=d.deptno
      4  order by d.deptno;
        DEPTNO DNAME
            10 ACCOUNTING
            20 RESEARCH
            30 SALES
    Elapsed: 00:00:00.04
    SQL>So CBO did what we asked it do so.It made a full sort merge join.Now there is nothing wrong in it.There is no intelligence added by CBO to it.So now what, the query looks okay isn't it.If the answer is yes than let's finish the talk here.If no than we proceed further.
    We deliberately used the term "atleast" here.This would govern that we are not looking for entirely matching both the sources, emp and dept.Any matching result should solve our query's result.So , with "our knowledge" , we know that Exist can do that.Let's write teh query by it and see,
    SQL> SELECT   D.deptno, D.dname
      2        FROM     scott.dept D
      3          WHERE    EXISTS
      4                 (SELECT 1
      5                  FROM   scott.emp E
      6                  WHERE  E.deptno = D.deptno)
      7        ORDER BY D.deptno;
        DEPTNO DNAME
            10 ACCOUNTING
            20 RESEARCH
            30 SALES
    Elapsed: 00:00:00.00
    SQL>Wow, that's same but there is a small difference in the timing.Note that I did run the query several times to elliminate the physical reads and recursive calls to effect the demo. So its the same result, let's see the plan.
    SQL> SELECT   D.deptno, D.dname
      2        FROM     scott.dept D
      3          WHERE    EXISTS
      4                 (SELECT 1
      5                  FROM   scott.emp E
      6                  WHERE  E.deptno = D.deptno)
      7        ORDER BY D.deptno;
    Elapsed: 00:00:00.00
    Execution Plan
    Plan hash value: 1090737117
    | Id  | Operation                    | Name    | Rows  | Bytes | Cost (%CPU)| Ti
    me     |
    |   0 | SELECT STATEMENT             |         |     3 |    48 |     6  (17)| 00
    :00:01 |
    |   1 |  MERGE JOIN SEMI             |         |     3 |    48 |     6  (17)| 00
    :00:01 |
    |   2 |   TABLE ACCESS BY INDEX ROWID| DEPT    |     4 |    52 |     2   (0)| 00
    :00:01 |
    |   3 |    INDEX FULL SCAN           | PK_DEPT |     4 |       |     1   (0)| 00
    :00:01 |
    |*  4 |   SORT UNIQUE                |         |    14 |    42 |     4  (25)| 00
    :00:01 |
    |   5 |    TABLE ACCESS FULL         | EMP     |    14 |    42 |     3   (0)| 00
    :00:01 |
    Predicate Information (identified by operation id):
       4 - access("E"."DEPTNO"="D"."DEPTNO")
           filter("E"."DEPTNO"="D"."DEPTNO")Can you see a keyword called Semi here? This means that Oralce did make an equi join but not complete.Compare the bytes/rows returned from this as well as cost with the first query.Can you notice the difference?
    So what do we get from all this?You asked that if CBO becomes so smart, won't we need developers/dbas at that time?The answer is , what one wants to be, a monkey or an astranaut? Confused,read this,
    http://www.method-r.com/downloads/doc_download/6-the-oracle-advisors-from-a-different-perspective-karen-morton
    So it won't matter how much CBO would become intelligent, there will be still limitations to where it can go, what it can do.There will always be a need for a human to look all the automations.Rememember even the most sofisticated system needs some button to be pressed to get it on which is done by a human hand's finger ;-).
    Happy new year!
    HTH
    Aman....

  • IN clause Vs Exist clause

    Which is better to use in select query IN or EXIST clause ??

    Which better in terms of what performance,readability ? Performance is the same  but EXISTS is more readable and easy understand in my opinion.
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • IN vs EXISTS clause

    I have seen in some of the posts that using 'EXISTS' clause in place of 'IN' yields better performance results.
    For example
    update customer
    set type = 'emp'
    where cid in (select empid from employees)
    I have 1 million rows in customer and 500k rows in employee table in this case is it better to use 'EXISTS' instead of 'IN' clause. Also does datatype of the column have effect on the type of clause being used.
    Any suggestions/inputs ???
    Thanks

    Andre Crone recently published some interesting thoughts on the Amis blog. Check it out.
    Cheers, APC

  • Where Exist clause to improve query performance

    select * from emp
    where emp_code in (select emp_code from emp_acct)
    it is said tht its always better to use where exist clause instead of IN.
    I hav written the same query using where Exist,
    select * from emp e
    where exists (select null from emp_acct ea where e.emp_code = ea.emp_acct)
    but both these queries are sharing the same cost.
    is there is any other way to use exist to decrease cost of the query.
    ---Piyush

    You can't compare the cost of two different queries.
    You can't relate cost to the running time of the query.
    Having said that, why is this not just a join?
    select e.*
    from emp e
    , emp_acct ea
    where e.emp_code = ea.emp_codecheers,
    Anthony

  • Update statement with EXISTS clause

    I saw this code in one of the procedures we are using ... is it possible to avoid EXIST caluse:
    update table_x p
    set p.internal_issue_ky = (select sh.internal_issue_ky
    from security_history sh, XT_SECURITY xs
    where sh.internal_wins_issue_id = xs.internal_wins_issue_id
    and sh.as_of_dt = xs.as_of_date
    and p.internal_wins_issue_id = sh.internal_wins_issue_id
    and p.effective_dt between sh.as_of_dt and sh.next_as_of_dt
    where exists
    (select sh.internal_issue_ky
    from security_history sh, XT_SECURITY xs
    where sh.internal_wins_issue_id = xs.internal_wins_issue_id
    and sh.as_of_dt = xs.as_of_date
    and p.internal_wins_issue_id = sh.internal_wins_issue_id
    and p.effective_dt between sh.as_of_dt and sh.next_as_of_dt
    Thanks.

    Without the EXISTS, every record in the table will be updated, and those that don't exist in the subquery will be updated with NULL. The EXIST clause ensures that only those records that form the subset in the subquery are updated, and is necessary here.

  • How to write this query using correlation subquery or non exists clause

    -- Tables description.
    --step-1- 4 employees present in EMP table.
    --step-2- each employee having 1 country_no in EMP_DOCS table.3 employees having same country_no(i.e emp's 1,2,3)
    --step-3- 1 emp document can have multiple items.In this case each employee having one each in the EMP_ITEMS table.
    --step-4- 1 EMPLOYEE  can have Multiple Documents so we have a relation between EMP_ITEMS and DOCUMENT_ITEMS.whatever items present in EMP_ITEMS those items will be inserted into DOCUMENT_ITEMS.so we have a item-item relation.
    --so we stored EMP_ITEMS id in EMP_ITEMS_REF_ID_1 of DOCUMENT_ITEMS table.
    -- step-5- DOCUMENT-INVOICE has 1-1 relation once invoice is created we stored invoice id in DOCUMENT table.
    --This is the requirement.Let's say in this example 3 employees are using same country_no and 4th employee is using another country_no
    --which is not used by other 3 employees.
    --Condtion-1:
    --if all of the employees have created INVOICE which is using same country_no of different country_no then the query should display all records.
    --Condition-2:
    --if any one of the employee not created INVOICE which is using same country_no of other employees then remaining employees also should not come in the query
    -- even though invoice is created by other employees.
    --Condition-3:
    --if any one of the employee not created even DOCUMENT  which is using same country_no of other employees then remaining employees also should not come in the query
    -- even though invoice is created by other employees.
    I hope I explain the conditions clearly.if you understand well by looking at the data i posted below may i know what is the final result should be displayed?
    create table EMP
      ID       NUMBER not null,
      TYPE     VARCHAR2(1)
    alter table EMP
      add constraint ID primary key (ID);
    create table EMP_DOCS
      ID         NUMBER not null,
      EMP_ID     NUMBER,
      COUNTRY_NO VARCHAR2(15)
    alter table EMP_DOCS
      add constraint PK_EMP_DT primary key (ID);
    alter table EMP_DOCS
      add constraint FK_EMP_DT foreign key (EMP_ID)
      references EMP (ID);
    create table EMP_ITEMS
      ID         NUMBER not null,
      EMP_DOC_ID     NUMBER
    alter table EMP_ITEMS
      add constraint PK_EMP_ITEMS_DT primary key (ID);
    alter table EMP_ITEMS
      add constraint FK_EMP_ITEMS_DT foreign key (EMP_DOC_ID)
      references EMP_DOCS (ID);
      create table DOCUMENT
      ID   NUMBER not null,
      DOCNO VARCHAR2(15),
      INVOICE_REF_1 NUMBER
    alter table DOCUMENT
      add constraint DOC_PK_ID primary key (ID);
      create table DOCUMENT_ITEMS
      ID         NUMBER not null,
      DOC_ID     NUMBER,
      EMP_ITEMS_REF_ID_1    NUMBER
    alter table DOCUMENT_ITEMS
      add constraint PK_DOCUMENT_ITEMS_DT primary key (ID);
    alter table DOCUMENT_ITEMS
      add constraint FK_DOCUMENT_ITEMS_DT foreign key (DOC_ID)
      references DOCUMENT (ID);
    create table INVOICE
      ID   NUMBER not null,
      INVOICE_NO VARCHAR2(15)
    alter table INVOICE
      add constraint INVOICE_PK_ID primary key (ID);
      INSERT INTO EMP ( ID, TYPE ) VALUES (
    1, 'A');
    INSERT INTO EMP ( ID, TYPE ) VALUES (
    2, 'A');
    INSERT INTO EMP ( ID, TYPE ) VALUES (
    3, 'A');
    INSERT INTO EMP ( ID, TYPE ) VALUES (
    4, 'A');
    INSERT INTO EMP_DOCS ( ID, EMP_ID, COUNTRY_NO ) VALUES (
    1, 1, 'INDIA');
    INSERT INTO EMP_DOCS ( ID, EMP_ID, COUNTRY_NO ) VALUES (
    2, 2, 'INDIA');
    INSERT INTO EMP_DOCS ( ID, EMP_ID, COUNTRY_NO ) VALUES (
    3, 3, 'INDIA');
    INSERT INTO EMP_DOCS ( ID, EMP_ID, COUNTRY_NO ) VALUES (
    4, 4, 'USA');
    INSERT INTO EMP_ITEMS ( ID, EMP_DOC_ID ) VALUES (
    1, 1);
    INSERT INTO EMP_ITEMS ( ID, EMP_DOC_ID ) VALUES (
    2, 2);
    INSERT INTO EMP_ITEMS ( ID, EMP_DOC_ID ) VALUES (
    3, 3);
    INSERT INTO EMP_ITEMS ( ID, EMP_DOC_ID ) VALUES (
    4, 4);
    INSERT INTO DOCUMENT ( ID, DOCNO, INVOICE_REF_1 ) VALUES (
    1, 'DOC1', 1);
    INSERT INTO DOCUMENT ( ID, DOCNO, INVOICE_REF_1 ) VALUES (
    2, 'DOC1', 2);
    INSERT INTO DOCUMENT ( ID, DOCNO, INVOICE_REF_1 ) VALUES (
    3, 'DOC3', 0);
    INSERT INTO DOCUMENT ( ID, DOCNO, INVOICE_REF_1 ) VALUES (
    4, 'DOC4', 3);
    INSERT INTO DOCUMENT_ITEMS ( ID, DOC_ID, EMP_ITEMS_REF_ID_1 ) VALUES (
    1, 1, 1);
    INSERT INTO DOCUMENT_ITEMS ( ID, DOC_ID, EMP_ITEMS_REF_ID_1 ) VALUES (
    2, 2, 2);
    INSERT INTO DOCUMENT_ITEMS ( ID, DOC_ID, EMP_ITEMS_REF_ID_1 ) VALUES (
    3, 2, 2);
    INSERT INTO DOCUMENT_ITEMS ( ID, DOC_ID, EMP_ITEMS_REF_ID_1 ) VALUES (
    4, 3, 3);
    INSERT INTO DOCUMENT_ITEMS ( ID, DOC_ID, EMP_ITEMS_REF_ID_1 ) VALUES (
    5, 4, 4);
    INSERT INTO INVOICE ( ID, INVOICE_NO ) VALUES (
    1, 'INV1');
    INSERT INTO INVOICE ( ID, INVOICE_NO ) VALUES (
    2, 'INV2');
    INSERT INTO INVOICE ( ID, INVOICE_NO ) VALUES (
    3, 'INV3');
    commit;
    -- I have written below query to satisfy above conditions but still required results are not coming..
    SELECT *
      FROM EMP E
    WHERE E.TYPE = 'A'
       AND NOT EXISTS (SELECT *
              FROM EMP_DOCS       EDOC1,
                   EMP_DOCS       EDOC2,
                   EMP            E1,
                   EMP_ITEMS      EMPI,
                   DOCUMENT_ITEMS DOCITM,
                   DOCUMENT       DOC,
                   INVOICE        INV
             WHERE EDOC1.EMP_ID = E.ID
               AND EDOC2.EMP_ID = E1.ID
               AND EDOC1.ID = EMPI.EMP_DOC_ID
               AND EDOC1.COUNTRY_NO = EDOC2.COUNTRY_NO
               AND EMPI.ID = DOCITM.EMP_ITEMS_REF_ID_1
               AND DOCITM.DOC_ID = DOC.ID
               AND INV.ID = DOC.INVOICE_REF_1);

    DB version:oracle 10g;10.2

  • How to simulate an EXISTS clause

    Hi,
    I have a report where the Fiscal Quarter and Year are prompted, and the report only shows the last 2 years by using the following filter:
    "Reporting Period"."Fiscal Year" IN (@{p_fiscal_year}{valueof("CurrentSAFiscalYear")},(@{p_fiscal_year}{valueof("CurrentSAFiscalYear")})-1)
    My problem is that if the particular fiscal year/quarter has no data, the users don't want any data to appear. This would normally be handled with a
    where exists (select 1 from fact where year = current year). How would I do something similar in OBIEE?

    so what you can possibly do is create a reference report
    where there are 2 columns :
    column 1 fact.year filter = variable current year
    column 2 fact.year -1
    Then in main report just use
    fact.year in advanced filter reference report--equal to -- fact.year
    OR
    fact.year in advanced filter reference report--equal to -- fact.year-1
    hope this helps.

Maybe you are looking for

  • Finder window doest not start

    On my wifes mac mini, we can no longer get finder to load, the system boots fine, and we can run a few applications, iTunes and safari. When i try to open finder to install new apps like firefox and clamXav, the finder window never opens. I have trie

  • Linked cells in same workbook are no longer working

    I created a workbook with multiple worksheets, with some cells containing data linked from one sheet to the next - there is no linking to external data.  The linking was done by the copy and paste link option and locking the cells in the destination

  • How to restrict the entries of a database table based on the user name

    Hi All, I have created a Database Table. Table maintenance generator is generated for the table. UNAME(user name) is one of the fields in the table. whenever the user creates a new entry, the field UNAME will be populated automatically with SY-UNAME

  • How do i parse an xml with a string?

    I got a string (ex. "<testing><testing1>bla</testing1></testing>") and i would like to temparory store in XmlDocument so that i can retrieve the value. I am new in using xml... Can you all pls help? urgent thanks

  • XSLT mapping tools

    Hi all I have a scenario in which i have to map from xsd to wsdl,but client requirements are as such that I have to use XSLT mapping.To the best of knowledge I have stylus studio does not support mapping in which wsdl is involved.What are the tools t