
- Learn MySQL
- MySQL - Home
- MySQL - Introduction
- MySQL - Installation
- MySQL - Administration
- MySQL - PHP Syntax
- MySQL - Connection
- MySQL - Create Database
- MySQL - Drop Database
- MySQL - Select Database
- MySQL - Data Types
- MySQL - Create Tables
- MySQL - Drop Tables
- MySQL - Insert Query
- MySQL - Select Query
- MySQL - Where Clause
- MySQL - Update Query
- MySQL - Delete Query
- MySQL - Like Clause
- MySQL - Sorting Results
- MySQL - Using Join
- MySQL - NULL Values
- MySQL - Regexps
- MySQL - Transactions
- MySQL - Alter Command
- MySQL - Indexes
- MySQL - Temporary Tables
- MySQL - Clone Tables
- MySQL - Database Info
- MySQL - Using Sequences
- MySQL - Handling Duplicates
- MySQL - SQL Injection
- MySQL - Database Export
- MySQL - Database Import
Select a field and if it's null, select another 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)
- Related Articles
- Select different fields in MySQL even if a field is set to null?
- Return true or false in a MySQL select if another field contains a string?
- MongoDB query to select one field if the other is null and the first field if both are not null?
- MongoDB query to select one field if the other is null?
- Concat a field in MySQL SELECT?
- MySQL select query to fetch data with null value?
- SELECT WHERE IN null in MySQL?
- MySQL SELECT IF statement with OR?
- Treat a MySQL column field as NULL if it is blank?
- How to update a field with a particular value if it is null in MySQL?
- MySQL - Select all records if it contains specific number?
- How to generate field in MySQL SELECT?
- How to use NULL in MySQL SELECT statement?
- Perform MySQL SELECT on fields containing null values?
- Can we use SELECT NULL statement in a MySQL query?

Advertisements