Splitting a comma-separated field in Postgresql and doing a UNION ALL on all the resulting tables

27,986

This should give you the output you're looking for:

SELECT 
    yourTable.ID, 
    regexp_split_to_table(yourTable.fruits, E',') AS split_fruits
FROM yourTable

EDIT: Fixed the regex.

Share:
27,986

Related videos on Youtube

John Horton
Author by

John Horton

Updated on February 11, 2020

Comments

  • John Horton
    John Horton over 4 years

    I have a table that contains a field of comma separated strings:

    ID | fruits
    -----------
    1  | cherry,apple,grape 
    2  | apple,orange,peach 
    

    I want to create a normalized version of the table, like this:

    ID | fruits
    -----------
    1  | cherry 
    1  | apple 
    1  | grape
    2  | apple 
    2  | orange 
    2  | peach 
    

    The postgresql 8.4 documentation describes a regexp_split_to_table function that can turn a single table:

    SELECT foo 
    FROM regexp_split_to_table('the quick brown fox jumped over the lazy dog',E'\\s+') AS
    foo;
    

    which gives you this:

      foo   
    --------
      the    
      quick  
      brown  
      fox    
      jumped 
      over   
      the    
      lazy   
      dog    
     (9 rows)
    

    But that is just for a single field. What I want to do is some kind UNION applied to all the tables generated by splitting each field. Thank you.

  • Admin
    Admin over 7 years
    can you please help me with stackoverflow.com/questions/40005974/…
  • Admin
    Admin over 7 years
    i tried SELECT CATEGORI.ID, regexp_split_to_table(CATEGORI.CATEGORY, E',') AS split_fruits FROM CATEGORI;
  • Admin
    Admin over 7 years
    it works but i want to filter duplicate data from it
  • BERA
    BERA over 2 years
    What's the E for?