Monday, January 11, 2010

Get extra records between two tables - Oracle

Here are examples of each when you wish to see matching data and data differences between two tables.

Example:
You have primary Person Table that has 100 records, unique identifier person_id,
then you have a another Table Person_Depts with only 63 records that has Person_id.

Table : Persons
person_id number,
person_name, etc...


Table : Person_Dept
person_id number,
dept_id number,
status char(1), etc...


When you wish to find the 63 matching records it's easy:

select distinct
from persons p,
person_dept pd
where p.person_id = pd.person_id


When you wish to return the 37 rows of the persons in person_dept and do not have a match in persons, you extract them using one of the followig two queries:

select distinct pd.person_id from person_dept pd
minus
select p.person_id from persons p


Or you could use the following lines on small sets of data, using this on long non-indexed tables

select tp.person_ID
from
person_dept tp
where (tp.person_ID ) NOT IN ( select p.person_id from persons p)