Wednesday, 15 March 2017

Sql Query To Compare Two Tables And Find Records With Matches

how to get matching records from two tables in oracle sql.
First  check the employee Records and check target records
for example i created  emp_target table  from emp with some duplicates in emp_target table.
Now Check the count of two table
SQL> SELECT COUNT(*) FROM EMP;



          RESULT IS :-14
SQL>SELECT COUNT(*) FROM EMP_TARGET;
          RESULT IS :-14
NOW SEE THE RECORDS FROM TWO TABLES. AS SHOWN BELOW

SQL> SELECT * FROM EMP; 

how to get matching records from two tables in oracle sql

     14 rows selected.

SQL> SELECT * FROM EMP_TARGET;           
                        
how to get matching records from two tables in oracle sql

14 rows selected.

Now use the Intersect Set operator to find the common records from two tables that is emp and emp_target, and write the query like below.

SQL> SELECT * FROM EMP INTERSECT SELECT * FROM EMP_TARGET;

how to get matching records from two tables in oracle sql
11 rows selected.
So 11 row are common in both tables. Now i want Missed Record count in target table.

how to find the missed target records count

first find the count of matched records from both table  for that we are using InLine View Sub Query.

SQL> SELECT COUNT(EMPNO) FROM(SELECT * FROM EMP INTERSECT SELECT * FROM EMP_TARGET);

COUNT(EMPNO)                                                                                      
------------                                                                                      
          11                                                                                      
After Finding the Count of matched records from two table next substitute the count with total count of target table record count that is emp.

SQL> SELECT ((SELECT COUNT(EMPNO) FROM EMP)-(SELECT COUNT(EMPNO) FROM (SELECT * FROM EMP INTERSECT SELECT * FROM EMP_TARGET))) FROM DUAL;

------------------------------
                3

Finaly the out put is 3

No comments:

Post a Comment