How to concat Values in MySQL Query and to handle Null values as well?


You can use CONCAT() method to concatenate values while IFNULL() method is used to handle NULL values. The syntax is as follows:

SELECT
CONCAT('anyStringValue:',IFNULL(yourColumnName, 'anyStringValue’)) AS anyVariableName
FROM yourTableName;

To understand the above syntax, let us create a table. The query to create a table is as follows:

mysql> create table ConcatValues
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> FirstName varchar(20),
   -> MiddleName varchar(20),
   -> LastName varchar(20),
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.62 sec)

Insert some records in the table using insert command. The query is as follows:

mysql> insert into ConcatValues(FirstName,MiddleName,LastName) values('John' ,NULL ,'Smith');
Query OK, 1 row affected (0.24 sec)

mysql> insert into ConcatValues(FirstName,MiddleName,LastName) values('Carol' ,NULL ,'Taylor');
Query OK, 1 row affected (0.16 sec)

mysql> insert into ConcatValues(FirstName,MiddleName,LastName) values('David' ,NULL ,'Miller');
Query OK, 1 row affected (0.23 sec)

Display all records from the table using select statement. The query is as follows:

mysql> select *from ConcatValues;

The following is the output:

+----+-----------+------------+----------+
| Id | FirstName | MiddleName | LastName |
+----+-----------+------------+----------+
| 1 | Mary | Elizabeth | Smith |
| 2 | John | NULL | Smith |
| 3 | Carol | NULL | Taylor |
| 4 | David | NULL | Miller |
+----+-----------+------------+----------+
4 rows in set (0.00 sec)

Here is the query to handle the NULL and concatenate values:

mysql> select
   -> concat('The middle name is:',IFNULL(MiddleName, 'Not Available')) AS MiddleName
   -> from ConcatValues;

The following is the output:

+----------------------------------+
| MiddleName                       |
+----------------------------------+
| The middle name is:Elizabeth     |
| The middle name is:Not Available |
| The middle name is:Not Available |
| The middle name is:Not Available |
+----------------------------------+
4 rows in set (0.00 sec)

Updated on: 30-Jul-2019

818 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements