1
votes

Hi first time posting for SQL,

I need to compare two different columns from two different tables in SQL.

For example there is two tables and each have one column in them and I need to compare them.

Column1 is in table1 and column2 is in table2.

I need to compare column1 and column2 for differences, I have looked online but was unable to find a query that would be able to help.

Essentially I need to find the inconsistencies in the two columns from two different tables.

3
What do you mean by "compare for differences"? Are you trying to find values that appear in both? values that appear only in one column? Please go into details. - Neria Nachum
Please edit your question with sample data and desired results. "Compare for differences" is quite vague. - Gordon Linoff
Ok I will. I need to find the differences in data that exist in one but does not exists in the other. Inconsistencies in the data columns. - ceesharpie
select * from table1 A where not exists (select 1 from table2 b where b.column=a.column); - BigMike

3 Answers

0
votes

The following Oracle SQL would be a solution provided you have an id that you can join on between the two tables.

 select tab1.id,
           case
            when tab1.col1 > tab2.col1 OR tab1.col1 < tab2.col1 then 'Different'
            else 'Equals'
           end
    from tab1, tab2
    where tab1.id = tab2.id;

Test data SQL:

create table tab1 ( id number, col1 varchar2(20));
create table tab2 ( id number, col1 varchar2(20));
insert into tab1 values (1, 'ABCD');
insert into tab1 values (2, 'EFGH');
insert into tab1 values (3, 'WXYZ');
insert into tab2 values (1, 'ABCD');
insert into tab2 values (2, 'EFG');
insert into tab2 values (3, 'ZYXW');
commit;

Results:

    ID CASEWHENT

     1 Equals
     2 Different
     3 Different
0
votes

Try this:

    WITH x AS (SELECT 1 AS ID, 'THE QUICK BROWN' AS tab1 FROM dual UNION ALL
                   SELECT 2 AS ID, 'FOX JUMPS OVER' AS tab1  FROM dual),
         y AS (SELECT 1 AS ID, 'THE QUICK BROWN FOX' AS tab2 FROM DUAL UNION ALL
                  SELECT 2 AS ID, 'FOX JUMPS OVER' AS TAB2 FROM DUAL)

SELECT   X.ID,X.tab1,Y.tab2,(CASE WHEN (X.tab1 = tab2) 
                             THEN 'Tab1 is equal  Tab2'
                             ELSE 'Tab1 is not equal to Tab2' END) AS Remarks
FROM X INNER JOIN Y ON X.ID = Y.ID;

OUTPUT:

    ID       TAB1                 TAB2                     REMARKS   
    1  THE QUICK BROWN      THE QUICK BROWN FOX     Tab1 is not equal to Tab2 
    2  FOX JUMPS OVER       FOX JUMPS OVER          Tab1 is equal  Tab2 
0
votes

You can do inner join and then find the difference.

SELECT
       table1.column1,
       table2.column2, 
      (CASE WHEN (table1.column1 = table2.column2 THEN 'No change' ELSE 'Change DETECTED' END)) AS Difference
FROM
table1 INNER JOIN table2 ON table1.id=table2.id