Reputation: 4756
Goal:
My goal is to create a new column called paymentPrice
which 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 "("
Upvotes: 1
Views: 3059
Reputation: 8490
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)
$$
STABLE
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.
Upvotes: 2