1

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*b-c/d) etc.

Is anyone has the solution? Thank you.

5
  • 1
    @DaleK Oh? Sorry I am new at DB management and don't know the difference between that. Ok, I will edit my question, thank you for the suggestion. Commented May 20, 2020 at 4:38
  • 1
    Can't reproduce: dbfiddle.uk/… Commented May 20, 2020 at 4:45
  • @Nick Ah, my column type of price and buy_price are an integer. I think that's why I got zero results. Let's check <dbfiddle.uk/…> Commented May 20, 2020 at 4:52
  • Yup, that's the problem. Changing the formula to (1.0 * (price-buy_price)/price) solves it: dbfiddle.uk/… Commented May 20, 2020 at 4:53
  • No worries - glad to help Commented May 20, 2020 at 4:57

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

2 Comments

Cool, that's also work. But what the difference if multiplied by 1.0? like (1.0 * (price-buy_price)/price)
@HermawanWiwid: no real difference, just different coding style. The 1.0 * also forces a non-integer expression (because 1.0 is a float constant)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.