0

Is there a way in Postgres I can parse string values to integers? Basically I'm trying to query one table (let's call it table_one) using values from another table (table_two) in a character varying column.

Say SELECT char_column FROM table_two results in "2,4,6,8", I'd like to use this result in a second query as;

SELECT column FROM table_one WHERE some_id IN (2,4,6,8)

How can I get the string "2,4,6,8" to values 2,4,6,8 so as to be able to use it in the second query?

I've tried casting and to_number functions to no success.

1

2 Answers 2

3
SELECT column
FROM table
WHERE other_column = ANY(string_to_array('2,4,6,8', ',')::INT[])
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I've been struggling with this for a while now.
1

Please try this:

SELECT column     FROM table    WHERE other_column IN (
                           SELECT NULLIF(i,'')::int 
                             FROM regexp_split_to_tables('2,4,6,8',',') t(i)
                         )

Explanation:

The part regexp_split_to_tables('2,4,6,8',',') will split the string into a table. Then you cast it into integer.

Hopefully it will help you.

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.