Reputation: 13110
How do I convert table column data from 'LastName, FirstName' to 'FirstName LastName' in Postgres.
So if the table column contains 'Ona, Lisa' I want it to return 'Lisa Ona'. If the column doesnt contain a ' ,' then I want it to return null. I've been trying to use postgres functions SUBSTRING and REGEXP_REPLACE but cannot get anything working.
Upvotes: 1
Views: 195
Reputation: 13110
Nevermind worked out a solution using SPLIT_PART function
SELECT
t1.sort_name,
split_part(t1.sort_name, ', ', 2)|| ' ' || split_part(t1.sort_name, ', ', 1)
FROM artist t1
WHERE
t1.sort_name LIKE '%, %'
Upvotes: 1
Reputation: 21915
try this
select split_part(name,',',2) ||' '|| split_part(name,',',1) as "thename" from tblname
where name LIKE '%,%'
String Functions and Operators and PostgreSQL SPLIT PART
Upvotes: 0
Reputation: 16487
You need strpos
and substr
functions and a CASE
to return NULL
.
SELECT CASE WHEN strpos(name,', ') > 0
THEN substr(name,strpos(name,', ') + 2) ||' ' || substr(name,0, strpos(name,', '))
ELSE NULL END
FROM person
Upvotes: 2