Skip to content
Advertisement

Compare Two tables in SQL and equals row set to ‘True’ in new Column

Can some one explain the SQL query for bellow outcomes in TableResult.

TableA                        TableB                    TableResult

Id | Function                 Id | Function              Id | Function | Compare
---|----------               ----|----------            ----|----------|---------
1  | code1                    1  | code1                 1  | code1    | true
2  | code2                    2  | code4                 2  | code2    | false
3  | code3                    3  | code5                 3  | code3    | false
4  | code4                                               4  | code4    | true

There is two tables TableA and TableB, Function column in both tables are unique. Entire data in TableA should be there in ResultTable, If TableB Function equals in TableA function, Then ResultTable Compare column must be true otherwise it’s false.

Can anyone advised How to get the desired outcome in SQL.

Any help would be greatly appreciated

Advertisement

Answer

You can do it with EXISTS:

select a.*,
  exists (select 1 from TableB b where b.function = a.function) compare
from TableA a  

or:

select a.*,
  case 
    when exists (select 1 from TableB b where b.function = a.function) then 'true'
    else 'false'
  end compare
from TableA a 

See the demo.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement