0

Hi so sorry for I know this just to basic. simple update only using sum on the same table. I need to get

total_tbl 
+-- month1 --- month2 --- month3 --- total --+ 
|     3          3          5                |
|     5          3          5                |
|     3                     4                |
|                5          5                |
+--------------------------------------------+

I need update the total column using SUM.

I have this statement so far:

UPDATE total_tbl SET total = (SELECT SUM(month1,month2,month3))

I should update even if one column doesn't have a value. Thanks!

0

2 Answers 2

2

SUM() is used to sum an expression across multiple rows, usually using GROUP BY. If you want to add expressions in the same row you just use ordinary addition.

Use COALESCE() to provide a default value for null columns.

UPDATE total_tbl
SET total = COALESCE(month1, 0) + COALESCE(month2, 0) + COALESCE(month3, 0)
Sign up to request clarification or add additional context in comments.

Comments

1

You shouldn't need to store this derived information. I would recommend a computed column:

alter table total_tbl
    add column total int -- or the datatype you need
    generated always as (coalesce(month1, 0) + coalesce(month2, 0) + coalesce(month3, 0)) stored

The additional column gives you an always up-to-date perspective at your data. You can even index it of you like, so it can be queried efficiently.

On the other hand, manually maintaining the values would require updating that column every time a value changes on the row, which can get tedious.

Comments

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.