I have a temporary table in a PostgreSQL function and I want to insert a new VARCHAR column. It should have a value that depends on another column of the table, named “amount”.
When the amount is positive I would like the value of the column row to be credit and when the value is negative the column should be debit.
I have one more request: I want to round the value of amount column in 2 decimal digits
You want
ALTER TABLE ... ADD COLUMNfollowed by anUPDATE.I initially said
ALTER TABLE ... ADD COLUMN ... USINGbut that was wrong on two counts.ADD COLUMNtakes aDEFAULTnotUSING– and You can’t do it in one pass because neither aDEFAULTexpression nor aUSINGexpression may not refer to other columns.So you must do:
Think carefully about whether zero should be ‘Debit’ or ‘Credit’ and adjust the
CASEaccordingly.For rounding, use
round(amount,2). There isn’t enough detail in your question for me to be sure how; probably byUPDATEing the temp table withUPDATE thetable SET amount = round(amount,2)but without the context it’s hard to know if that’s right. That statement irreversibly throws information away so it should only be used on a copy of the data.