Postgresql – How to we sort the words inside a string in PostgreSQL

postgresql-9.6

In my postgresql table one column data is like below

250 TABLETS + PVC + PVDC + ALU + HOSPITAL PACK + Film-coated tablet - BLISTER - [/Tablet] - QUETIAPINE FUMARATE 28.78 mg is present 
20 ML + MATERIAL UNKNOWN + Oral suspension - BOTTLE - [/mL] - ALUMINIUM HYDROXIDE 37 mg; MAGNESIUM HYDROXIDE 40 mg...

How can I split this string based on '+' character and sort this alphabetically and put | character and update the same column?

Best Answer

Considering your table has some ID column, you can get it this way:

with ct as
(
select id,
  unnest(regexp_split_to_array(t, '\+')) part
from
  a
), 
ct2 as
(
select
  id, string_agg(part, '|' order by part) parts
from
  ct
group by
  id
)
update a
set t = ct2.parts
from ct2
where ct2.id = a.id;
id | t                                                                                                                                  
-: | :----------------------------------------------------------------------------------------------------------------------------------
 1 | 250 TABLETS | ALU | Film-coated tablet - BLISTER - [/Tablet] - QUETIAPINE FUMARATE 28.78 mg is present| HOSPITAL PACK | PVC | PVDC 
 2 | 20 ML | MATERIAL UNKNOWN | Oral suspension - BOTTLE - [/mL] - ALUMINIUM HYDROXIDE 37 mg; MAGNESIUM HYDROXIDE 40 mg                 

db<>fiddle here