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)

Updated on: 30-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements