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

Use a string value from a CTE in an IN-clause in a simple SQL query

I am trying to make a simple SQL query in PostgreSQL to use in our team:

with findData as (
  select '(''XXX'',''YYYY'')' as dataList
)
select * from findData

That gives the result:

('XXX','YYYY')

Exactly what I wanted !

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

But I want to use it like this in a simple SQL script:

select t.variabel1,
       t.variabel2
from myTable t
where t.variabel3 in (select dataList from findData);

But this doesn’t work …

Has my problem a solution?

>Solution :

The datalist is treated as a single string value, currently. So, to use the ‘IN’, you need them seperate. Can be done like this.

with findData as (
    select unnest(array['XXX', 'YYYY']) as dataList
)
select t.variabel1, t.variabel2
from myTable t
where t.variabel3 in (select dataList from findData);

The unnest function is used to expand the array into rows.

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