- 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
Add a new column and set values in it on the basis of conditions in MySQL?
To set values on the basis of conditions, use IF() method. Let us first create a table −
mysql> create table DemoTable -> ( -> Age int -> ); Query OK, 0 rows affected (0.55 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(19); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable values(16); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values(17); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values(22); Query OK, 1 row affected (0.19 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
Ouptut
This will produce the following output −
+------+ | Age | +------+ | 19 | | 16 | | 17 | | 22 | +------+ 4 rows in set (0.00 sec)
Following is the query to set values on the basis of condition −
mysql> select Age,if(Age > 18,'You are qualified!','Sorry, you are rejected!') AS Result from DemoTable;
Output
This will produce the following output −
+------+-------------------------+ | Age | Result | +------+-------------------------+ | 19 | You are qualified! | | 16 | Sorry, you are rejected!| | 17 | Sorry, you are rejected!| | 22 | You are qualified! | +------+-------------------------+ 4 rows in set (0.00 sec)
Advertisements
To Continue Learning Please Login
Login with Google