MySQL query to return a string as a result of IF statement?


Let us first create a table −

mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   EmployeeSalary int
);
Query OK, 0 rows affected (1.68 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(EmployeeSalary) values(12000);
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable(EmployeeSalary) values(20000);
Query OK, 1 row affected (0.55 sec)
mysql> insert into DemoTable(EmployeeSalary) values(11500);
Query OK, 1 row affected (0.94 sec)
mysql> insert into DemoTable(EmployeeSalary) values(15500);
Query OK, 1 row affected (0.44 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+----------------+
| Id | EmployeeSalary |
+----+----------------+
|  1 | 12000          |
|  2 | 20000          |
|  3 | 11500          |
|  4 | 15500          |
+----+----------------+
4 rows in set (0.00 sec)

Following is the query to return a string as a result of IF statement −

mysql> select Id,if(EmployeeSalary <= 12000 ,'Internship Employee','FullTime Employee') as status from DemoTable;

This will produce the following output −

+----+---------------------+
| Id | status              |
+----+---------------------+
|  1 | Internship Employee |
|  2 | FullTime Employee   |
|  3 | Internship Employee |
|  4 | FullTime Employee   |
+----+---------------------+
4 rows in set (0.00 sec)

Updated on: 07-Oct-2019

335 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements