
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
Implement CASE Statement with WHEN Clause in MySQL
Let us first create a table −
mysql> create table DemoTable ( UserId int, UserName varchar(100) ); Query OK, 0 rows affected (0.57 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(100,'Chris'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(101,'Robert'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values(102,'David'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values(103,'Mike'); Query OK, 1 row affected (0.11 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+--------+----------+ | UserId | UserName | +--------+----------+ | 100 | Chris | | 101 | Robert | | 102 | David | | 103 | Mike | +--------+----------+ 4 rows in set (0.00 sec)
Following is the query for CASE WHEN −
mysql> select case when exists(select * from DemoTable where UserId=102) then 'Present' else 'Not Present' end as Result;
This will produce the following output −
+---------+ | Result | +---------+ | Present | +---------+ 1 row in set (0.02 sec)
Advertisements