Using CONCAT function in MySQL 8: A Practical Guide

Updated: January 26, 2024 By: Guest Contributor Post a comment

Introduction

The CONCAT function in MySQL is a string function that allows you to join two or more strings together. This can be incredibly useful when working with database tables where you need to combine information from different columns or add a certain format to the data you retrieve. In this guide, we will take an in-depth look at the CONCAT function, demonstrate its use with multiple examples, and learn how to leverage it in MySQL 8.

Basic Usage of CONCAT Function

The CONCAT function in MySQL is quite straightforward. The basic syntax is as follows:

SELECT CONCAT(string1, string2, ...);

Let’s start with an example. Suppose we have a table named users with a first and last name field:

CREATE TABLE users (
    user_id INT AUTO_INCREMENT,
    first_name VARCHAR(100),
    last_name VARCHAR(100),
    PRIMARY KEY (user_id)
);

INSERT INTO users (first_name, last_name) VALUES ('John', 'Doe'), ('Jane', 'Doe');

If we want to create a full name from the first and last name, we can do so with CONCAT:

SELECT CONCAT(first_name, ' ', last_name) AS 'Full Name'
FROM users;

This will produce the following result:

+-----------+
| Full Name |
+-----------+
| John Doe  |
| Jane Doe  |
+-----------+

Handling NULL Values with CONCAT_WS

The CONCAT function in MySQL does not handle NULL values by default. If any of the arguments is NULL, the result of the CONCAT function is also NULL. To overcome this problem, we use the CONCAT_WS (Concatenate With Separator) function which skips all NULL values. The syntax for CONCAT_WS is:

SELECT CONCAT_WS(separator, string1, string2, ...);

Let’s see an example where a user might not have a middle name:

SELECT CONCAT_WS(' ', first_name, middle_name, last_name) AS 'Full Name'
FROM users;

If middle_name is NULL, it will be skipped, and you’ll simply get the first and last name.

Concatenation with Different Data Types

In MySQL, you can also concatenate strings with different data types. When other data types such as integers or dates are concatenated with strings, they are automatically converted to strings. Here’s an example:

SELECT CONCAT(user_id, ': ', first_name, ' ', last_name) AS 'User Reference'
FROM users;

This will yield:

+-----------------+
| User Reference  |
+-----------------+
| 1: John Doe    |
| 2: Jane Doe    |
+-----------------+

Concatenating with Separator

When you want to join strings with a specific separator, such as a comma or a hyphen, you can do so easily. An example might be creating an email address from a user’s first and last name:

SELECT CONCAT(first_name, '.', last_name, '@example.com') AS 'Email Address'
FROM users;

The result:

+-----------------------+
| Email Address         |
+-----------------------+
| [email protected]  |
| [email protected]  |
+-----------------------+

Advanced Concatenation

Where CONCAT starts to show its true power is when combined with conditionals or functions. For example, you can use CONCAT with CASE statement:

SELECT user_id,
       CASE
           WHEN is_active THEN CONCAT(first_name, ' ', last_name, ' (Active)')
           ELSE CONCAT(first_name, ' ', last_name, ' (Inactive)')
       END AS 'User Status'
FROM users;

Moreover, you could use CONCAT to construct dynamic SQL queries with prepared statements:

SET @tableName = 'users';
SET @columnName = 'first_name';
SET @query = CONCAT('SELECT ', @columnName, ' FROM ', @tableName);
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

Commercial Use

Frequently in a business environment, you might need to format output data that includes both text and variable elements. CONCAT can be very helpful in generating such dynamic reports or for data-cleansing purposes:

SELECT CONCAT('The user ', first_name, ' ', last_name, ' has an id of ', user_id, '.') AS 'User Information'
FROM users;

The output offers a readable statement that could be presented in a report:

+------------------------------------+
| User Information                   |
+------------------------------------+
| The user John Doe has an id of 1.  |
| The user Jane Doe has an id of 2.  |
+------------------------------------+

Combining CONCAT with Aggregation

You can also combine CONCAT with GROUP_CONCAT to aggregate concatenate values from multiple rows:

SELECT department_id,
       GROUP_CONCAT(CONCAT(first_name, ' ', last_name) ORDER BY first_name SEPARATOR ', ') AS 'Department Users'
FROM employees
GROUP BY department_id;

This query would return a comma-separated list of names for each department.

Conclusion

In conclusion, the CONCAT function in MySQL 8 is an extremely versatile and essential tool for string manipulation. It allows for the straightforward combining of column values, formatting of output for readability, and concatenation with other SQL functions for dynamic SQL generation. By mastering CONCAT, you ensure your databases can deliver information in the exact format required.