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 a row of the table with desired value, when a column's value which is not in the table is selected in where clause in keyword?

I have a table with one of the columns as ID. I have a set of values which I give in the where clause to compare the ‘ID’ column using ‘in’ keyword. I want to select the row if the value in that set of values has a record in the table. If not, the value that is not in the table has to be selected along with empty values other columns.

For example:
There is a table with columns ID & Animal. It has 8 records.

The table with all records

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

If I run the query:

SELECT ID, Animal from #Temp1 where ID in (4,8)

it will return the following result.

The table result filtered

But, if I run the query:

SELECT ID, Animal from #Temp1 where ID in (4,8,12)

it should return the following result.

The table result with desired values

>Solution :

Use a LEFT JOIN in concert with string_split() instead

Select ID = A.value
      ,Animal = coalesce(B.Animal,'ID Not Found') 
 From string_split('4,8,12',',') A
 Left Join YourTable B on A.value=B.ID

Results

ID  Animal
4   Donkey
8   Hampster
12  ID Not Found

If by chance string_split() is not available

Select ID = A.value
      ,Animal = coalesce(B.Animal,'ID Not Found') 
 From (values (4)
             ,(8)
             ,(12)
      ) A(value)
 Left Join YourTable B on A.value=B.ID
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