- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
CASE WHEN column1 IS NULL THEN NULL ELSE column2 END with MySQL
For this, you can use the CASE statement. Let us first create a table−
mysql> create table DemoTable -> ( -> Name varchar(20), -> Marks1 int, -> Marks2 int -> ); Query OK, 0 rows affected (0.72 sec)
Insert some records in the table using insert command−
mysql> insert into DemoTable values('Chris',45,null); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('David',null,78); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values('Bob',67,98); Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------+--------+--------+ | Name | Marks1 | Marks2 | +-------+--------+--------+ | Chris | 45 | NULL | | David | NULL | 78 | | Bob | 67 | 98 | +-------+--------+--------+ 3 rows in set (0.00 sec)
Here is the query to implement CASE WHEN −
mysql> select *, -> (case when Marks1 is null then null else Marks2 end ) as Value -> from DemoTable;
This will produce the following output −
+-------+--------+--------+-------+ | Name | Marks1 | Marks2 | Value | +-------+--------+--------+-------+ | Chris | 45 | NULL | NULL | | David | NULL | 78 | NULL | | Bob | 67 | 98 | 98 | +-------+--------+--------+-------+ 3 rows in set (0.00 sec)
Advertisements