Tutorialspoint

MySQL query to decrease the value of a specific record to zero?


1 Answer
Anvi Jain

Use SET to decrease the value and WHERE to set the condition for a specific record to be 0. Let us first create a table −

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

Insert some records in the table using insert command &minus

mysql> insert into DemoTable(Number) values(10);
Query OK, 1 row affected (0.20 sec)

mysql> insert into DemoTable(Number) values(20);
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable(Number) values(1);
Query OK, 1 row affected (0.10 sec)

mysql> insert into DemoTable(Number) values(0);
Query OK, 1 row affected (0.12 sec)

mysql> insert into DemoTable(Number) values(-1);
Query OK, 1 row affected (0.39 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+--------+
| Id | Number |
+----+--------+
|  1 |     10 |
|  2 |     20 |
|  3 |      1 |
|  4 |      0 |
|  5 |     -1 |
+----+--------+
5 rows in set (0.00 sec)

Following is the query to decrease the value to 0 −

mysql> update DemoTable
   set Number = Number-1
   where Id = 3 AND Number > 0;
Query OK, 1 row affected (0.20 sec)
Rows matched: 1 Changed: 1 Warnings: 0

Let us display table records once again −

mysql> select *from DemoTable;

This will produce the following output. Now, record with Id 3 is 0 since we decremented it by 1 −

+----+--------+
| Id | Number |
+----+--------+
|  1 |     10 |
|  2 |     20 |
|  3 |      0 |
|  4 |      0 |
|  5 |     -1 |
+----+--------+
5 rows in set (0.00 sec)

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.