
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
Select Field and Handle Nulls with MySQL
For this, use COALESCE(). Let us first create a table −
mysql> create table DemoTable1470 -> ( -> FirstName varchar(20), -> Age int -> ); Query OK, 0 rows affected (0.57 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1470 values('Robert',23); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable1470 values('Bob',NULL); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable1470 values(NULL,25); Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1470;
This will produce the following output −
+-----------+------+ | FirstName | Age | +-----------+------+ | Robert | 23 | | Bob | NULL | | NULL | 25 | +-----------+------+ 3 rows in set (0.00 sec)
Following is the query to select a field and if it's null, select another −
mysql> select coalesce(FirstName,Age) as FirstNameOrAgeValue from DemoTable1470;
This will produce the following output −
+---------------------+ | FirstNameOrAgeValue | +---------------------+ | Robert | | Bob | | 25 | +---------------------+ 3 rows in set (0.00 sec)
Advertisements