Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Select data from 2 tables conditionally

Let’s say I have 2 tables (Table1 and Table2) with same structure

  • int Id
  • string Name

Ex:

Table1: (1,’abc’), (2,’xxx’), (3, ‘mm’)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Table2: (1,’abcd’), (3, ‘nnnn’)

The goal is to display data from Table1 if there is no data for the same Id in Table2 or from Table2 when there is such data

For the tables above, the data returned will be:

(1, ‘abcd’) — from Table2

(2, ‘xxx’) — from Table1

(3, ‘nnnn’) — from Table2

This is what I tried:

select Table1.Id, 
case Table2.Name
    when null then Table1.Name
    else Table2.Name 
end as Name
from Table1
left join Table2 on Table2.Id = Table1.Id

but doesn’t work

>Solution :

Your CASE WHEN is somewhat wrong, you need IS to check for NULL

CREATE TABLE Table1(id int, name varchar(5))
CREATE TABLE Table2(id int, name varchar(5))
INSERT INTO Table1 VALUES (1,'abc'), (2,'xxx'), (3, 'mm')

3 rows affected

INSERT INTO Table2 VALUES (1,'abcd'), (3, 'nnnn')

2 rows affected

select Table1.Id, 
case when Table2.Name is null
    then Table1.Name
    else Table2.Name 
end as Name
from Table1
left join Table2 on Table2.Id = Table1.Id
Id Name
1 abcd
2 xxx
3 nnnn

fiddle

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading