25

I am trying to convert the Comma separated string into an integer array (integer[]) to use in Where clause.

I have tried cast, ::Int which didn't work. Appreciate your input

Example

Table A   |  Table B
ID        |  Set_id
2         |  14,16,17
1         |  15,19,20
3         |  21

My Query:

Select * 
from Table a, table b 
where a.id in b.set_id
1
  • This is a horrible design. Why do you do that? Commented Jul 25, 2017 at 13:32

3 Answers 3

53

You need to convert the string to a proper integer array if you want to use that for a join condition.

Select * 
from Table a
  join table b on a.id = any(string_to_array(b.set_id, ',')::int[]);

But a much better solution would be to properly normalize your tables (or at least stores those IDs in an integer array, not a varchar column)

Sign up to request clarification or add additional context in comments.

1 Comment

This may happen when some raw data was stored as "1,23,456" in some file. You have to convert those to array of integers for less storage usage and better performance.
10
Select * from Table_a a, table_b  b
where a.id = any(regexp_split_to_array(b.set_id,',')::int[]);

Comments

6

You could use unnest() function. unnest function is to used expand an array to a set of rows.
Select * from Table_a a, table_b b where a.id in (SELECT unnest(string_to_array(b.set_id, ',')::int[]));

1 Comment

Welcome to Stack Overflow. Code dumps without any explanation are rarely helpful. Stack Overflow is about learning, not providing snippets to blindly copy and paste. Please edit your question and explain how it answers the specific question being asked. See How to Answer. This is particularly important when answering old questions (this is nearly 4 years old) with existing answers. How does this improve upon what's already here?

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.