Append text to column data based on the column in PostgreSQL

前端 未结 2 1470
生来不讨喜
生来不讨喜 2021-02-02 06:33

I would like to append some text to every cell in each column of my table to act as a symbol for that particular column. For example say my table is as follows (all fields are t

相关标签:
2条回答
  • 2021-02-02 06:45

    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;
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题