'compare two columns from two different tables in oracle sql for differences
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.
Solution 1:[1]
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
Solution 2:[2]
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
Solution 3:[3]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | brenners1302 |
| Solution 3 |
