How to subtract by 1 if the field value > 0 in MySQL?

MySQLMySQLi Database

You can use CASE statement with UPDATE command for this. Let us first create a table −

mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Value int
);
Query OK, 0 rows affected (1.44 sec)

Insert records in the table using insert command −

mysql> insert into DemoTable(Value) values(100);
Query OK, 1 row affected (0.47 sec)
mysql> insert into DemoTable(Value) values(0);
Query OK, 1 row affected (4.16 sec)
mysql> insert into DemoTable(Value) values(104);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable(Value) values(0);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(Value) values(5);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable(Value) values(10);
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable(Value) values(0);
Query OK, 1 row affected (0.18 sec)

Display records from the table using select command −

mysql> select *from DemoTable;

This will produce the following output −

+----+-------+
| Id | Value |
+----+-------+
| 1  | 100   |
| 2  | 0     |
| 3  | 104   |
| 4  | 0     |
| 5  | 5     |
| 6  | 10    |
| 7  | 0     |
+----+-------+
7 rows in set (0.00 sec)

Now use to set the condition to subtract if the field value is more than 0 if field value > 0, else let it remain the same −

mysql> update DemoTable set Value=CASE WHEN Value > 0 THEN Value-1 ELSE 0 END;
Query OK, 4 rows affected (0.25 sec)
Rows matched: 7 Changed: 4 Warnings: 0

Let us check table records once again −

mysql> select *from DemoTable;

This will produce the following output −

+----+-------+
| Id | Value |
+----+-------+
| 1  | 99    |
| 2  | 0     |
| 3  | 103   |
| 4  | 0     |
| 5  | 4     |
| 6  | 9     |
| 7  | 0     |
+----+-------+
7 rows in set (0.00 sec)
raja
Published on 29-Apr-2019 12:14:59
Advertisements