Query difference. UNION vs OR

Connected to:
Oracle9i Enterprise Edition Release 9.2.0.8.0 - 64bit Production
With the Partitioning, Oracle Label Security, OLAP and Oracle Data Mining options
JServer Release 9.2.0.8.0 - ProductionHello,
Sorry for a question on EOD friday.
I have three tables.(original tables have millions of rows)
Here is the sample create statements.
CREATE TABLE table1
AS
   (SELECT LEVEL col1, 10 col2
      FROM DUAL
    CONNECT BY LEVEL <= 500000
    UNION ALL
    SELECT LEVEL col1, 20 col2
      FROM DUAL
    CONNECT BY LEVEL <= 10000);
CREATE TABLE table2
AS
   (SELECT LEVEL col1,
           10 col2,
           'MAIN' col3,
           0 col4,
           LEVEL * 111 col5
      FROM DUAL
    CONNECT BY LEVEL <= 500000
    UNION ALL
    SELECT 20 col1,
           20 col2,
           'PRAC' col3,
           1 col4,
           999 col5
      FROM DUAL);
CREATE TABLE table3
AS
   (SELECT CEIL (LEVEL / 6) col1, LEVEL col2
      FROM DUAL
    CONNECT BY LEVEL <= 3000000);And I have this query written long ago by some one.
SELECT /*+ full(t1) full(t2) full(t3) */
      t1.col1,t1.col2,t2.col5,t3.col2
  FROM table1 t1, table2 t2,table3 t3
WHERE t1.col1 = t2.col1
   AND t1.col2 = t2.col2
   AND t1.col1 = t3.col1
UNION
SELECT /*+ full(t1) full(t2) full(t3) */
      t1.col1,t1.col2,t2.col5,t3.col2
  FROM table1 t1, table2 t2,table3 t3
WHERE t2.col3 = 'PRAC'
   AND t2.col4 = 1
   AND t1.col2 = t2.col2
   AND t1.col1 = t3.col1;     A little background on the business: For every row in table 1 there will be a row in table2 where both col1 and col2 matches.
and there might be one more row where only col2 matches and t2.col3='PRAC' and t2.col4=1.
That row is a common contract and will be shared by multiple rows in table1. You can see that when you execute the above select.
And for every row in table1 there are 6 rows in table3.
Now, After seeing the above select, I have changed it to the following simply which gives me same results and started testing it.
Which I have no doubts is simple and more efficient.
SELECT /*+ full(t1) full(t2) full(t3)*/
      t1.col1,t1.col2,t2.col5,t3.col2
  FROM table1 t1, table2 t2,table3 t3
WHERE (t1.col1 = t2.col1
     OR  (t2.col3 = 'PRAC'
      AND t2.col4 = 1))
   AND t1.col2 = t2.col2
   AND t1.col1=t3.col1
ORDER BY t1.col1;But surprisingly, the new query is taking for ever. What is wrong with a full table scan and an OR clause?
In the old query we have a simple joins in both parts of the union and my new query will return either 1 or 2 rows for every row in table1.
Not sure whats wrong.
G.
Edited by: Ganesh Srivatsav on Apr 29, 2011 3:51 PM
Edited by: Ganesh Srivatsav on Apr 29, 2011 4:57 PM

here is what I got
SELECT /*+ full(t1) full(t2) */
      t1.col1,t1.col2,t2.col5
  FROM table1 t1, table2 t2
WHERE t1.col1 = t2.col1
   AND t1.col2 = t2.col2
UNION
SELECT /*+ full(t1) full(t2) */
      t1.col1,t1.col2,t2.col5
  FROM table1 t1, table2 t2
WHERE t2.col3 = 'PRAC'
   AND t2.col4 = 1
   AND t1.col2 = t2.col2;
Elapsed: 00:00:00.04
plan
SELECT STATEMENT  CHOOSECost: 11  Bytes: 349  Cardinality: 5                      
     8 SORT UNIQUE  Cost: 11  Bytes: 349  Cardinality: 5                 
          7 UNION-ALL            
               3 HASH JOIN  Cost: 5  Bytes: 65  Cardinality: 1       
                    1 TABLE ACCESS FULL TABLE DSAMSTRC.TABLE2 Cost: 2  Bytes: 234  Cardinality: 6 
                    2 TABLE ACCESS FULL TABLE DSAMSTRC.TABLE1 Cost: 2  Bytes: 182  Cardinality: 7 
               6 HASH JOIN  Cost: 5  Bytes: 284  Cardinality: 4       
                    4 TABLE ACCESS FULL TABLE DSAMSTRC.TABLE2 Cost: 2  Bytes: 45  Cardinality: 1 
                    5 TABLE ACCESS FULL TABLE DSAMSTRC.TABLE1 Cost: 2  Bytes: 182  Cardinality: 7 
SELECT /*+ full(t1) full(t2) */
      t1.col1,t1.col2,t2.col5
  FROM table1 t1, table2 t2
WHERE (t1.col1 = t2.col1
     OR  (t2.col3 = 'PRAC'
      AND t2.col4 = 1))
   AND t1.col2 = t2.col2
ORDER BY t1.col1;
Elapsed: 00:00:00.03
Plan
SELECT STATEMENT  CHOOSECost: 6  Bytes: 336  Cardinality: 4                 
     4 SORT ORDER BY  Cost: 6  Bytes: 336  Cardinality: 4            
          3 HASH JOIN  Cost: 5  Bytes: 336  Cardinality: 4       
               1 TABLE ACCESS FULL TABLE DSAMSTRC.TABLE2 Cost: 2  Bytes: 348  Cardinality: 6 
               2 TABLE ACCESS FULL TABLE DSAMSTRC.TABLE1 Cost: 2  Bytes: 182  Cardinality: 7 

Similar Messages

  • Query with union

    Hi,
    I have three table:
    Candidates: (candidate_id primary key)
    Purhcase_orders: (Po_number primary key)
    Bids: (bid_number primary key)
    Just wanted to retrieve candidate information like candidate_id, first_name etc, along with count of purchase orders issued against this candidate and count of bid_number.
    For that I have written below query:
    query - 1:
    SELECT CANDIDATE_ID,
    INITCAP (first_name) FIRST_NAME,
    +(SELECT COUNT (DISTINCT bid_number)+
    FROM bids
    WHERE BIDS.CANDIDATE_ID = cand.candidate_id)
    BID_COUNT,
    +(SELECT COUNT (DISTINCT po_number)+
    FROM purchase_orders po
    WHERE PO.CONTRACTEE_ID = cand.candidate_id)
    PO_COUNT,
    +'Y' match_flag,+
    DECODE ( (SELECT candidate_id
    FROM v_ineligible_candidates vic
    WHERE VIC.CANDIDATE_ID = cand.candidate_id),
    NULL, 'N',
    +'Y')+
    INELIGIBLE_FLAG
    FROM candidates cand
    Based on business requirement, need to create another set of query (query -2) same like above. In that we have some decode statements to calculate match_flag, then need to perform UNION operation between query -1 and query -2.
    have around 130563 number of rows in candidates table.
    Individually both queries are taking 500 msec.
    But when I have used union, it didnt give result for atleast 60 sec. Then I cancelled execution.
    Execution plan for the final query with UNION: (final cost)
    Cost: 2,873  Bytes: 9,130,170  Cardinality: 260,862                
    Please help me in this issue.
    Why its taking that much time in union.
    Please correct my mistake and suggest me in this query.
    UNION ALL is running but not UNION.
    Thanks in advance

    Please post complete Explain Plans.
    To get detailed information of Explain Plan use
    explain plan for
    your_query;
    select *
      from table(dbms_xplan.display(null, null, 'ALL'));Post it alongwith below details between {noformat}{noformat} (exactly as specified) tags to preserve formatting and ease of understanding.
    On your requirement,
    Using UNIONALL you will get two set of rows, with UNION you might get a single row if your MATCH_FLAG are same for both queries. Use of either, has to meet your requirements than to meet your performance. If it is Business Acceptable, then look for performance and tuning.
    If you could do the folllowing, it might be helpful for you.
    1. Post the Sample table structure (Table information of Candidates should suffice) in a Create Table/With Sub-Query clause.
    2. Sample Data in Insert Into/With Sub-Query format.
    3. Expected Outcome based on Sample data
    4. The Explain Plan of your Queries as requested above.
    Reason of asking these details are, there might be a way to avoid Hitting the table Twice and avoid use of UNION/UNIONALL clauses.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Select query differences between oracle 9 and oracle 8.

    Hi,
    I have a problem using the select query between oracle 7 and oracle 9i I don't have the same result :
    ex:
    With oracle7
    SQL> select 'champ1','champ2' from DUAL;
    'CHAMP 'CHAMP
    champ1 champ2
    With Oracle 9
    SQL> select 'champ1','champ2' from DUAL;
    'CHAMP1' 'CHAMP2'
    champ1 champ2
    So Can someone tell me how to solve this problem ? Is there a parameter in oracle 9 to set?
    Thanx.

    Whenever you are posting anything over internet forums like this - you should be very careful about not just posting the details which requires to solve the problem - also should be sensible about your question.
    This is not at all desired when you are posting such question. It may be because - you may not well aware of the fact.
    My suggestion is -> First Go through the basics Of SQL in general.
    Then go for any specific product like Oracle/ SQL Server/ Sybase etc.
    And, finally learn the advanced commands of that DB.
    You asked it - may be you thought the difference in output in terms of lines. But, that is not your actual output. That is the graphical display part only.
    Anyway,
    You can get the quite familier output by first type the following command ->
    set lin 310Regards.
    Satyaki De.

  • Returning a count from a query using Union

    Hi. I'm attempting to select a count from this query and then display the total in a message, but I'm getting a 'Too many rows returned' (ORA-01422). Can anyone tell me how I can achieve a total for this query?
             SELECT nvl(count(*),0)
           INTO conflict_cnt
           FROM dropper_assign
           WHERE dropper_id = :dropper_vacations.dropper_id AND
                trunc(sched_date) between :begin_dt and :end_dt
              union                          
       SELECT nvl(count(*),0)
        FROM exfc.bundle a, splits b
        WHERE a.bundle = b.bundle AND
             b.dropper_id = :dropper_vacations.dropper_id AND
             trunc(a.actual_dt) between :begin_dt and :end_dt;
              call_alert.the_error('test: '||to_char(conflict_cnt));Any help would be greatly appreciated.

    Thanks Christian, I can know return to my favourite present occupation named HOLIDAYS ;)
    btw with count function as the first message
    WITH
      data AS
        SELECT
          COUNT(*) cnt
        FROM
          dual
          CONNECT BY level <= 10
        UNION
        SELECT
          COUNT(*) cnt
        FROM
          dual
          CONNECT BY level <= 20
    SELECT
      SUM(cnt)
    FROM
      data
    SUM(CNT)              
    30        
    /* and */
    WITH
      data AS
        SELECT
          COUNT(*) cnt
        FROM
          dual
          CONNECT BY level <= 10
        UNION ALL /****** returns me also 30 *****/
        SELECT
          COUNT(*) cnt
        FROM
          dual
          CONNECT BY level <= 20
    SELECT
      SUM(cnt)
    FROM
      data
    SUM(CNT)              
    30       result will defer only if both count return exactly the same value so definitely UNION ALL for that case or the simple solution I have provided before ...
    but leave it. that's enough messages for this thread ;)
    Jean-Yves
    Edited by: JeanYves Bernier on 9 août 2011 17:42

  • Select query with UNION clause in database adapter

    Friends,
    I have got a SQL query with two UNION clause withing it. like
    select a,b,c
    from a
    union
    select a,b,c
    from b
    The schema generated is like below in sequence
    <element>a</element>
    <element>b</element>
    <element>c</element>
    <element>a</element>
    <element>b</element>
    <element>c</element>
    So, the columns from different select queries joined with UNION clause are all appeared in schema instead of the distinct columns.
    Is there any way around to solve this issue ? or will need to with DB function/procedure.

    I think I know what you are saying but your example doesn't make sense, your SQL should produce something like
    I had to change a, b, c with elementA, elementB, elementC as a and b are reserved html tags.
    <elementA>DateA</elementA>
    <elementB>DataB</elementB>
    <elementC>DataC</elementC>
    ...What is the result of the query when you run it in SQLPlus? Is it what you expect?
    cheers
    James

  • Query with Union to Show Ship to of Both Supplier & Customer BP's

    Hi Guys,
    I need to do a query that I can use in a formatted search, that will allow me to select from a list that shows both BP Ship to Addresses from The Customer and Supplier Tables. I know I have to use a union, however I have no clue where to start with this - would someone be so kind as to point me in the right directions please.
    Kind regards
    Sean Martin
    Edited by: Sean Martin on Apr 18, 2011 5:20 PM

    Hello Sean - I see you are new - let me welcome you to the SAP B1 forums...
    Maybe you do have the wrong forum as Julie suggests above, but maybe it is a bit perplexing as to what you need in an SAP B1 sense...
    1.  Let us know where you would be using the formatted search (in the Sales documents? - in the Purchasing documents?) - OR - maybe give a business scenario...
    2.  Let us know what field the results would populate...
    3.  Are you looking for two formatted searches - one to be used with suppliers and one to to be used for customers - OR - do you want the formatted search to list all Ship-To addresses combined into one list?
    4.  A statement of UNION might not be needed!
    5.  The tables to reference in the formatted search are OCRD and CRD1.
    That way you can help us help you better...again, wecome and...
    Regards - Zal

  • Command Query using UNION

    Hello,
    I may be barking up the wrong tree and asking this question in the wrong forum so please accept my apologies if this is the case.
    I have access to a MYSql database through a ODBC connection and would like to create a report based on four tables (let's say A, B, C and D) where tables A & B hold biographical data and tables C & D  contain different attribute detail with identical column names (attrib_name and attrib_desc) that relate to A & B .
    The report I would like to create will list records from both A and B along with corresponding records from C and D merged into two columns attrib_name and attrib_desc.
    I have tried a couple of versions of a union query but I just cannot seem to get it to generate the correct output.
    Any help would be much appreciated.
    Thank you
    Paul

    hi Paul,
    Command objects are written in syntax specific to the database that you're using, so you may be best off looking at mysql forums instead. plus you haven't really stated what the issue is that you experiencing.
    given the above, here's a couple basic things about UNION syntax...
    1 the number of fields selected must be the same
    2 the corresponding fields should be in the same sequence
    3 the types (e.g. date, integer) must match
    4 in your SELECT statement use an AS 'name' for each field so that the field names match up in both sets in the query
    you may also wish to use a UNION ALL instead of a UNION as UNION ALL will ensure that all records are brought back as opposed to UNION which does a check on a virtual record set to ensure that there's no duplicates...this in turn can cause performance to suffer a bit.

  • Writing query using UNION Operator

    Question -
    (1)
    Write an SQL Statement to list the following items: Customer ID, Customer Name, number of invoices, sum of total for invoices. Ensure that all customers are returned in the result set.
    Answer for the above is written as below by one person. That seams to be correct. Is there another way of writing this same query.;
    select c.CUSTOMER_ID,c.NAME,i.cnt,i.s
    from gee_customer c,(select customer_id,count(*) as cnt, sum(TOTAL) as s
    from gee_invoice
    group by customer_id) i
    where c.CUSTOMER_ID = i.customer_id (+)
    (2)
    My other question is How to write the above answer (or what you sugest) using UNION operator ?
    Any ideas please
    Message was edited by:
    user483578

    In fact the outer join means you use the union of two result sets - usual join result
    and the rows from the outer table for which there is not any row in the inner table.
    SQL> select d.deptno, e.ename from emp e, dept d
      2  where d.deptno = e.deptno(+)
      3  order by 1,2
      4  /
        DEPTNO ENAME
            10 CLARK
            10 KING
            10 MILLER
            20 ADAMS
            20 FORD
            20 JONES
            20 SCOTT
            20 SMITH
            30 ALLEN
            30 BLAKE
            30 JAMES
            30 MARTIN
            30 TURNER
            30 WARD
            40
    15 rows selected.
    SQL> select d.deptno,e.ename from emp e, dept d
      2  where d.deptno = e.deptno
      3  union
      4  select deptno, null
      5  from dept d where not exists (select null from emp e where e.deptno = d.deptno)
      6  order by 1,2
      7  /
        DEPTNO ENAME
            10 CLARK
            10 KING
            10 MILLER
            20 ADAMS
            20 FORD
            20 JONES
            20 SCOTT
            20 SMITH
            30 ALLEN
            30 BLAKE
            30 JAMES
            30 MARTIN
            30 TURNER
            30 WARD
            40
    15 rows selected.In your example something like (NOT tested !)
    with i as (select customer_id,count(*) as cnt, sum(TOTAL) as s
    from gee_invoice group by customer_id)
    select c.CUSTOMER_ID,c.NAME,i.cnt,i.s
    from gee_customer c, i
    where c.CUSTOMER_ID = i.customer_id
    union
    select c.CUSTOMER_ID,c.NAME,null,null
    from gee_customer c
    where not exists (select null from i where c.CUSTOMER_ID = i.customer_id)
    Rgds.

  • Query using Union All and CTEs is slow

    TypePatient
    [ednum] int NOT NULL,  PK
    [BackgroundID] int NOT NULL, FK
    [Patient_No] varchar(50) NULL, FK
    [Last_Name] varchar(30) NULL,
    [First_Name] varchar(30) NULL,
    [ADateTime] datetime NULL,
    Treat
    [ID] int NOT NULL, PK
    [Ednum] numeric(10, 0) NOT NULL, FK
    [Doctor] char(50) NULL,
    [Dr_ID] numeric(10, 0) NULL,
    background
    [ID] int NOT NULL, PK
    [Patient_No] varchar(50) NULL, FK
    [Last_Name] char(30) NULL,
    [First_Name] char(30) NULL,
    [DateofBirth] datetime NULL,
    pdiagnose
    [ID] int NOT NULL, PK
    [Ednum] int NOT NULL, FK
    [DSMNo] char(10) NULL,
    [DSMNoIndex] char(5) NULL,
    substance
    [ID] int NOT NULL, PK
    [Ednum] int NOT NULL, FK
    [Substance] varchar(120) NULL,
    DXCAT
    [id] int NULL, PK
    [dx_description] char(100) NULL,
    [dx_code] char(10) NULL,
    [dx_category_description] char(100) NULL,
    [diagnosis_category_code] char(10) NULL)
    Substance
    ID
    Ednum
    Substance
    1
    100
    Alcohol Dependence
    4
    200
    Caffeine Dependence
    5
    210
    Cigarettes
    dxcat
    id
    dx_description
    dx_code
    dx_category_description
    diagnosis_category_code
    10
    Tipsy
    zzz
    Alcohol
    SA
    20
    Mellow
    ppp
    Mary Jane
    SA
    30
    Spacey
    fff
    LSD
    SA
    50
    Smoker
    ggg
    Nicotine
    SA
    pdiagnose
    ID
    Ednum
    DSMNo
    Diagnosis
    1
    100
    zzz
    Alcohol
    2
    100
    ddd
    Caffeine
    3
    210
    ggg
    Smoker
    4
    130
    ppp
    Mary Jane
    TypePatient
    ednum
    Patient_No
    Last_Name
    First_Name
    ADateTime
    100
    sssstttt
    Wolly
    Polly
    12/4/2013
    130
    rrrrqqqq
    Jolly
    Molly
    12/8/2013
    200
    bbbbcccc
    Wop
    Doo
    12/12/2013
    210
    vvvvwww
    Jazz
    Razz
    12/14/2013
    Treat
    ID
    Ednum
    Doctor
    Dr_ID
    2500
    100
    Welby, Marcus
    1000
    2550
    200
    Welby, Marcus
    1000
    3000
    210
    Welby, Marcus
    1000
    3050
    130
    Welby, Marcus
    1000
    background
    ID
    Patient_No
    Last_Name
    First_Name
    DateofBirth
    2
    sssstttt
    Wolly
    Polly
    8/6/1974
    3
    rrrrqqqq
    Jolly
    Molly
    3/10/1987
    5
    bbbbcccc
    Wop
    Doo
    8/12/1957
    6
    vvvvwww
    Jazz
    Razz
    7/16/1995
    Desired output:
    Staff ID
    Doctor
    Patient_No
    Client Name
    Date of Service
    Ednum
    DX Code
    DX Cat
    DX Desc
    Substance
    1000
    Welby, Marcus
    bbbcccc
    Wop, Doo
    12/12/2013
    200
    Caffeine Dependence
    1000
    Welby, Marcus
    rrrqqq
    Jolly, Molly
    12/8/2013
    130
    ppp
    SA
    Mary Jane
    1000
    Welby, Marcus
    sssttt
    Wolly, Polly
    12/4/2013
    100
    zzz
    SA
    Alcohol
    1000
    Welby, Marcus
    sssttt
    Wolly, Polly
    12/4/2013
    100
    ddd
    SA
    LSD
    1000
    Welby, Marcus
    sssttt
    Wolly, Polly
    12/4/2013
    100
    Alcohol Dependence
    1000
    Welby, Marcus
    vvvvwww
    Jazz, Razz
    12/14/2013
    210
    ggg
    SA
    Smoker
    1000
    Welby, Marcus
    vvvvwww
    Jazz, Razz
    12/14/2013
    210
    Cigarettes
    A patient is assigned an ednum. There are two different menus for staff to enter
    diagnoses. Each menu stores the entries in a different table. The two tables are substance and pdiagnose. A patient’s diagnosis for a substance abuse can be entered in one table and not the other. 
    The number of entries for different substances for each patient can vary between the two tables. John Doe might be entered for alcohol and caffeine abuse in the pdiagnosis table and entered only for caffeine abuse in the substance table. They are only
    linked by the ednum which has nothing to do with the diagnosis/substance. The substance entered in one table is not linked to the substance entered in the other. A query will not put an entry for alcohol from the pdiagnosis table on the same row as an alcohol
    entry from the substance table except by chance. That is the reason for the way the query is written.
    The query accepts parameters for a Dr ID and a start and end date. It takes about 7 to 15 seconds to run. Hard coding the dates cuts it down to about a second.
    I might be able to select directly from the union all query instead of having it separate. But then I’m not sure about the order by clauses using aliases.
    Is there a way to rewrite the query to speed it up?
    I did not design the tables or come up with the process of entering diagnoses. It can’t be changed at this time.
    Please let me know if you notice any inconsistencies between the DDLs, data, and output. I did a lot of editing.
    Thanks for any suggestions.
    with cte_dxcat (Dr_ID, Doctor, Patient_No,Last_Name,
    First_Name, Adatetime,Ednum,
    dx_code,diagnosis_category_code,dx_description,substance,
    DateofBirth) as
    (Select distinct t.Dr_ID, t.Doctor, TP.Patient_No,TP.Last_Name,
    TP.First_Name, TP.Adatetime as 'Date of Service',TP.Ednum,
    DXCAT.dx_code,DXCAT.diagnosis_category_code,DXCAT.dx_description,
    null as 'substance',BG.DateofBirth
    From TypePatient TP
    inner join treat t on TP.ednum = t.Ednum
    inner join background BG on BG.Patient_No = TP.Patient_No
    inner join pdiagnose PD on TP.Ednum = PD.Ednum
    inner join Live_Knowledge.dbo.VA_DX_CAT_MAPPING DXCAT on DXCAT.dx_code = PD.DSMNo
    Where (TP.Adatetime >= convert(varchar(10), :ST, 121)+ ' 00:00:00.000'
    and TP.Adatetime <= convert(varchar(10), :SP, 121)+ ' 23:59:59.000')
    and DXCAT.diagnosis_category_code = 'SA'
    and t.Dr_ID =:DBLookupComboBox2
    cte_substance (Dr_ID, Doctor, Patient_No,Last_Name,
    First_Name,Adatetime, Ednum,
    dx_code,diagnosis_category_code,dx_description,Substance,DateofBirth) as
    (Select distinct t.Dr_ID, t.Doctor, TP.Patient_No,TP.Last_Name,
    TP.First_Name, TP.Adatetime as 'Date of Service', TP.Ednum,
    null as 'dx_code',null as 'diagnosis_category_code',null as 'dx_description',s.Substance, BG.DateofBirth
    From TypePatient TP
    inner join treat t on TP.ednum = t.Ednum
    inner join background BG on BG.Patient_No = TP.Patient_No
    inner join pdiagnose PD on TP.Ednum = PD.Ednum
    inner join substance s on TP.Ednum = s.Ednum
    Where (TP.Adatetime >= convert(varchar(10), '12/1/2013', 121)+ ' 00:00:00.000'
    and TP.Adatetime <= convert(varchar(10), '12/31/2013', 121)+ ' 23:59:59.000')
    and t.Dr_ID =:DBLookupComboBox2
    cte_all (Dr_ID, Doctor, Patient_No,Last_Name,
    First_Name,Adatetime, Ednum,
    dx_code,diagnosis_category_code,dx_description,Substance,DateofBirth) as
    (select cte_dxcat.Dr_ID as 'Staff ID', cte_dxcat.Doctor as 'Doctor',
    cte_dxcat.Patient_No as 'Patient_No',
    cte_dxcat.Last_Name as 'Last',cte_dxcat.First_Name as 'First',
    cte_dxcat.Adatetime as 'Date of Service',cte_dxcat.Ednum as 'Ednum',
    cte_dxcat.dx_code as 'DX Code',cte_dxcat.diagnosis_category_code as 'DX Category Code',
    cte_dxcat.dx_description as 'DX Description',
    cte_dxcat.substance as 'Substance',cte_dxcat.DateofBirth as 'DOB'
    from cte_dxcat
    union all
    select cte_substance.Dr_ID as 'Staff ID', cte_substance.Doctor as 'Doctor',
    cte_substance.Patient_No as 'Patient_No',
    cte_substance.Last_Name as 'Last',cte_substance.First_Name as 'First',
    cte_substance.Adatetime as 'Date of Service',cte_substance.Ednum as 'Ednum',
    cte_substance.dx_code as 'DX Code',cte_substance.diagnosis_category_code as 'DX Category Code',
    cte_substance.dx_description as 'DX Description',
    cte_substance.substance as 'Substance',cte_substance.DateofBirth as 'DOB'
    from cte_substance)
    select cte_all.Dr_ID as 'Staff ID', cte_all.Doctor as 'Doctor',
    cte_all.Patient_No as 'Patient_No',
    (cte_all.Last_Name + ', '+ cte_all.First_Name) as 'Client Name',
    cte_all.Adatetime as 'Date of Service',cte_all.Ednum as 'Ednum',
    cte_all.dx_code as 'DX Code',cte_all.diagnosis_category_code as 'DX Category Code',
    cte_all.dx_description as 'DX Description',
    cte_all.substance as 'Substance',
    CONVERT(char(10), cte_all.DateofBirth,101) as 'DOB'
    from cte_all
    order by cte_all.Patient_No,cte_all.Adatetime

    Please post real DDL instead of your invented non-language, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions
    and formatting rules. Your rude, non-SQL narrative is so far away from standards I cannot even use you as a bad example in book. 
    Temporal data should use ISO-8601 formats (we have to re-type the dialect you used!). Code should be in Standard SQL as much as possible and not local dialecT. 
    This is minimal polite behavior on SQL forums. You posted a total mess! Do you really have patients without names?? You really use a zero to fifty characters for a patient_nbr??? Give me an example. That is insane! 
    Your disaster has more NULLs than entire major corporate systems. Since you cannot change it, can you quit? I am serious. I have been employed in IT since 1965, and can see a meltdown.
    I looked at this and I am  not even going to try to help you; it is not worth it. I am sorry for you; you are in an environment where you cannot learn to do any right. 
    But you are still responsible for the rudeness of not posting DDL. 
    --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

  • Sql query using union

    hi
    i need the query to fetch the data ...
    i have two table
    1. plan
    2. voidplan
    each table has id uniquely, and each table has rep_id but it is not unique.
    i retrieved the data from both table using union. now i need the data for the rep who is in both table. i want to check union by id, and i need to retrieve the reps who is in both tables.
    my code is
    select "PLAN"."ID" as "ID",
         "PLAN"."REP_ID" as "REP_ID",
         "PLAN"."REGION" as "REGION",
         "PLAN"."LOB" as "LOB",
         "PLAN"."PLAN_HIERARCHY_CHANGE" as "PLAN_HIERARCHY_CHANGE"
    from     "PLAN" "PLAN" ,"VOIDPLAN" "VOIDPLAN" where "PLAN"."REP_ID" IN (SELECT REP_ID FROM VOIDPLAN)
    UNION
    SELECT "VOIDPLAN"."ID" as "ID",
         "VOIDPLAN"."REP_ID" as "REP_ID",
         "VOIDPLAN"."REGION" as "REGION",
         "VOIDPLAN"."LOB" as "LOB",
         "VOIDPLAN"."PLAN_HIERARCHY_CHANGE" as "PLAN_HIERARCHY_CHANGE"
    from     "VOIDPLAN" "VOIDPLAN"
    THIS QUERY GIVES ALL UNION RESULT, NUT IT DOES'T FILTER THE REP_ID, IT SHOWS ALL THE REP_ID, I NEED THE REPS WHO IS IN BOTH TABLES
    CAN ANYONE PLEASE TELL ME THE SOLUTION
    regards
    vally.s

    SQL> create table plan
      2  as
      3  select 1 id, 1111 rep_id, 'vally' rep_name from dual union all
      4  select 2, 2222, 'kavi' from dual union all
      5  select 3, 3333, 'shyam' from dual
      6  /
    Tabel is aangemaakt.
    SQL> create table voidplan
      2  as
      3  select 5 id, 1111 rep_id, 'vally' rep_name from dual union all
      4  select 6, 2222, 'kavi' from dual
      5  /
    Tabel is aangemaakt.
    SQL> select case x when 1 then p.id else v.id end id
      2       , p.rep_id
      3       , p.rep_name
      4    from plan p
      5       , voidplan v
      6       , (select 1 x from dual union select 2 from dual) x
      7   where p.rep_id = v.rep_id
      8   order by 1
      9  /
       ID REP_ID REP_N
        1   1111 vally
        2   2222 kavi
        5   1111 vally
        6   2222 kavi
    4 rijen zijn geselecteerd.Regards,
    Rob.

  • Where to place ORDER BY clause when a query includes UNION

    I have a query that has UNION in it. could you please tell me where to place the ORDER BY clause. Because it's throwing an error if i place the ORDER BY clause at the end

    Because you are using the UNION set operator, you need to either specifically list your columns or use positional notation.
    Without a set operator we can order by the column name without specifically listing it:
    SQL> select * from dual
      2  order by dummy;
    D
    X
    1 row selected.This doesn't work once you introduce a set operator:
    SQL> ed
    Wrote file afiedt.buf
      1  select * from dual union all
      2  select * from dual union all
      3  select * from dual
      4* order by dummy
    SQL> /
    order by dummy
    ERROR at line 4:
    ORA-00904: "DUMMY": invalid identifierSo you need to either use positional notation:
    SQL> ed
    Wrote file afiedt.buf
      1  select * from dual union all
      2  select * from dual union all
      3  select * from dual
      4* order by 1
    SQL> /
    D
    X
    X
    X
    3 rows selected.Or, specifically list or alias the columns you are projecting:
    SQL> ed
    Wrote file afiedt.buf
      1  select dummy from dual union all
      2  select dummy from dual union all
      3  select dummy from dual
      4* order by dummy
    SQL> /
    D
    X
    X
    X
    3 rows selected.
    SQL> ed
    Wrote file afiedt.buf
      1  select dummy as d from dual union all
      2  select dummy as d from dual union all
      3  select dummy as d from dual
      4* order by d
    SQL> /
    D
    X
    X
    X
    3 rows selected.cheers,
    Anthony

  • ABAP Query - Differences in generated code after upgrade

    Hi all,
    We have upgraded to ECC 6. from 4.6C. We are experiencing differences between the behaviour of some queries in different systems. This can be as subtle as some of the output parameters not appearing on the selection screen (such as the options within the output format box, i.e. ABAP list, ABC analysis etc), to actual syntax errors in queries where there is no difference between the infosets and queries in the two systems.
    A pattern I have noticed is that there are big differences in the generated code behind the query transaction.
    In production, where we have the problems, the generated code contains a lot of include programs starting with /1BCDWB/, I am not sure what these are, but the generated code in the systems that work don't have these. I am not sure what is triggering the code to generate differently, but I think if I can find out then it will point me in the right direction.
    any help appreciated.
    Stephen

    Stephen,
    I have noticed the queries are generated with two different formats. One is very compact and has multiple different includes each for data, selection screen, various selection screen events, etc. Other is a single big non-modular program.
    We have also noticed generated program template gets reset to the non-modular kind, if additional code is added in the selection-screen code section of the infoset. They do not return to the original even after you undo the changes.

  • Query with UNION option

    Hi ,
    I have one partition table.The partitions are created datewise.Now when i have to fire select query on that talble i am firing below querry
    Select count(1) from table A where createdate between ('01-JAN-2012 00:00:00','DD-MON-YYYY HH24:MI:SS') AND ('01-JAN-2012 23:59:59','DD-MON-YYYY HH24:MI:SS')
    Above query will scan 1 day partition.
    now if i want to fetch records from whole month ,it will scan 31 partition one by one.
    Select count(1) from table A where createdate between ('01-JAN-2012 00:00:00','DD-MON-YYYY HH24:MI:SS') AND ('31-JAN-2012 23:59:59','DD-MON-YYYY HH24:MI:SS')
    Now if i change the query by writing another way which will scan partition parallely.
    Select count(1) from table A where createdate between ('01-JAN-2012 00:00:00','DD-MON-YYYY HH24:MI:SS') AND ('01-JAN-2012 23:59:59','DD-MON-YYYY HH24:MI:SS')
    union
    Select count(1) from table A where createdate between ('02-JAN-2012 00:00:00','DD-MON-YYYY HH24:MI:SS') AND ('02-JAN-2012 23:59:59','DD-MON-YYYY HH24:MI:SS')
    union
    Select count(1) from table A where createdate between ('03-JAN-2012 00:00:00','DD-MON-YYYY HH24:MI:SS') AND ('03-JAN-2012 23:59:59','DD-MON-YYYY HH24:MI:SS')
    union
    till
    Select count(1) from table A where createdate between ('31-JAN-2012 00:00:00','DD-MON-YYYY HH24:MI:SS') AND ('31-JAN-2012 23:59:59','DD-MON-YYYY HH24:MI:SS')
    Is it possible that i can make query by passing different month in above union query .
    Month can be dynamic, and above select can be take the values by passing the month.
    kindly guide me
    =======

    I hear you. But can you demonstrate, instead of just telling?
    Else, I'll be guessing, that you are just guessing. And I am inclined to guess that your guess is wrong.
    But, I could be guessing wrong, of course. (And week-ends I am not online to test it myself)
    Start by showing the table, ddl. Is it parallel, noparallel? - And then show the plans for both queries.
    And how did you come to that conclusion of "one by one" vs "in parallel"?
    Regards
    Peter

  • Why do i get ORA-03113 when doing a spatial query against union all view?

    Hi, i created the following view
    CREATE OR REPLACE FORCE VIEW cola_markets_v
    AS
      (SELECT mkt_id, NAME, shape shape_a, NULL shape_b, NULL shape_c,
              NULL shape_d
         FROM COLA_MARKETS
        WHERE NAME = 'cola_a')
       UNION ALL
      (SELECT mkt_id, NAME, NULL shape_a, shape shape_b, NULL shape_c,
              NULL shape_d
         FROM COLA_MARKETS
        WHERE NAME = 'cola_b')
       UNION ALL
      (SELECT mkt_id, NAME, NULL shape_a, NULL shape_b, shape shape_c,
              NULL shape_d
         FROM COLA_MARKETS
        WHERE NAME = 'cola_c')
       UNION ALL
      (SELECT mkt_id, NAME, NULL shape_a, NULL shape_b, NULL shape_c,
              shape shape_d
         FROM COLA_MARKETS
        WHERE NAME = 'cola_d');added the necessary entries in USER_SDO_GEOM_METADATA and created a spatial index on COLA_MARKETS (SHAPE). However, when i do a spatial query against this view, i get ORA-03113. A spatial query against the base table works fine. Any ideas why this happens? (This is Oracle 10.2.0.3.0)
    Thanks in advance, Markus
    PS: This is my spatial query
    SELECT *
      FROM cola_markets_v t
    WHERE sdo_filter (t.shape_a,
                             SDO_GEOMETRY (2003,
                                           NULL,
                                           NULL,
                                           sdo_elem_info_array (1, 1003, 3),
                                           sdo_ordinate_array (1, 1, 2, 2)
                             'querytype=window'
                            ) = 'TRUE';

    Thank you for your reply. I have tried it with 11.1.0.6.0 today and it works. This might be an issue with 10.2.0.3.0.

  • Generic Extraction - query view and infoset query difference

    Hi Guys,
    I want to know the Generic datasource difference between Extraction from view and Extraction from Query .I have read some threads and documents, still i am not getting the exact difference.
    My understanding :
    Views: combination of tables to view the end result , we use views.
    Infoset query also with help of SQ01, 02, 03  : we combine tables to see the result.
    both use primary key to select the data.
    Please help me.
    Thanks ,
    Nithi.

    Hi Nithi ,
    When we build the datasource on the View
    View is basically a table in which you can take data from many table combniation  .
    in view you can specify the table join condtion and selection condtion
    View data gets updated as the data in the source table gets updated
    When we build the datasource on the Infoset
    Data source str gets filled from the infoset query .you need to use SQ01 and Sq02 transaction for this
    in infoset you can define the tables from which you want to read the date .There is also facilty to write ABAP code which will process the data and fill the the data source str using infoset query
    infoset query read the data from infoset and transfer to data structure
    Thanks
    Rajendra

Maybe you are looking for

  • How can I create mirror margins in Pages 5.2?

    Hello! Maybe someone can help me. I need to have mirror margins but I think Pages 5.2 hasn't got this option... Any ideas?

  • Driver for Intel Corp. Intel(R) PRO/Wireless 2200BG in Solaris 10 x86

    Hi Folks, I bought a Laptop with the NIC mentioned in the Subject. After installing Solaris 10 x86 I'd like to install a driver for this card. Can someone of you tell me how, or point me to a good documentation? Cheers Sven

  • Copy Command Doesnt work in Premiere CS6!

    When you set your in and out points on your timeline, and then do the copy command, it will not paste your in and out to your selected timeline! I did some research and found a workaround: Set your in/out Lift Undo (cnrtl Z) Copy (cntrl C) Paste to s

  • How do I create a SENT On My Mac mailbox?

    I've just migrated our Macs from Microsoft Outlook for Mac to Apple Mail, iCal and Address Book and activate iCloud. I don't know how I did it, but under my MAILBOXES in the "Sent" mailbox there are two sub-mailboxes: "iCloud" and "On My Mac" Both th

  • Printing pdf files from Finder - Error (AppleGraphicsPolicyClient)

    If I try to print from finder a PDF file using the Print command in the Finder menu Preview opens but give the following error: The document "xxxxx” could not be opened for printing. Console details: Preview(1258) deny iokit-open AppleGraphicsPolicyC