tags:

views:

44

answers:

2

i have two tables both have columns of fname and lname how would i write the query to check and see if one of the tables is missing a record that doesnt exist in the other table?

here are the tables and its columns

tbl_client
-fname
-lname

tbl_lease
-fname
-lname

i need to keep checking the tbl_lease to see if the records match the table tbl_client and if it doesnt i would be able to display it to me. thanks

+1  A: 

A simple way would be to use a not exists predicate in the where clause:

select tbl_client.fname, tbl_client.lname, 'missing from lease' as missingfrom
    from tbl_client
    where not exists
       (select 1 from tbl_lease where tbl_lease.fname=tbl_client.fname
        and tbl_lease.lname=tbl_client.lname)
union
select tbl_lease.fname, tbl_lease.lname, 'missing from client' as missingfrom
    from tbl_lease
    where not exists
       (select 1 from tbl_client where tbl_lease.fname=tbl_client.fname
        and tbl_lease.lname=tbl_client.lname)

Or maybe do a full outer join and check which table's records are null, but that's probably a bit less straightforward, and it could be less efficient than a not exists.

Fly
If you do not have matching indexes on at least one of the names in both tables, you might run into some table scans that could be very slow in any case. With an index on tbl_client(lname, fname) and one on tbl_lease(lname, fname), the query ought be very fast.
Fly
wow thanks didnt know of that one. when using not exists is it checking whats in the paranthesis as not exist or the selection before not exist
SarmenHB
It's checking that the subquery in parentheses returns no records.
Fly
A correlated subquery in this case, but an `exists` or `not exists` correlated subquery can run very fast with the indexes because the RDBMS just has to do an index seek.
Fly
A: 

Get all the records in tbl_lease where fname is not present in tbl_client:

 select tl.* from tbl_lease tl
    left join tbl_client tc on tl.fname = tc.fname 
 where tc.fname is null;

And the other way around, records present in tbl_client where the fname is not present in tbl_lease

 select tc.* from tbl_client tc
   left join tbl_lease tl on tc.fname = tl.fname 
  where tl.fname is null;
nos