0

I have a table in PostgreSQL with following values.

col1
; substrate
positive allosteric modulator
inducer; substrate

I would like to split the row values by ';' into multiple columns. As per my understanding, split_part() function works only for fix number of values.

How can I get the below output?

col1                                col2                            col3
; substrate                                                         substrate                            
positive allosteric modulator       positive allosteric modulator
inducer; substrate                  inducer                         substrate

Thanks

0

1 Answer 1

1

You can split it into an array, then access each array element:

select col1,
       elements[1] as col2, 
       elements[2] as col3
from (
  select col1, regexp_split_to_array(col1, '\s*;\s*') as elements
  from the_table
) t  
Sign up to request clarification or add additional context in comments.

2 Comments

What if I do not know the maximum number of array elements?
@rshar: you have to use some value. One fundamental restriction of SQL is, that the number, names and data type of all columns of a query must be known before the query is started. You can't have a dynamic number of columns.

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.