NewSQL
NewSQL

Reputation: 181

How to fetch matched data from first table and unmatched from second table

I have 2 tables with same structure eg. Table A and B with columns id,value.

Table A

ID    VALUE
1      10
2      20
3      0


Table B

ID    VALUE
1      24
2      26
3      0
4      40
5      50

    expected output:

ID    VALUE
1      10
2      20
3      0
4      40
5      50

as per output first three id is matched with table B so id(1,2,3) with value comes from table A and id(4,5) with value is not matched so it comes from table B.

Upvotes: 1

Views: 41

Answers (1)

Raphaël Althaus
Raphaël Althaus

Reputation: 60503

You could use a right join on table b (or a left join on table a) and use a coalesce operator.

select b.id, coalesce(a.value, b.value)
from tablea a
right join tableb b on a.id = b.id

or

select b.id, coalesce(a.value, b.value)
from tableb b
left join tablea a on a.id = b.id

see SqlFiddle

Upvotes: 1

Related Questions