- 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
Select different fields in MySQL even if a field is set to null?
For this, you can use COALESCE(). Let us first create a table −
mysql> create table DemoTable1336 -> ( -> FirstName varchar(20) -> , -> SecondName varchar(20) -> ); Query OK, 0 rows affected (0.64 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1336 values('John',NULL); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable1336 values(NULL,'Chris'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable1336 values('David','Mike'); Query OK, 1 row affected (0.18 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1336;
This will produce the following output −
+-----------+------------+ | FirstName | SecondName | +-----------+------------+ | John | NULL | | NULL | Chris | | David | Mike | +-----------+------------+ 3 rows in set (0.00 sec)
Following is the query to select different fields in MySQL even if a field is set to null −
mysql> select coalesce(FirstName,SecondName) as AlternateName from DemoTable1336;
This will produce the following output −
+---------------+ | AlternateName | +---------------+ | John | | Chris | | David | +---------------+ 3 rows in set (0.00 sec)
Advertisements