Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting comma separated string to integer array in Postgres

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
like image 462
sam Avatar asked Jul 25 '17 13:07

sam


People also ask

How do I convert text to integer in PostgreSQL?

The PostgreSQL TO_NUMBER() function converts a character string to a numeric value.

What is [] in PostgreSQL?

Array Type. PostgreSQL gives the opportunity to define a column of a table as a variable length single or multidimensional array. Arrays of any built-in or user-defined base type, enum type, or composite type can be created. We will focus on one data type in particular, the Array of text, text[].

Does PostgreSQL support array?

PostgreSQL allows columns of a table to be defined as variable-length multidimensional arrays. Arrays of any built-in or user-defined base type, enum type, composite type, range type, or domain can be created.

How do I convert to PostgreSQL?

PostgreSQL CONVERSION is used to convert between character set encoding. CREATE A CAST defines a new cast on how to convert between two data types. Cast can be EXPLICITLY or IMPLICIT . The behavior is similar to SQL Server's casting, but in PostgreSQL, you can also create your own casts to change the default behavior.


1 Answers

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)

like image 74
a_horse_with_no_name Avatar answered Sep 21 '22 19:09

a_horse_with_no_name