- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MySQL query to decrease the value of a specific record to zero?
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