How to update a MySQL column by subtracting a value with some conditions?


Let us first create a table −

mysql> create table DemoTable
(
   Score int
);
Query OK, 0 rows affected (0.65 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(45);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(29);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(56);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values(24);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values(32);
Query OK, 1 row affected (0.09 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-------+
| Score |
+-------+
|    45 |
|    29 |
|    56 |
|    24 |
|    32 |
+-------+
5 rows in set (0.00 sec)

Following is the query to update MySQL column by subtracting a value with some conditions −

mysql> update DemoTable set Score=Score-2 where Score > 30;
Query OK, 3 rows affected (0.14 sec)
Rows matched: 3 Changed: 3 Warnings: 0

Let us check the table records once again −

mysql> select *from DemoTable;

This will produce the following output −

+-------+
| Score |
+-------+
|    43 |
|    29 |
|    54 |
|    24 |
|    30 |
+-------+
5 rows in set (0.00 sec)

Updated on: 24-Sep-2019

717 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements