Add some value to an int type column value in a table without knowing its current value in SQL?


For this, simply use UPDATE command along with SET. Let us first create a table −

mysql> create table DemoTable
(
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentScore int
);
Query OK, 0 rows affected (0.81 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(StudentScore) values(78);
Query OK, 1 row affected (0.46 sec)
mysql> insert into DemoTable(StudentScore) values(89);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(StudentScore) values(67);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(StudentScore) values(95);
Query OK, 1 row affected (0.25 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-----------+--------------+
| StudentId | StudentScore |
+-----------+--------------+
|         1 |           78 |
|         2 |           89 |
|         3 |           67 |
|         4 |           95 |
+-----------+--------------+
4 rows in set (0.00 sec)

Following is the query to add some value to an int in a database without knowing its current value −

mysql> update DemoTable
   set StudentScore=StudentScore+21
   where StudentId=3;
Query OK, 1 row affected (0.22 sec)
Rows matched : 1 Changed : 1 Warnings : 0

Let us check the table records once again −

mysql> select *from DemoTable;

This will produce the following output −

+-----------+--------------+
| StudentId | StudentScore |
+-----------+--------------+
|         1 |           78 |
|         2 |           89 |
|         3 |           88 |
|         4 |           95 |
+-----------+--------------+
4 rows in set (0.00 sec)

Updated on: 07-Oct-2019

90 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements