How can I create a column in postgres from values and selections based on other columns?

后端 未结 3 2067
孤街浪徒
孤街浪徒 2021-02-07 13:21

I want to create a new field (or two) in my table that is a concatenation of other fields, which seems relatively straightforward. But what is the case syntax or

3条回答
  •  無奈伤痛
    2021-02-07 13:49

    I recommend a "generated" column rather than storing the data redundantly. It will take less space on disk, which is likely to actually make it faster than storing the generated value, and will certainly be less prone to accidentally falling out of sync with the base data. Assuming you like the format provided by @vyegorov, You could create a function like this, using the record type of your table (which matches the table name) as input:

    CREATE FUNCTION adesc(rec atab)
      RETURNS text
      IMMUTABLE
      LANGUAGE SQL
    AS $$
    SELECT to_char($1.gpa, 'FM09.0') AS gpa_txt,
           $1.name||'-'||$1.major||'-Grade'||
      CASE WHEN $1.gpa >= 3.3 THEN 'A'
           WHEN $1.gpa > 2.7 AND $1.gpa < 3.3 THEN 'B'
           WHEN $1.gpa > 0 THEN 'C'
           ELSE 'F' END || '-' || to_char($1.gpa, 'FM09.0') AS adesc;
    $$;
    

    You would need to reference this using a relation qualifier (the table name or an alias). When such a reference is not resolved by finding an actual column, PostgreSQL will look for a function taking the table's record type as its only parameter. So you would be able to do something like this:

    SELECT name, major, gpa, atab.adesc
      FROM atab;
    

    Such a "generated column" can be used in indexes for fast searching, if that's what you're after, with something like adesc(atab).*.

提交回复
热议问题