'Comparing values of two columns and return % change postgres

It's seems like i get the correct values but im unsecure.

Is this the correct way to calculate the % change of two columns in postgressql v.10?

    select col1, col2, (col1-col2)/col1 * 100 as percent_change from mytable
having percent_change > 3 or percent_change < -3

In the end i also only want to return rows with a percent range over +-3%



Solution 1:[1]

no, that is not the correct way to calculate the % change in postgresql.

What this is actually doing is returning a float64 value of the difference between col1 and col2 as a FLOAT64 percentage of col1's value.

So in your example, we're calculating percent_change as (col1 - col2) / col1 * 100 = (col1 - col2) * 100 / col1 = (col2/col1-1)*100 and you want to return a decimal type value. So instead you would want to do: (col2-col1)/col1 * 100

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 PJMan0300