Need help to get alternate or better way to write query

Hi,
I am on Oracle 11.2
DDL and sample data
create table tab1 -- 1 millions rows at any given time
id       number       not null,
ref_cd   varchar2(64) not null,
key      varchar2(44) not null,
ctrl_flg varchar2(1),
ins_date date
create table tab2 -- close to 100 million rows
id       number       not null,
ref_cd   varchar2(64) not null,
key      varchar2(44) not null,
ctrl_flg varchar2(1),
ins_date date,
upd_date date
insert into tab1 values (1,'ABCDEFG', 'XYZ','Y',sysdate);
insert into tab1 values (2,'XYZABC', 'DEF','Y',sysdate);
insert into tab1 values (3,'PORSTUVW', 'ABC','Y',sysdate);
insert into tab2 values (1,'ABCDEFG', 'WYZ','Y',sysdate);
insert into tab2 values (2,'tbVCCmphEbOEUWbxRKczvsgmzjhROXOwNkkdxWiPqDgPXtJhVl', 'ABLIOWNdj','Y',sysdate);
insert into tab2 values (3,'tbBCFkphEbOEUWbxATczvsgmzjhRQWOwNkkdxWiPqDgPXtJhVl', 'MQLIOWNdj','Y',sysdate);I need to get all rows from tab1 that does not match tab2 and any row from tab1 that matches ref_cd in tab2 but key is different.
Expected Query output
'ABCDEFG',  'WYZ'
'XYZABC',   'DEF'
'PORSTUVW', 'ABC'Existing Query
select
   ref_cd,
   key
from
    select
        ref_cd,
        key
    from
        tab1, tab2
    where
        tab1.ref_cd = tab2.ref_cd and
        tab1.key    <> tab2.key
    union
    select
        ref_cd,
        key
    from
        tab1
    where
        not exists
           select 1
           from
               tab2
           where
               tab2.ref_cd = tab1.ref_cd
    );I am sure there will be an alternate way to write this query in better way. Appreciate if any of you gurus suggest alternative solution.
Thanks in advance.

Hi,
user572194 wrote:
... DDL and sample data ...
create table tab2 -- close to 100 million rows
id       number       not null,
ref_cd   varchar2(64) not null,
key      varchar2(44) not null,
ctrl_flg varchar2(1),
ins_date date,
upd_date date
insert into tab2 values (1,'ABCDEFG', 'WYZ','Y',sysdate);
insert into tab2 values (2,'tbVCCmphEbOEUWbxRKczvsgmzjhROXOwNkkdxWiPqDgPXtJhVl', 'ABLIOWNdj','Y',sysdate);
insert into tab2 values (3,'tbBCFkphEbOEUWbxATczvsgmzjhRQWOwNkkdxWiPqDgPXtJhVl', 'MQLIOWNdj','Y',sysdate);
Thanks for posting the CREATE TABLE and INSERT statments. Remember why you go to all that trouble: so the people whop want to help you can re-create the problem and test their ideas. When you post statemets that don't work, it's just a waste of time.
None of the INSERT statements for tab2 work. Tab2 has 6 columns, but the INSERT statements only have 5 values.
Please test your code before you post it.
I need to get all rows from tab1 that does not match tab2 WHat does "match" mean in this case? Does it mean that tab1.ref_cd = tab2.ref_cd?
and any row from tab1 that matches ref_cd in tab2 but key is different.
Existing Query
select
ref_cd,
key
from
select
ref_cd,
key
from
tab1, tab2
where
tab1.ref_cd = tab2.ref_cd and
tab1.key    <> tab2.key
union
select
ref_cd,
key
from
tab1
where
not exists
select 1
from
tab2
where
tab2.ref_cd = tab1.ref_cd
Does that really work? In the first branch of the UNION, you're referencing a column called key, but both tables involved have columns called key. I would expect that to cause an error.
Please test your code before you post it.
Right before UNION, did you mean
tab1.key    != tab2.key? As you may have noticed, this site doesn't like to display the &lt;&gt; inequality operator. Always use the other (equivalent) inequality operator, !=, when posting here.
I am sure there will be an alternate way to write this query in better way. Appreciate if any of you gurus suggest alternative solution.Avoid UNION; it can be very inefficient.
Maybe you want something like this:
SELECT       tab1.ref_cd
,       tab1.key
FROM           tab1
LEFT OUTER JOIN  tab2  ON  tab2.ref_cd     = tab1.ref_cd
WHERE       tab2.ref_cd  IS NULL
OR       tab2.key     != tab1.key
;

Similar Messages

  • I need help in getting my reponses

    I need help in getting my responses back, or I am sending out the form wrong and people aren't getting it. Either way I need help, as I am getting very frustrated.  Thanks Dori

    <moved from Downloading, Installing, Setting Up to Photoshop General Discussion>

  • Hi need help on getting customer open  items

    hi all,
    i need help regarding getting open items for customers in the previous
    ie. if i give current date,
    i want to get the open items for past 30 days from current date
    help me to get this ...
    thanks a lot
    regards,
    selvi

    or else ,
    use table BSID.
    Regards
    Peram

  • I need help in getting my Iphone 3gs unfrozen

    Need help in getting my Iphone 3gs unfrozen. The apple logo is shown yet it will not restart. Suggestions?

    Hi,
    Try here >  iPhone and iPod touch: Frozen and unresponsive

  • I need help in getting my software options in CS5 Photoshop Student version. We have registered the product but don't have print preview or Adjust Auto Levels for example?

    I need help in getting my software options in CS5 Photoshop Student version. We have registered the product but don't have print preview or Adjust Auto Levels for example?

    <moved from Downloading, Installing, Setting Up to Photoshop General Discussion>

  • Sign in told my firefox out of date did try to do upgrade but could not need help to get my sign in workin email

    sign in told my firefox is out of date. did try to do the upgrade but could not do
    need help to get my sign in working

    Kathleen Beal/funstarling please respond in https://support.mozilla.org/en-US/questions/982953

  • I changed my password i forgot what it is need help to get back in

    i need help i changed my passwordand i forgot it now i need help to get back in it keeps saying disabled?? help me plz

    Place the iOS device in Recovery Mode and then connect to your computer and restore via iTunes. The iPod will be erased.
    iOS: Wrong passcode results in red disabled screen                          
    If recovery mode does not work try DFU mode.                         
    How to put iPod touch / iPhone into DFU mode « Karthik's scribblings         
    For how to restore:
    iTunes: Restoring iOS software
    To restore from backup see:
    iOS: How to back up
    If you restore from iCloud backup the apps will be automatically downloaded. If you restore from iTunes backup the apps and music have to be in the iTunes library since synced media like apps and music are not included in the backup of the iOS device that iTunes makes.
    You can redownload iTunes purchases by:
    Downloading past purchases from the App Store, iBookstore, and iTunes Store

  • Need help in getting 'RoleApprover' and 'Manager of RoleApprover'

    We are developing a Custom Role Approval Process using SOA composite.
    A manager or a delegated admin will be raising a Role Approval request for a beneficiary. We need to assign the Approval task to beneficiaries' manager or Role Approver.
    If the RoleApprover does not Approve the task in stipulated time, the task needs to get escalated to RoleApprover's manager.
    I'm new to OIM APIs, i was folllowing the tutorial "developing_oim_custom_approval_process_for_role_request.pdf". This needs an user defined field 'RoleApprover' created in the Role request form. We cannot create user defined field in the role request form.
    I need help in getting the 'RoleApprover' and the 'Manager of RoleApprover' programmatically.
    Payload from the OIM Approval request follows:
    <ns2:process>
    <RequestID>176</RequestID>
    <RequestModel>Assign Roles</RequestModel>
    <RequestTarget>Onhand Quantity</RequestTarget>
    <RequesterDetails>
    <FirstName>Steve</FirstName>
    <LastName>Waugh</LastName>
    <Login>STEVEWAUGH</Login>
    <DisplayName>Steve Waugh</DisplayName>
    <ManagerLogin>XELSYSADM</ManagerLogin>
    <OrganizationName>Test</OrganizationName>
    <Email>[email protected]</Email>
    <Status>Active</Status>
    <XellerateType>End-User</XellerateType>
    <UserType>Full-Time</UserType>
    <Role>ALL USERS</Role>
    <Role>Primavera P6 - Global</Role>
    <Role>iProcurement Catalog Administrator</Role>
    <Role>Onhand Quantity</Role>
    <Role>Test Purchasing Super User</Role>
    <Role>Test Delegated Administrator</Role>
    <Role>HELPDESK ADMINISTRATORS</Role>
    <Role>Test e-Commerce Gateway Super User</Role>
    <Role>eBusiness Finance</Role>
    <Role>Test Line Manager</Role>
    <Role>Test_ApplicationApprover</Role>
    </RequesterDetails>
    <BeneficiaryDetails>
    <FirstName>David</FirstName>
    <LastName>Boon</LastName>
    <Login>DAVIDBOON</Login>
    <DisplayName>David Boon</DisplayName>
    <ManagerLogin>STEVEWAUGH</ManagerLogin>
    <OrganizationName>TestCO</OrganizationName>
    <Email>[email protected]</Email>
    <Status>Active</Status>
    <XellerateType>End-User</XellerateType>
    <UserType>Full-Time</UserType>
    <Role>ALL USERS</Role>
    <Role>Hyperion</Role>
    <Role>Test Purchasing Administrator</Role>
    <Role>Test Internet Expenses Audit Manager</Role>
    <Role>Test Internet Expenses Auditor</Role>
    </BeneficiaryDetails>
    <ObjectDetails>
    <name>Test Onhand Quantity</name>
    <attributes/>
    </ObjectDetails>
    <url>
    http://host:port/workflowservice/CallbackService
    </url>
    <OtherDetails/>
    </ns2:process>
    Edited by: rajesh on Feb 13, 2011 9:00 AM

    Choose Xerces2.4 to serialize the DOM object is an option.
    javac XercesTest.java -classpath xmlParserAPIs.jar;xercesImpl.jar;.
    java -classpath xmlParserAPIs.jar;xercesImpl.jar;. XercesTest test.xml
    below is the source file: XercesTest.java
    //JAXP
    import javax.xml.parsers.*;
    import org.w3c.dom.*;
    //APACHE SERIALIZE FUNCTION
    import org.apache.xml.serialize.*;
    class XercesTest
    public static void main(String[] args) throws Exception
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse( new File( args[0] ) );
    File f = new File( "copy_of_"+ args[0] );
    OutputFormat format = new OutputFormat("xml","UTF-8",true ) ;
    FileOutputStream fout = new FileOutputStream( f );
    XMLSerializer ser = new XMLSerializer(fout, format );
    ser.serialize( doc );
    maybe it's helpful
    land

  • The basic sliders disappeared. Including the Exposure, Contrast, Highlights, Shadows, Whites, Blacks, Clarity and Vibrance Sliders are no longer available. I need help to get them back

    The basic sliders disappeared. Including the Exposure, Contrast, Highlights, Shadows, Whites, Blacks, Clarity and Vibrance Sliders are no longer available. I need help to get them back on the program. 
    I can't figure out where the sliders went and how to put them back on. Anyone have any suggestions?
    Thanks

    In Lightroom, go to the Window menu, select Panels, select Basic

  • TS1363 i need help to get out of recovery mode

    i need help to get out of recovery mode

    To get the phone out of recovery mode you will need to connect it to a computer with iTunes installed on it and restore it.

  • My mom and I both have iphone5 but when I send her messages they aren't blue but any other iphone I text is blue I need help to get that fixed

    My mom and I both have iphone5 but when I send her messages they aren't blue but any other iphone I text is blue I need help to get that fixed

    Both of you need to have iMessage activated, and both have to have active Internet connection for iMessage. Are you both using the same Apple ID? Are you using the phone number or Apple ID for messages?

  • HT4199 I need help with getting my printer to print, PLEASE.

    I need help with getting my printer to print, Please.

    What have you done so far?
    I suggest you connect it via a usb  cable first.  Once you get the printer working, move to wifi.  You will have to use an existing printer usb cable or purchase a cable.  Be sure to get the correct cable.  Ask for help.
    The warrenty indicates there is phone support.  Give HP a call.
    Warranty
    One-year limited hardware warranty; 24-hour, 7 days a week phone support
    Robert

  • A better way to write last_day query

    Hi folks,
    I am looking for a better way to write a query to find last_day in month but if its sunday or holiday it should move to day before last day.
    So for example if 31 is sunday it should go for 30, if 30 is holiday it should move down to 29.
    I got this so far but the connect by level is hardcoded to 15. Want to see if there is a better way to get this working:
    select max(datum)
      from (    select last_day(trunc(sysdate)) - level + 1 as datum
                  from dual
            connect by level < 15)
    where to_char(datum, 'day') != 'sunday'    
       and to_char(datum, 'DDMM') not in
             ('3012')Best regards,
    Igor

    Like this
    select to_char(last_day_month, 'Day') day_is,
           last_day_month,
           last_day_month - case when to_char(last_day_month, 'fmday') = 'sunday' then 1
                                 when to_char(last_day_month, 'ddmm' ) = '3012'   then 1
                                 else 0
                            end last_business_day_month
      from (
              select last_day(add_months(trunc(sysdate, 'year'), level-1)) last_day_month
                from dual
              connect by level <= 12
    DAY_IS    LAST_DAY_MONTH LAST_BUSINESS_DAY_MONTH
    Tuesday   31-JAN-12      31-JAN-12              
    Wednesday 29-FEB-12      29-FEB-12              
    Saturday  31-MAR-12      31-MAR-12              
    Monday    30-APR-12      30-APR-12              
    Thursday  31-MAY-12      31-MAY-12              
    Saturday  30-JUN-12      30-JUN-12              
    Tuesday   31-JUL-12      31-JUL-12              
    Friday    31-AUG-12      31-AUG-12              
    Sunday    30-SEP-12      29-SEP-12              
    Wednesday 31-OCT-12      31-OCT-12              
    Friday    30-NOV-12      30-NOV-12              
    Monday    31-DEC-12      31-DEC-12 

  • Need help on getting the column names of Tabletype

    I have a table Mapping with the following values: This Mapping table contains the table names (in Tabname) and the column names(colname) of various tables and values(ValuesTobeFilled) for the columns.
    I have to insert into the tables present in the Tabname field with the values present in the ValuesTobeFilled in the columns present in the Colname field.
    Note: The Mapping table need not contain all the columns of the base table. The columns that are not present can be filled with null. And this mapping table is not fixed i.e. rows can be inserted/deleted frequently.
    Sample values in mapping table:
    Tabname                        Colname        ValuesTobeFilled
    sample_items     Eno     Corresponding Expression to get the values from XML input
    sample_items     Ename     Corresponding Expression to get the values from XML input
    XXX     YYY     Corresponding Expression to get the values from XML input
    Before filling in the actual tables, I have to store the entire data temporarily and I have used a tabletype declared as follows:
    TYPE T_sample_items IS TABLE OF sample_items%ROWTYPE INDEX BY BINARY_INTEGER;
    l_sample_items T_sample_items;
    Where the table sample_items have the following columns:
    •     Eno
    •     Ename
    •     Eaddress
    •     Eemail
    So, the tabletype should be filled as:
    Eno     Ename     Eaddress     EEmail
    1     XXX     -     -
    I have declared a cursor to select the values from mapping table and I need to fill in the ValuesTobeFilled values to the corresponding table.
    CURSOR c_xpath (c_tname mapping.TABNAME%type)
    IS
    select * from mapping where tabname = c_tname;
    CURSOR c_tables
    IS
    SELECT DISTINCT TABNAME FROM mapping;
    FOR crsr IN c_tables
    LOOP
    p_tname := CRSR.TABNAME;
    FOR csr IN c_xpath(p_tname)
    LOOP
    IF l_xml_doc.EXISTSNODE(CSR.XPATH_EXP) = 1
    THEN
    l_node_value := l_xml_doc.extract(CSR.XPATH_EXP).getStringVal(); -- This is the value to be stored in the corresponding column
    ELSE
         l_node_value := NULL;
    END IF;
    IF CSR.COLUMN_NAME = ‘eno’
    THEN
         l_sample_items(1).eno := l_node_value;
    ELSIF CSR.COLUMN_NAME = ‘ename’
    THEN
         l_sample_items(1).name := l_node_value;
    END IF;
    END LOOP;
    END LOOP;      
    And I need to eliminate hard coding while comparing the column names (in the following piece of code) as the Mapping table values are subject to insertion/deletion:
    IF CSR.COLUMN_NAME = ‘eno’
    THEN
         l_sample_items(1).eno := l_node_value;
    ELSIF CSR.COLUMN_NAME = ‘ename’
    THEN
         l_sample_items(1).ename := l_node_value;
    END IF;
    I need to insert the values directly into the tabletype without this hardcoding. Please suggest me ways to compare the mapping table values with the field (column) names of the tabletype. If it is not possible using tabletype, please suggest any other ways of fixing the problem.
    Many thanks,
    Gopi

    I take it this isn't going to be a serious production system at the end of the day?
    Storing metadata in tables for extraction and insertion of data is just wrong in so many ways. It smells heavily of Entity Attribute Value modelling, which is the most wrong way to use a relational database and is known to have major performance implications and be liable to bugs and issues. The idea that EAV modelling allows for 'generic' databases where new data items can be added flexibly later on without having to change code is usually justified with an excuse of "it means we don't have to update all our tables when we want a new column" which is easily countered with "if you're adding a single column a good relational design wouldn't require you to add it to more than one table anyway in most cases".
    Just what exactly are you trying to do and why? There has to be a better way.

  • I need help in getting VZ to fix my DSL speed - they refused to fix it two times

    I live in E. Boston and opened a trouble ticket on 8-26-13 for slow internet speed. Ticket number was {edited for privacy}Agreement was made for a tech to arrive on the 28th between 1 and 5 PM. Somebody showed at my door on the 28th at 11:15AM. He immediately said that he had already done some outside checking and there was a problem outside of my home. I showed him my slow connection speed and he left saying he would be back later. I saw him on poles around my home and he called later saying he needed help from his office and would let me know the status by 3PM or so. I never heard from him again. I continued to check the ticket status and it was open.
    On Friday, Aug. 30th, about 9:15AM, I received a call from a VZ telephone tech named Rich. He again did some outside checking and came into my home. I showed him my slow internet speed and he went back outside after telling me that he had no test equipment but he would go back outside to see what he could do and call his manager since he was not a VZ internet tech. He came back a little later and told me that he did all that he could do and asked me to run my tests again. I did so in front of the tech and the speed was at least 30% slower than it is supposed to be. The VZ telephone tech said he would call for help from his office to send a tech with proper test equipment and he left. A number of hours passed and the VZ telephone tech called and told me HIS MANAGER TOLD HIM TO CLOSE THE TICKET AND TO SEND THE MANAGER THE INFORMATION.
    I immediately asked for and got the name and office of the manager that did this and I have it. I will hold off posting it for a couple of days but then I will let everyone know how this Verizon manager performs as well as who he is. I wonder how his superiors will like that?
    Does anyone have any suggestions who in Verizon cares enough to get my problem resolved? I have already filed a complaint with the AGO today. Verizon does this to keep their numbers from being respective of what they really are as well as knowing that customers do not want to again walk through all of the crap in opening a trouble ticket in India. I have been in telecom for 45 years and this is just disgraceful. It is about time VZ developed some integrity.

    Your issue has been escalated to a Verizon agent. Before the agent can begin assisting you, they will need to collect further information from you.Please go to your profile page for the forum, and look in the middle, right at the top where you will find an area titled "My Support Cases". You can reach your profile page by clicking on your name beside your post, or at the top left of this page underneath the title of the board.
    Under “My Support Cases” you will find a link to the private board where you and the agent may exchange information. This should be checked on a frequent basis as the agent may be waiting for information from you before they can proceed with any actions. Please keep all correspondence regarding your issue in the private support portal.

Maybe you are looking for

  • SPSecurity.RunWithElevatedPrivileges Not Working for Read Only Permissions Users

    I have the following code in a method that generates tabbed web parts on any page in SharePoint 2010. The problem is that it will not work for users who have Read access only on a SharePoint site.  It will work when those users have Contribute access

  • Sync keeps telling me my password is wrong, i have reset it several times.

    I have set up sync for my android and my desktop however when I try to sync my mobile is telling me my password is wrong and when I try to relog into sync via the browser on my desktop it tells me the password is wrong. I have deleted and reset the p

  • Reports 6 - Attached Libraries.

    Am currently developing a report using Oracle Report Builder 6.0 - which has an attached library containing a specific program unit. When compiled on my machine (win2000), no errors are encountered. But during runtime, we receive the error "ORA-06508

  • APO Planned Order

    Hi Experts, I have a problem with the generated planned orders whenever i run location heuristic. It produces planned orders more than the demand. I have Push deployment Horizon defined, and also Pull deployment Horizon both at 150days. But in the De

  • Password Confused?

    I'm very condfused with reagrds to my Apple accounts and passwords.. I have: - An icloud account: [email protected] - An Apple account: xxxxxx @yahoo.com It seems that my apple ID runs my itunes such as the apps store and my icloud account runs thing