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

How to return NULL from a select-where-in postgresql query when the record does not exist in the array?

I have a query

select * 
from table1 as t
where t.id in ('1', '2')

If both records are the my result is [1, 2].
If only record #1 is there my result is [1].

But if only record #1 is there how can I make the result be [1, NULL] ?

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

>Solution :

Using VALUES and LEFT JOIN:

SELECT t.id
FROM (VALUES ('1'), ('2')) s(c)
LEFT JOIN table1 AS t
  ON t.id = s.c;

db<>fiddle demo

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