Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

102
Visualizações
Transform PSQL rows into arrays?

I have a postgresql database containing a table that looks something like this simplified example:

Name  Pets            Hobbies
Jhon  Dog, Cat, Cat   Music
Jane  Dog             Sports, Music
Dan   Dog, Turtle     Reading, Sports, VideoGames
Lia   Cat, Cat        VideoGames, Sports

As you can see, in this example I have 3 columns, 2 of them containg some strings separated by commas. What I would like to do is to get that values into arrays, so if I do something like:

SELECT
    Name,
    Pets,
    Hobbies
FROM
    examples_table;

I get an output like this (having the contents of the rows with multiple values in arrays):

Name  Pets              Hobbies
Jhon  {Dog, Cat, Cat}   {Music}
Jane  {Dog}             {Sports, Music}
Dan   {Dog, Turtle}     {Reading, Sports, VideoGames}
Lia   {Cat, Cat}        {VideoGames, Sports}

So that way I can access to the contents I want easily (for example, if I want to access who has Cat as Pets). I know this is a possible thing to do on PostgreSQL, but i don't know how to do it (also I'm currently working on psql version 12 on an Ubuntu device). Thanks!

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

The built-in string_to_array() will handle this for you:

select name,
       string_to_array(pets, ', ') as pets,
       string_to_array(hobbies, ', ') as hobbies
  from examples_table;

If you want to change the table in-place:

alter table examples_table
  alter column pets type text[]
    using string_to_array(pets, ', '),
  alter column hobbies type text[]
    using string_to_array(hobbies, ', ');
over 4 years ago · Santiago Trujillo Relatório

0

Try this:

select 
name, 
regexp_split_to_array(pets,', '),
regexp_split_to_array(hobbies,', ') from example

or

select 
name, 
string_to_array(pets,', '), 
string_to_array(hobbies,', ') 
from example

EDIT for your comment's requirement run this:

update  example set 
       pets=regexp_split_to_array(pets, ', ') ,
       hobbies=regexp_split_to_array(hobbies, ', ') 
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda