How to combine two tables and get rows from first table if there is match in the second table?

314 Views Asked by At

I have two tables with the same schema, I want combine both the tables with distinct Id. If there is matching between two tables (with the same Id), then chose Table A Source over Table B Source

Table A                     Table B         
Id  Name    Age Source      Id  Name    Age Source
A   Jack    33  public      A   Jack    32  private
B   Jon     44  public      B   Jon     44  private
C   Tom     45  public      E   Matt    19  private
D   sid     19  public      F   Tom     30  private
A   Jack    33  public


    Result          
Id  Name    Age Source
A   Jack    33  public
B   Jon     44  public
C   Tom     45  public
D   sid     19  public
E   Matt    19  private
F   Tom     30  private

I tried union, but now sure how to prefer table Source over Table B source. Thanks for your help

1

There are 1 best solutions below

4
GMB On

This reads like a full join, and coalesce() for prioritization:

select coalesce(a.id, b.id) id,
    coalesce(a.name, b.name) name,
    coalesce(a.age, b.age) age,
    coalesce(a.source, b.source) source
from tablea a
full join tableb b on a.id = b.id