Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update one column as sum of other two columns

I need to update each row of a table with one column as sum of other two columns in the same table

Something like this

UPDATE table1 SET table1.column1 = sum (table1.column1 + table1.column2) for every row

I have tried

This is working for me

UPDATE table1 SET column1 =(SELECT  SUM(column1 + column2)  FROM table1 where rowid = 1) WHERE rowid = 1

So I can do this by iterating each rowid by first selecting all rowId

for( all rowid as i){
    UPDATE table1 SET column1 =(SELECT  SUM(column1 + column2)  FROM table1 where rowid = i) WHERE rowid = i
    }

But I need to do for all the rows in that table in one query

When I tried:

update table1  set column1  = (select (column1  + column2) from table1 )

this will summ all the values of column1 and column2 i want to do wrt to a row

Any idea?

Me working in sqLite for Android

like image 477
Labeeb Panampullan Avatar asked Feb 09 '12 15:02

Labeeb Panampullan


3 Answers

There's no need for loops or inner selects. Just try this:

UPDATE table1 SET column1 = column1 + column2
like image 143
Mark Byers Avatar answered Nov 05 '22 16:11

Mark Byers


It's allowed to read from columns in the set clause:

UPDATE  table1 
SET     column1 = column1 + column2
WHERE   rowid = 1
like image 28
Andomar Avatar answered Nov 05 '22 16:11

Andomar


For all the rows you need not WHERE predicate:

UPDATE table SET
  column1 = column1+column2

thats all.

like image 3
Oleg Dok Avatar answered Nov 05 '22 16:11

Oleg Dok