- 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
MySQL CASE statement to place custom values in place of NULL
Let us first create a table −
mysql> create table DemoTable ( FirstName varchar(20) ); Query OK, 0 rows affected (1.15 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('John'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values(NULL); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values('Adam'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(NULL); Query OK, 1 row affected (0.09 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+ | FirstName | +-----------+ | John | | NULL | | Adam | | NULL | +-----------+ 4 rows in set (0.00 sec)
Let us now use CASE statement −
mysql> select case when FirstName is NULL then 'UNKNOWN NAME' else FirstName end AS FirstName from DemoTable;
This will produce the following output −
+--------------+ | FirstName | +--------------+ | John | | UNKNOWN NAME | | Adam | | UNKNOWN NAME | +--------------+ 4 rows in set (0.00 sec)
We can also get the same results using IFNULL() −
mysql> select IFNULL(FirstName,'UNKNOWN NAME') AS FirstName from DemoTable;
This will produce the following output −
+--------------+ | FirstName | +--------------+ | John | | UNKNOWN NAME | | Adam | | UNKNOWN NAME | +--------------+ 4 rows in set (0.00 sec)
Advertisements