Computed / calculated / virtual / derived columns in PostgreSQL

前端 未结 7 1011
爱一瞬间的悲伤
爱一瞬间的悲伤 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:48

    One way to do this is with a trigger!

    CREATE TABLE computed(
        one SERIAL,
        two INT NOT NULL
    );
    
    CREATE OR REPLACE FUNCTION computed_two_trg()
    RETURNS trigger
    LANGUAGE plpgsql
    SECURITY DEFINER
    AS $BODY$
    BEGIN
        NEW.two = NEW.one * 2;
    
        RETURN NEW;
    END
    $BODY$;
    
    CREATE TRIGGER computed_500
    BEFORE INSERT OR UPDATE
    ON computed
    FOR EACH ROW
    EXECUTE PROCEDURE computed_two_trg();
    

    The trigger is fired before the row is updated or inserted. It changes the field that we want to compute of NEW record and then it returns that record.

提交回复
热议问题