Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update statement using current value of the table

Tags:

sql

oracle

I want to update a row in a table by incrementing by one the integer value of one of the field..

The current doesn't work, why?

Update htmIndex SET numObs = numObs+1 where ...
like image 444
Acibi Avatar asked Jul 05 '10 10:07

Acibi


1 Answers

Simple case, update one row:

SQL> select name
  2         , age
  3  from t23
  4  where id = 2
  5  /

NAME                AGE
------------ ----------
MR KNOX              47

SQL> update t23
  2  set age = age + 6
  3  where id = 2
  4  /

1 row updated.

SQL> select name
  2         , age
  3  from t23
  4  where id = 2
  5  /

NAME                AGE
------------ ----------
MR KNOX              53

SQL>

Update a row when the column has a null value:

SQL> select name
  2         , age
  3  from t23
  4  where id = 6
  5  /

NAME                AGE
------------ ----------
SALLY

SQL> update t23
  2  set age=age+5
  3  where id = 6
  4  /

1 row updated.

SQL> select name
  2         , age
  3  from t23
  4  where id = 6
  5  /

NAME                AGE
------------ ----------
SALLY

SQL> update t23
  2  set age = nvl(age,0) +5
  3  where id = 6
  4  /

1 row updated.

SQL> select name
  2         , age
  3  from t23
  4  where id = 6
  5  /

NAME                AGE
------------ ----------
SALLY                 5

SQL>

Equally straightforward when updating multiple rows:

 SQL> select name
   2         , age
   3  from t23
   4  where age > 20
   5  /

 NAME                AGE
 ------------ ----------
 MR KNOX              53
 FOX IN SOCKS         37
 CAT                  23
 LORAX               443

 SQL> update t23
   2  set age = age + 1
   3  where age > 20
   4  /

 4 rows updated.

 SQL> select name
   2         , age
   3  from t23
   4  where age > 20
   5  /

 NAME                AGE
 ------------ ----------
 MR KNOX              54
 FOX IN SOCKS         38
 CAT                  24
 LORAX               444

SQL>
like image 144
APC Avatar answered Oct 14 '22 06:10

APC