You can decrement value in MySQL with update command. With this, you can also restrict the value to not reach below 0.
The syntax is as follows −
update yourTableName set yourColumnName = yourColumnName - 1 where yourColumnName > 0;
To avoid the value to go below zero, you can use yourColumnName > 0.
To understand the above syntax, let us create a table. The query to create a table.
mysql> create table DecrementDemo −> ( −> DecrementValue int −> ); Query OK, 0 rows affected (0.62 sec)
Insert some records in the table with insert statement. The query is as follows −
mysql> insert into DecrementDemo values(15),(14),(13),(12),(11),(10); Query OK, 6 rows affected (0.18 sec) Records: 6 Duplicates: 0 Warnings: 0
Now you can display all records from table with the help of select statement. The query is as follows −
mysql> select *from DecrementDemo;
The following is the output −
+----------------+ | DecrementValue | +----------------+ | 15 | | 14 | | 13 | | 12 | | 11 | | 10 | +----------------+ 6 rows in set (0.00 sec)
Here is the query to decrement value from a table −
mysql> update DecrementDemo −> set DecrementValue = DecrementValue - 1 where DecrementValue > 0; Query OK, 6 rows affected (0.16 sec) Rows matched: 6 Changed: 6 Warnings: 0
Check whether the value decremented or not using the following query −
mysql> select *from DecrementDemo;
The following is the output −
+----------------+ | DecrementValue | +----------------+ | 14 | | 13 | | 12 | | 11 | | 10 | | 9 | +----------------+ 6 rows in set (0.00 sec)