简体   繁体   中英

Postgres: Generated column with parenthesis operation

I wanna add a generated column in my PostgreSQL table. The problem is when I use operation with parenthesis, I got zero results.

ALTER TABLE my_table 
add COLUMN my_column decimal(4,3) GENERATED ALWAYS AS ((price-buy_price)/price) STORED;

All the result in my_column is 0.000. Then I try to avoid the parenthesis in my operation so my query looks like:

ALTER TABLE my_table 
add COLUMN my_column2 decimal(4,3) GENERATED ALWAYS AS (price-buy_price/price) STORED;

That's work but the result is not what I want. I wonder why it fails every time I use parenthesis and it works when I do operations like (a+b) or (a+b/c) or (a*bc/d) etc.

Is anyone has the solution? Thank you.

If your columns are integer columns the division is also an integer division leaving you with no decimal digits. You need to cast at least one of the expressions in the division:

ALTER TABLE my_table 
   add my_column decimal(4,3)  
      GENERATED ALWAYS AS ( (price-buy_price) / price::numeric) STORED;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM