
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Replace Values in a MySQL Table
To replace values in a table, use the CASE statement. To understand the concept, let us create a table. The query to create a table is as follows
mysql> create table replaceValueDemo -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Name varchar(10), -> isGreaterThan18 varchar(10) -> ); Query OK, 0 rows affected (0.49 sec)
Insert some records in the table using insert command.
The query is as follows
mysql> insert into replaceValueDemo(Name,isGreaterThan18) values('John','YES'); Query OK, 1 row affected (0.24 sec) mysql> insert into replaceValueDemo(Name,isGreaterThan18) values('Carol','NO'); Query OK, 1 row affected (0.16 sec) mysql> insert into replaceValueDemo(Name,isGreaterThan18) values('Mike','YES'); Query OK, 1 row affected (0.20 sec) mysql> insert into replaceValueDemo(Name,isGreaterThan18) values('Bob','YES'); Query OK, 1 row affected (0.17 sec) mysql> insert into replaceValueDemo(Name,isGreaterThan18) values('Larry','NO'); Query OK, 1 row affected (0.09 sec) mysql> insert into replaceValueDemo(Name,isGreaterThan18) values('David','NO'); Query OK, 1 row affected (0.11 sec) mysql> insert into replaceValueDemo(Name,isGreaterThan18) values('James','DONOTKNOW'); Query OK, 1 row affected (0.14 sec) mysql> insert into replaceValueDemo(Name,isGreaterThan18) values('Robert','DONOTKNOW'); Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement.
The query is as follows
mysql> select *from replaceValueDemo;
The following is the output
+----+--------+-----------------+ | Id | Name | isGreaterThan18 | +----+--------+-----------------+ | 1 | John | YES | | 2 | Carol | NO | | 3 | Mike | YES | | 4 | Bob | YES | | 5 | Larry | NO | | 6 | David | NO | | 7 | James | DONOTKNOW | | 8 | Robert | DONOTKNOW | +----+--------+-----------------+ 8 rows in set (0.00 sec)
Here is the query to replace values in a MySQL table
mysql> update replaceValueDemo set isGreaterThan18=case when isGreaterThan18='YES' THEN 'NO' ELSE 'YES' END -> where isGreaterThan18 IN('YES','NO'); Query OK, 6 rows affected (0.19 sec) Rows matched: 6 Changed: 6 Warnings: 0
Let us check the table records once again.
The query is as follows
mysql> select *from replaceValueDemo;
The following is the output with the replaced values
+----+--------+-----------------+ | Id | Name | isGreaterThan18 | +----+--------+-----------------+ | 1 | John | NO | | 2 | Carol | YES | | 3 | Mike | NO | | 4 | Bob | NO | | 5 | Larry | YES | | 6 | David | YES | | 7 | James | DONOTKNOW | | 8 | Robert | DONOTKNOW | +----+--------+-----------------+ 8 rows in set (0.00 sec)
Advertisements