PostgreSQL – Insert Sum of Row Data into Separate Column

postgresql

I have a table

   id   name     class  social  science math  Total
    2   Max      Three  85        56     85
    3   Arnold   Three  55        40     75
    4   Krish    Four   60        50     70
    5   John     Four   60        80     90

I have to find total of each student's marks and insert to column Total.

While running this query –

INSERT INTO student(Total)    
SELECT (social + math + science ) as Total from student;

I am getting in this format –

   id   name     class  social  science math  Total
    2   Max      Three  85        56     85
    3   Arnold   Three  55        40     75
    4   Krish    Four   60        50     70
    5   John     Four   60        80     90
    6                                          226
    7                                          170
    8                                          180
    9                                          230

How to correct this I am not getting.

Best Answer

Use an UPDATE statement.

update student 
   set total = social + math + science;

But that column is totally useless. In general you should not store data in a database that can easily be derived from existing values.

In your, adding the values of the three columns adds no (noticeable) overhead to a select statement, so there is no point in storing the total.

You should rather remove the column completely and then create a view doing this for you. Otherwise you need to update that column each time one of the other three columns are changed.

create view total_score
as
select id, name, class, social, science, math, 
       social + math + science as total
from student;

Plus: your name column should be defined as NOT NULL.