Append text to column data based on the column in PostgreSQL

The accepted answer is not handle null value and blank space. So I gave this answer. If it help someone, it will be my pleasure.

update "public"."mytable" set 
"name"= case when "name" is null or trim("name")='' then null else 'a' || "name" end,
"age"= case when "age" is null or trim("age")='' then null else 'b' || "age" end,
"location"= case when "location" is null or trim("location")='' then null else 'c' || "location" end;

First you have to transform your age to be some kind of string. After that you can transform the values like this (of course you have to do this for each field):

update mytable set name = 'a' || name, age = 'b' || age;

This updates the data inside your table. If you only want the output to be prefixed you can use the following approach:

select 'a' || name as name, 'b' || age as age from mytable;

In this case there is no need to convert your age data type.

Tags:

Postgresql