- 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
SET only two values for all the rows in a MySQL table based on conditions?
For condition based update, use UPDATE and IF(). Let us first create a table −
mysql> create table DemoTable ( Value int ); Query OK, 0 rows affected (0.47 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(10); Query OK, 1 row affected (0.08 sec) mysql> insert into DemoTable values(20); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values(10); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values(20); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values(30); Query OK, 1 row affected (0.10 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------+ | Value | +-------+ | 10 | | 20 | | 10 | | 20 | | 30 | +-------+ 5 rows in set (0.00 sec)
Following is the query to update based on a condition −
mysql> update DemoTable set Value=if(Value=10,20,10); Query OK, 5 rows affected (0.20 sec) Rows matched: 5 Changed: 5 Warnings: 0
Let us check the table records once again −
mysql> select *from DemoTable;
This will produce the following output −
+-------+ | Value | +-------+ | 20 | | 10 | | 20 | | 10 | | 10 | +-------+ 5 rows in set (0.00 sec)
Advertisements