PostgreSQL: creating a generated column

2019-08-19 00:13发布

Goal:

My goal is to create a new column called paymentPricewhich is the sum of receiptPrice, platformFee, delivererFee (which needs to display the sum of the current values).

From reading the docs I thought using a generated column would be thebest way to achieve this.

Syntax:

ALTER TABLE
   "orders"
ADD
   "paymentPrice" FLOAT GENERATED ALWAYS AS (orders."receiptPrice" + orders."platformFee" + orders."delivererFee") VIRTUAL;'

Error:

My current syntax results in the following error, but I can't figure out what I'm doing wrong

error: syntax error at or near "("

1条回答
走好不送
2楼-- · 2019-08-19 00:38

As noted above in the comments - generated columns will be available in Postgres 12.

It is possible to fake a generated column with a function in versions < 12:

https://www.db-fiddle.com/f/21FtTGSuTXzZxoQX9CRUZf/0

CREATE TABLE orders (
    receiptPrice INT,
    platformFee INT,
    delivererFee INT
);

CREATE OR REPLACE FUNCTION paymentPrice(_order orders) 
RETURNS integer AS $$
  SELECT ( _order.receiptPrice + _order.platformFee + _order.delivererFee)
$$ 
LANGUAGE SQL;
SELECT paymentPrice(orders) FROM orders;

I guess a use case for this would be, if some other tooling depends on it (use cases for me where tools like https://github.com/graphile/postgraphile) or if the queries should be less verbose.

查看更多
登录 后发表回答