Need sql query to remove duplicates using UNION ALL clause

Hi,
I have a sql query which has UNION clause.But the UNION clause is causing some performance issues.
To overcome that I have used UNION ALL to improve performance but its returning duplicates.
Kindly anyone send a sample SQL query where my primary objective is used to use UNION ALL clause and to consider unique rows (elimating duplicate
ones)
Any help will be needful for me
Thanks and Regards

why not UNION? :(
another way also use MINUS
SQL>
SQL> with t as
  2  (
  3  select 1 if from dual union all
  4  select 2 if from dual union all
  5  select 1 if from dual union all
  6  select 3 if from dual union all
  7  select 3 if from dual
  8  )
  9  ,t2 as
10  (
11  select 1 if from dual union all
12  select 2 if from dual union all
13  select 3 if from dual union all
14  select 4 if from dual union all
15  select 5 if from dual
16  )
17  (select if from t
18  union all
19  select if from t2)
20  /
        IF
         1
         2
         1
         3
         3
         1
         2
         3
         4
         5
10 rows selected
SQL> so
SQL>
SQL> with t as
  2  (
  3  select 1 if from dual union all
  4  select 2 if from dual union all
  5  select 1 if from dual union all
  6  select 3 if from dual union all
  7  select 3 if from dual
  8  )
  9  ,t2 as
10  (
11  select 1 if from dual union all
12  select 2 if from dual union all
13  select 3 if from dual union all
14  select 4 if from dual union all
15  select 5 if from dual
16  )
17  (select if from t
18  union all
19  select if from t2)
20  minus
21  select -99 from dual
22  /
        IF
         1
         2
         3
         4
         5
SQL>

Similar Messages

  • Trying to create table using Union All Clause with multiple Select stmts

    The purpose of the query is to get the Substring from the value for eg.
    if the value is *2 ASA* then it should come as ASA
    where as if the value is *1.5 TST* the it sholud come as TST like wise for others too.
    I am trying to execute the below written SQL stmt but getting error as:
    *"ORA-00998 must name this expression with the column alias 00998.00000 - Must name this expression with the column alias"*
    CREATE TABLE TEST_CARE AS
    SELECT row_id, old_care_lvl,SUBSTR(old_care_lvl,3), len FROM test_care_lvl
    WHERE LENGTH(old_care_lvl) =5
    UNION ALL
    SELECT row_id, old_care_lvl,SUBSTR(old_care_lvl,3), len FROM test_care_lvl
    WHERE LENGTH(old_care_lvl) =7
    UNION ALL
    SELECT row_id, old_care_lvl,SUBSTR(old_care_lvl,3), len FROM test_care_lvl
    WHERE LENGTH(old_care_lvl) =14
    UNION ALL
    SELECT row_id, old_care_lvl,SUBSTR(old_care_lvl,3),LEN FROM test_care_lvl
    WHERE LENGTH(old_care_lvl) =7 AND old_care_lvl ='Regular'
    I want to create the table using the above given multiple select using the Union ALL clause but when trying to create run the query getting error as "ORA-00998 must name this expression with the column alias 00998.00000 - Must name this expression with the column alias"
    Please guide me how to approach to resolve this problem.
    Thanks in advance.

    When you create a table using a SELECT statement the column names are derived from the SELECT list.
    Your problem is that one of your columns is an expression that does not work as a column name SUBSTR(old_care_lvl,3)What you need to do is alias this expression and the CREATE will pick up the alias as the column name, like this:
    CREATE TABLE TEST_CARE AS
    SELECT row_id, old_care_lvl,SUBSTR(old_care_lvl,3) column3, len FROM test_care_lvl
    WHERE LENGTH(old_care_lvl) =5
    UNION ALL
    SELECT row_id, old_care_lvl,SUBSTR(old_care_lvl,3), len FROM test_care_lvl
    WHERE LENGTH(old_care_lvl) =7
    UNION ALL
    SELECT row_id, old_care_lvl,SUBSTR(old_care_lvl,3), len FROM test_care_lvl
    WHERE LENGTH(old_care_lvl) =14
    UNION ALL
    SELECT row_id, old_care_lvl,SUBSTR(old_care_lvl,3),LEN FROM test_care_lvl
    WHERE LENGTH(old_care_lvl) =7 AND old_care_lvl ='Regular'
    );You may not like the name "column3" so use something appropriate.

  • Need Sql Query that Suppress the repeating rows.

    Hi Sir,
    I have below data set.
    DeptID  Sum(SAL) Avg(Sal)
      10      1300      1300
      10      2450      1300
      10      5000      1300
      20      800        800
      20      1100      800
      20      2975      800
      20      3000      800
      30      800        800
      30      1100      800
      30      2975      800
      40      3000      800
      40      4000      900
    I Need  SQL query that can remove the duplicate or suppress.Just like below data set.
    Output:
    DeptID  Sum(SAL) Avg(Sal)
      10      1300      1300
                2450      1300
                5000      1300
      20       800        800
                1100      800
                2975      800
                3000      800
                800        800
      30      1100      800
                2975      800
      40      3000      800
               4000      900
    Could you please help me on this..

    Your requiremnt is more of a reporting request which should not be handled in SQL. For example in SQL Plus you can use the BREAK command
    SQL> break on deptno
    SQL> select deptno, ename from emp order by deptno;
        DEPTNO ENAME
            10 KING
               CLARK
            20 JONES
               SCOTT
               SMITH
               ADAMS
            30 TURNER
               MARTIN
               WARD
               ALLEN
               BLAKE
    11 rows selected.
    SQL>
    But if you still wish to do it in SQL you can use ROW_NUMBER analytic function and achieve it like this
    select decode(rno, 1, deptno) deptno
         , ename
      from (
              select row_number() over(partition by deptno order by ename) rno
                   , deptno
                   , ename
                from emp

  • Cannot export query output when using UNION ALL

    Hi
    I can run a query in SQL Developer 1.5.5 and if it's a SELECT statement it works fine, but if I output the result of several SELECT statements using UNION ALL after some 10,000 records the SQL Developer crashes and it generates a file whose size is 0 kb
    Is there a workaround for this??
    Thanks and Regards!
    Isaac

    Should be fixed in the upcoming 2.1... you can try the RC1 also...
    Regards,
    K.

  • Need sql query to find out Joins attached with folders in Discoverer

    Hi,
    Can anyone let me know the sql query which can be used to identify the joins which are attached to the folders.
    Actually we have to identify all the joins conditions from folders those are migrated from one instance to others.
    Thanks
    abhishek

    I recommend that you implement the admin EUL supplied by oracle, you can get there a lot of repository information (metalink note: 556932.1).
    Try to use this (maybe you will need some pkg's):
    SELECT
    DECODE(KEYS.FK_MANDATORY,
    1,
    'Always exist in master folder',
    'Might not exist in master folder') "Detail Item values",
    EUL10G_US.EUL5_GET_JOIN(EXP.EXP_ID, 'N') "Join Master --> Detail",
    KEYS.KEY_DESCRIPTION JOIN_DESCRIPTION,
    KEYS.KEY_DEVELOPER_KEY JOIN_IDENTIFIER,
    KEYS.KEY_NAME JOIN_NAME,
    DECODE(SUBSTR(KEYS.KEY_NAME, 1, 19),
    'AUTO_GENERATED_NAME',
    'Yes',
    'No') "AutoGen",
    DECODE(DECODE(SUBSTR(KEYS.KEY_NAME, 1, 19),
    'AUTO_GENERATED_NAME',
    'Yes',
    'No') ,
    'Yes',
    EUL10G_US.EUL5_GET_JOIN(EXP.EXP_ID),
    KEYS.KEY_NAME) "Actual Join Name",
    KEYS.KEY_UPDATED_DATE JOIN_LAST_UPDATE,
    DECODE(KEYS.FK_ONE_TO_ONE, 1, 'One to one join', NULL) "One to One join",
    DECODE(KEYS.FK_MSTR_NO_DETAIL,
    1,
    'Outer join on detail' || CHR(10),
    NULL) "Outer Join on Detail",
    DECODE(KEYS.FK_DTL_NO_MASTER,
    1,
    'Outer join on master' || CHR(10),
    NULL) "Outer Join on Master",
    DECODE(KEYS.FK_MSTR_NO_DETAIL,
    1,
    'Outer join on detail' || CHR(10),
    NULL) || DECODE(KEYS.FK_DTL_NO_MASTER,
    1,
    'Outer join on master' || CHR(10),
    NULL) ||
    DECODE(KEYS.FK_ONE_TO_ONE, 1, 'One to one join', NULL) "Optional Join Configurations",
    OBJ.OBJ_NAME "MASTER_FOLDER",
    OBJ_DETAIL.OBJ_NAME "DETAIL_FOLDER"
    FROM EUL10G_US.EUL5_OBJS OBJ,
    EUL10G_US.EUL5_EXPRESSIONS EXP,
    EUL10G_US.EUL5_KEY_CONS KEYS,
    EUL10G_US.EUL5_OBJS OBJ_DETAIL
    WHERE ((KEYS.KEY_ID = EXP.JP_KEY_ID) AND
    (OBJ.OBJ_ID = KEYS.FK_OBJ_ID_REMOTE) AND
    (OBJ_DETAIL.OBJ_ID = keys.KEY_OBJ_ID));

  • Need sql query to find out Joins attached with folders

    Hi,
    Can anyone let me know the sql query which can be used to identify the joins which are attached to the folders.
    We dont want to see those from front end(disc admin).
    Thanks
    abhishek

    abhishek - This is the Application Express forum. I have no idea what you are asking but it may need to be directed to a different forum.
    Scott

  • Need sql query to import from excel sheet

    Hey , i need sql query to import from excel sheet.
    i work in a company where i need to daily update the data from excel sheet.
    if i get a shortcut method i ill be very thank full to you guys to reduce my work upto 10 %.

    any query which can inert from excel file?
    Sort of. Certainly not anything as simple as what you seem to hope for. Check out this very good PHP class:
    PHPExcel - Home

  • SQl query to remove all dbms_output statement

    Hi
    Can u please tell me Single SQl query to remove all dbms_output statement from package and procedure
    Umesh

    >
    Can u please tell me Single SQl query to remove all
    dbms_output statement from package and procedure
    If you are comfortable with scripting languages like Perl, Python, Ruby etc., then removing lines having the dbms_output statements from your files should be a trivial matter.
    pratz

  • Performance using UNION ALL

    Hello
    i have 2 schemas S1 and S2 containing complex relational tables. The tables in each schema are related to each other via foreign key relationships. i made views for feature tables in both the schemas , querying column values from their related tables.
    the data structure in both the schemas are exactly the same. Dut to management reasons we have to split them in 2 schemas. S1 contain data for region A and S2 contains data from region B. Now the client wants to see a combined data from region A & B.
    we are planning to create another schema S3 and make views combining views from S1 and S2 in both schemas (V1 in S1 + V1 in S2) using UNION ALL.
    Does UNION ALL will make use of the indexes we already built for parent tables in S1 and S2? Will there be a performance degradation using this approach? What can be the best approach? Our client needs to see real time data....
    regards
    sam

    Since union does an extra sort it has a performance difference compared to union all.
    SQL> select user from dual union select user from dual ;
    USER
    HR
    SQL> select user from dual union all select user from dual ;
    USER
    HR
    HRİf there is up to date and appropriate object statistics Oracle's Cost Based Optimizer will choose best access path, join method and join order depending on your query. Only exceptions are hints, outlines and sql profiles since they stabilize the execution plan.
    For further commenting please post your oracle version, query's test results and its statistics taken from sql*plus timing and autotrace options - http://www.bhatipoglu.com/entry/17/oracle-performance-analysis-tracing-and-performance-evaluation

  • Drill down problem when using union all combination

    Hi All,
    I have a simple report with a drill down. The report has three columns Region, Sales, Flag... which will drill down to detail level of sales. The Flag column has Y, N values and we added 'All' Value in flag so that the user can select Y, N and All from the table prompt in the report . We have used union all in the report using combination to add the ' All ' Value in the flag. The problem is that now the main report is not passing the Flag values to the detail report. Flag is prompted in the filter in detail report.
    If I remove the 'All' value from Analysis with only Y N selection criteria the drill down works.
    Is there any work around? I have to use table prompt and All value selection in flag for drill down.
    Thanks,
    Virat

    The problem is without union all when doing combination of analysis drill down works, when I use combination drill down does not work because it does not pass the parameters for flag . I have used union all to add All value in flag.

  • Select query-using Union All display duplicate records.

    Hello All Gurus-
    I am using Oracle 9.i
    When i use the following query to fetch the records based on BUILDNUMBERNAME and ASSIGNED_BUILD then i am getting duplicate records -
    select T1.ID FROM Defect T1,statedef T2,repoproject T3
    WHERE T1.STATE=T2.ID AND T1.repoproject = T3.dbid AND T3.name Like 'ABC' AND T1. ASSIGNED_BUILD like '1.4.5.6'
    Union All
    select T1.ID FROM Defect T1,statedef T2,repoproject T3
    WHERE T1.STATE=T2.ID AND T1.repoproject = T3.dbid AND T3.name Like 'ABC' AND T1.BUILDNUMBERNAME like '1.4.5.6'
    How can i use the order by on T1.ID ? When i use the Order by T1.ID then it throws some error.
    Kindly help me in this :(
    Thanks in advance.

    Sorry for not providing all of the details -
    I am using Toad tool to run the query.
    1-When i use the following query -
    Select T1.ID FROM Defect T1,statedef T2,repoproject T3
    WHERE T1.STATE=T2.ID AND T1.repoproject = T3.dbid AND T3.name Like 'ABC' AND T1. ASSIGNED_BUILD like '1.4.5.6' order by T1.ID
    Union All
    select T1.ID FROM Defect T1,statedef T2,repoproject T3
    WHERE T1.STATE=T2.ID AND T1.repoproject = T3.dbid AND T3.name Like 'ABC' AND T1.BUILDNUMBERNAME like '1.4.5.6' order by T1.ID
    ORA-00933: SQL command not properly ended.
    2-If i am not using the T1.ID and run the following query
    Select T1.ID FROM Defect T1,statedef T2,repoproject T3
    WHERE T1.STATE=T2.ID AND T1.repoproject = T3.dbid AND T3.name Like 'ABC' AND T1. ASSIGNED_BUILD like '1.4.5.6'
    Union All
    select T1.ID FROM Defect T1,statedef T2,repoproject T3
    WHERE T1.STATE=T2.ID AND T1.repoproject = T3.dbid AND T3.name Like 'ABC' AND T1.BUILDNUMBERNAME like '1.4.5.6'
    Then it is running fine but it is displaying the duplicate values like -
    00089646
    00087780
    00089148
    00090118
    00090410
    00088503
    00080985
    00084526
    00087108
    00087109
    00087117
    00088778
    00086714
    00079518
    00087780
    00089148
    00090392
    00090393
    00090395
    00090398
    00090401
    00090402
    00090403
    00090406
    00090408
    00088503
    00080985
    00084526
    00087108
    00087109
    00087117
    00088778
    00086714
    00079518

  • Query takes long when using UNION

    Hi ,
    I habe a query as follows;
    SELECT
                        '9999' site_id,
                        m.ghi_prov_num provnum,
                           SUBSTR (l.seq_num, 1, 3)provloc,
                        t.dea_number dea,
                            t.license_number statelicensenumber ,
                            n.npi_num npi,
                            m.prefix prefixname,
                            m.lastname lastname,
                            m.firstname firstname,
                            t.middle_name middleinitial,
                            m.suffix suffixname,
                            null clinicname,
                            l.street1 addressline1,
                            l.street2 addressline2,
                            l.city city,
                            l.state state,
                            l.zip5 zip,
                            l.phone phoneprimary,
                            null ext,
                            null fax,
                            null email,
                            null alt_phone,
                            null alt_phone_ext
                     FROM provider m, LOCATION l, npi n,TEMP_VITAL_CACTUS t,test_provider_pin pin
                      WHERE m.ghi_prov_num=l.ghi_prov_num
                          and m.ghi_prov_num=n.ghi_prov_num(+)
                          and m.ghi_prov_num=t.ghi_prov_num(+)
                          and m.tax_id=pin.tax_id
         UNION
          SELECT   
                        '9999', m.ghi_prov_num ,
                            m.location provloc,
                           null  ,
                           null  ,
                            n.npi_num  ,
                            null ,
                            m.lastname ,
                            m.firstname  ,
                            null,
                            null  ,
                            null  ,
                            m.street1  ,
                            m.street2  ,
                            m.city ,
                            m.state  ,
                            m.zip5 ,
                            m.phone  ,
                            null  ,
                            null  ,
                            null  ,
                            null  ,
                            null
                           FROM dental_provider m, npi n,test_provider_pin pin
                       WHERE m.ghi_prov_num=n.tax_id(+)
                           and m.location=n.location(+)
                            and pin.tax_id=m.ghi_prov_num;The query takes for ever;
    But Individual query takes less than a sec to execute.Is there any way can i rewrite the query?
    Please help
    Hena.

    user11253970 wrote:
    But Individual query takes less than a sec to execute.Is there any way can i rewrite the query?Have a feeling you are using Toad/SQL Navigator or similar tool which returns data one screen at a time. If so, then it does not "takes less than a sec to execute" but rather to fetch first screen of rows. When you use UNION Oracle has to return distinct rows from both queries. Therefore it must fetch not just first screen but all rows. To verify, issue first query and in yiour GUI tool click on get last screen. Then you'll know how long whole select takes. Do the same for second query. Also, do you need distinct rows or akll rows? IF all rows, change UNION to UNION ALL.
    SY.

  • Select extra row without using UNION ALL in pl/sql

    Hi,
    Can anyone tell me how to select extra row without using UNION or UNION ALL in pl/sql. Actually I want to have my o/p of query as partitioned by designation and ordered by salary and than one extra row which will contain the highest salary in a particular salary. My table has first_name,emp_id,designation and salary column. And I wnt the o/p as.
    Mohinish,12212,SI,46000
    Ram,11212,SSI,47000
    Shyam,12133,SI,48000
    Rick,9898,SI,46000
    Rocky,12312,SSI,56000
    Sariq,23948,SI,43000
    Suman,12789,HR,49000
    Sampy,12780,SI,46000
    Parna,11111,HR,50000
    Now the o/p should be.
    Mohinish,12212,SI,46000
    Rick,9898,SI,46000
    Sariq,23948,SI,43000
    Shyam,12133,SI,48000
    Shyam,12133,SI,48000
    Ram,11212,SSI,47000
    Rocky,12312,SSI,56000
    Rocky,12312,SSI,56000
    Suman,12789,HR,49000
    Parna,11111,HR,50000
    Parna,11111,HR,50000
    Thanks in Advance

    You don't have to do a UNION or UNION ALL in PL/SQL but you would need to in SQL to get the desired output:
    with data_recs
    as (select 'Mohinish' first_name,12212 emp_id,'SI' designation,46000 salary from dual union
         select 'Ram',11212,'SSI',47000 from dual union
         select 'Shyam',12133,'SI',48000 from dual union
         select 'Rick',9898,'SI',46000 from dual union
         select 'Rocky',12312,'SSI',56000 from dual union
         select 'Sariq',23948,'SI',43000 from dual union
         select 'Suman',12789,'HR',49000 from dual union
         select 'Sampy',12780,'SI',46000 from dual union
         select 'Parna',11111,'HR',50000 from dual)
    select first_name, emp_id, designation, salary from data_recs union all
    select s.first_name, s.emp_id, s.designation, s.salary
      from (select first_name,
                   emp_id,
                   designation,
                   salary,
                   row_number() over (partition by designation order by salary desc) high_salary
              from data_recs
             order by designation, salary) s
    where s.high_salary = 1
    order by designation, salary;
    FIRST_NAME  EMP_ID DESIGNATION   SALARY
    Suman        12789 HR             49000
    Parna        11111 HR             50000
    Parna        11111 HR             50000
    Sariq        23948 SI             43000
    Rick          9898 SI             46000
    Mohinish     12212 SI             46000
    Sampy        12780 SI             46000
    Shyam        12133 SI             48000
    Shyam        12133 SI             48000
    Ram          11212 SSI            47000
    Rocky        12312 SSI            56000
    Rocky        12312 SSI            56000

  • Need sql query for like operation.

    Hi All,
    i have table like name column and contain the data like
    ibm 100
    ibm 200
    ibm 300
    a2b
    a
    b
    c
    like this ....
    but sql query need search using like or any regular expression---
    select * from table where name like (ibm 200 and ibm 300).
    and i don't want use like this select * from table where name like' ibm 200' or name like 'ibm 300').
    can you please any body help to correct the above query...
    Edited by: anbarasan on Oct 16, 2011 10:02 PM

    WITH t AS
         (SELECT 'ibm 100' NAME
            FROM DUAL
          UNION ALL
          SELECT 'ibm 200' NAME
            FROM DUAL
          UNION ALL
          SELECT 'ibm 300' NAME
            FROM DUAL
          UNION ALL
          SELECT 'a2b' NAME
            FROM DUAL)
    SELECT *from t where    REGEXP_LIKE (name, 'ibm')
    and REGEXP_LIKE (name, '100|200')

  • SQL QUERY TO REMOVE ONE OF THE THE RESULT SET

    Hello Everyone,
    I need some advise on how to achieve the subject. My query is as follows:
    select t2.post_date a, trunc(sysdate - (&num + 1))
    from trans_hist t2
    where t2.post_date >= trunc(sysdate - (&num + 1))
    and 'xxxxxxxxxxxxxxx' in
    (t2.reference_from_account_id, t2.reference_to_account_id)
    and decode(t2.reference_from_account_id,
    'xxxxxxxxxxxxxxx',
    t2.from_account_balance,
    t2.to_account_balance) = 150
    order by t2.post_date
    It will give me the following result:
    4-JUN-2007
    5-JUN-2007
    6-JUN-2007
    I will would to build my query so that it excludes the last row. My aim is to come up with something like the below:
    select max(t2.post_date)
    from trans_hist t2
    where t2.post_date >= trunc(sysdate - (&num + 1))
    and 'xxxxxxxxxxxxxxx' in
    (t2.reference_from_account_id, t2.reference_to_account_id)
    and decode(t2.reference_from_account_id,
    'xxxxxxxxxxxxxxx',
    t2.from_account_balance,
    t2.to_account_balance) = 150
    order by t2.post_date
    Thank you for your help.
    Randy

    maybe something like:
    SQL> with trans_hist as
      2  (select to_date('4-JUN-2007','DD-MON-YYYY') post_date from dual union all
      3   select to_date('5-JUN-2007','DD-MON-YYYY') post_date from dual union all
      4   select to_date('6-JUN-2007','DD-MON-YYYY') post_date from dual)
      5  select * from trans_hist;
    POST_DATE
    04-JUN-07
    05-JUN-07
    06-JUN-07
    SQL> with trans_hist as
      2  (select to_date('4-JUN-2007','DD-MON-YYYY') post_date from dual union all
      3   select to_date('5-JUN-2007','DD-MON-YYYY') post_date from dual union all
      4   select to_date('6-JUN-2007','DD-MON-YYYY') post_date from dual)
      5  select transaction_history.post_date
      6    from (select post_date,
      7                 row_number() over (order by post_date desc) rn
      8            from trans_hist) transaction_history
      9   where transaction_history.rn > 1;
    POST_DATE
    05-JUN-07
    04-JUN-07
    SQL> in your code it will be something like:
    select t3.a, t3.b
      from (select t2.post_date a, trunc(sysdate - (&num + 1)) b,
                   row_number() over (order by t2.post_date desc) rn
              from trans_hist t2
             where t2.post_date >= trunc(sysdate - (&num + 1))
               and 'xxxxxxxxxxxxxxx' in (t2.reference_from_account_id, t2.reference_to_account_id)
               and decode(t2.reference_from_account_id,'xxxxxxxxxxxxxxx',t2.from_account_balance,t2.to_account_balance) = 150) t3
    where t3.rn > 1
    order by t3.a

Maybe you are looking for