Selecting data from either of two tables if a key exists

Hi Everyone,

I have a question on how to select data when it exists in either of two tables.

Example:  I have table 'A' that contains the main key (serial number). Table B will have a corresponding record for that key. Table C may have an entry with the matching key.   I would like to using the key from table 'A', extract data from Table 'C' if a matching key exists, otherwise extract data from Table 'B'. NOTE: Table 'B' will always have a matching key/entry, Table 'C' contains only updates for certain keys.

Thanks in advance!
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

you could do something like this:

with a as (
select 1 as priority, list-of-columns
from C
union all
select 2, list-of-columns
from B
b as (
select *
from A t1 join a t2 on t1.key = t2.key
order by priority
select * from b
fetch first 1 rows only
Dave FordSoftware Developer / Database AdministratorCommented:
Personally, I would use a LEFT OUTER JOIN and a COALESCE to accomplish that. It seems a lot cleaner and easier to me.

 select a.theMainKey,
       coalesce(c.someData, b.someOtherData)
  from TableA a
  left outer join TableB b
    on b.theMainKey = a.theMainKey
  left outer join TableC c
    on c.theMainKey = a.theMainKey

Open in new window


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Mark1MAuthor Commented:
Hi momi_sabag,

Thank you for your response and solution.
Mark1MAuthor Commented:
Hi Dave,

Thank you for your response and solution.

Works great!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.