MySQL case statement inside a select statement?


For this, you can use CASE WHEN statement. Let us first create a table −

mysql> create table DemoTable
   -> (
   -> FirstName varchar(20),
   -> Score int
   -> );
Query OK, 0 rows affected (0.63 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('John',46);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('John',78);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('John',69);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Chris',78);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('Chris',89);
Query OK, 1 row affected (0.17 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-----------+-------+
| FirstName | Score |
+-----------+-------+
| John      |    46 |
| John      |    78 |
| John      |    69 |
| Chris     |    78 |
| Chris     |    89 |
+-----------+-------+
5 rows in set (0.00 sec)

Following is the query to implement case statement inside a select statement −

mysql> select FirstName,max(case when Score=69 then 1 else 0 end ) as isExistsOrNot
   -> from DemoTable
   -> group by FirstName;

This will produce the following output −

+-----------+---------------+
| FirstName | isExistsOrNot |
+-----------+---------------+
| John      |             1 |
| Chris     |             0 |
+-----------+---------------+
2 rows in set (0.00 sec)

Updated on: 12-Dec-2019

296 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements