4

I was trying to make this query to work

select *
from DUALS
where num in ('1,2,3')

string '1,2,3' creating on the fly, so i cant replace it as list of integers in code.

So I end with this:

select *
from DUALS
where num in (select unnest (string_to_array('1,2', ',')::integer[]))

It works, but I'm wondering if it might be simplified. Can't use 'Any' operator.

5
  • I think is simple enough. But if you want can create a function to receive string a return integer[] Commented May 16, 2017 at 14:09
  • 2
    Why can't you use the ANY operator? Commented May 16, 2017 at 14:09
  • Because of cross-platfrom reason. Some DB engines can use ANY predicates only with subqueries, but works fine with in '1,2,3'. Commented May 16, 2017 at 15:12
  • If this is supposed to be portable, how can you use unnest and string_to_array or array types in general? Commented May 16, 2017 at 15:25
  • preprocessor for postgresql in this case. Ugly but works. The way of less resistance for now. In general, original query is portable, but not in postgresql. In postgresql it will look like second query. Commented May 16, 2017 at 15:29

2 Answers 2

1

You can just use this code:

select *
from DUALS
where num = any('{1,2,3}'::int[])
Sign up to request clarification or add additional context in comments.

1 Comment

>> Can't use 'Any' operator.
0

Alternate soluton is to use python string replacement - and then pass the full query string. Provided you know the dynamically generated comma separated string or can build it.

Python code: query = " select * from students where name in (%s);"

#some for loop which will create below string students_list_str = 'MUSK', 'TRUMP'

query_str = query%(students_list_str) #Now query_str = " select * from students where name in ('MUSK', 'TRUMP');"

cursor.execute(query_str)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.