Split string on first space occurance in PostgreSQL?

Viewed 1307

I have a column that contains first and last names like these.

word1 word2
word1 word2 word3
word1 word2

I need to split string on first space occurance.

|word1| |word2|
|word1| |word2| |word3|
|word1| |word2|

can someone help me thanks

4 Answers

You split the column into an array:

select string_to_array(words, ' ') as words_array

You can put this in separate columns if you like, but I would move the string_to_array() to the from clause:

select word_array[1], word_array[2], word_array[3]
from t cross join lateral
     (values (string_to_array(t.words, ' '))) v(word_array)

For a fixed maximum number of elements per string, you can use split_part()`:

select 
    split_part(col, ' ', 1) as word1, 
    split_part(col, ' ', 2) as word2,
    split_part(col, ' ', 3) as word3
from mytable

An alternative uses arrays:

select x.arr[1] as word1, x.arr[2] as word2, x.arr[3] as word3 
from mytable t
cross join lateral (values (string_to_array(t.col, ' '))) x(arr)

This might be more efficient because the string is parsed only once.

It depends on how many words there are in the sentence, for the first word it is simple I think.

SELECT split_part(colName,' ',1);

For everything else after the first space it becomes a bit more complicated. You can use math or regular expression. I think something like good old math can work.

SELECT substring(colname,(length(split_part(colname,' ',1)))+2,(length(colname)) - (length(split_part(colname,' ',1))+1));

Or you can use the function select regexp_replace with regular expression

Based on @Alessio answer, I improved its query to be compatible with row that have only one element like, because its query crash in this case :

word1
word1 word2
word1 word2 word3

to be splitted as :

word1 | NULL
word1 | word2
word1 | word2 word3

The query is :

UPDATE "my_table" SET "col_1" = split_part("col_name", ' ', 1)), "col_2" = substring("col_name",(length(split_part("col_name",' ',1)))+1,(length("col_name")) - (length(split_part("col_name",' ',1))))
Related