
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
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)
Advertisements