Computed / calculated / virtual / derived columns in PostgreSQL

前端 未结 7 1101
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 06:16

Does PostgreSQL support computed / calculated columns, like MS SQL Server? I can\'t find anything in the docs, but as this feature is included in many other DBMSs I thought

7条回答
  •  不知归路
    2020-11-22 06:55

    YES you can!! The solution should be easy, safe, and performant...

    I'm new to postgresql, but it seems you can create computed columns by using an expression index, paired with a view (the view is optional, but makes makes life a bit easier).

    Suppose my computation is md5(some_string_field), then I create the index as:

    CREATE INDEX some_string_field_md5_index ON some_table(MD5(some_string_field));
    

    Now, any queries that act on MD5(some_string_field) will use the index rather than computing it from scratch. For example:

    SELECT MAX(some_field) FROM some_table GROUP BY MD5(some_string_field);
    

    You can check this with explain.

    However at this point you are relying on users of the table knowing exactly how to construct the column. To make life easier, you can create a VIEW onto an augmented version of the original table, adding in the computed value as a new column:

    CREATE VIEW some_table_augmented AS 
       SELECT *, MD5(some_string_field) as some_string_field_md5 from some_table;
    

    Now any queries using some_table_augmented will be able to use some_string_field_md5 without worrying about how it works..they just get good performance. The view doesn't copy any data from the original table, so it is good memory-wise as well as performance-wise. Note however that you can't update/insert into a view, only into the source table, but if you really want, I believe you can redirect inserts and updates to the source table using rules (I could be wrong on that last point as I've never tried it myself).

    Edit: it seems if the query involves competing indices, the planner engine may sometimes not use the expression-index at all. The choice seems to be data dependant.

提交回复
热议问题