Sling Academy
Home/MySQL/Using CONCAT function in MySQL 8: A Practical Guide

Using CONCAT function in MySQL 8: A Practical Guide

Last updated: January 26, 2024

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.

Next Article: Using SUBSTRING function in MySQL 8: A Practical Guide

Previous Article: How to perform full-text search in MySQL 8

Series: MySQL Tutorials: From Basic to Advanced

MySQL

You May Also Like

  • MySQL: How to reset the AUTO_INCREMENT value of a table
  • MySQL: How to add a calculated column to SELECT query
  • MySQL: Eliminate orphan rows in one-to-many relationships
  • MySQL: Using R-Tree Indexes for Spatial Data Types
  • How to Create Custom Collations in MySQL
  • Using Hash Indexes in MySQL: A Practical Guide
  • Understanding Full-Text Indexes in MySQL
  • Partial Indexes in MySQL: A Practical Guide
  • MySQL: How to Remove FOREIGN KEY Constraints
  • Using ENUM in MySQL 8: A Practical Guide (with Examples)
  • MySQL: Creating a Fixed-Size Table by Using Triggers
  • One-to-Many Relationship in MySQL 8: A Practical Guide
  • Using Regular Expressions in MySQL 8: The Complete Guide
  • Using Loops in MySQL: A Practical Guide (with Examples)
  • How to Execute an SQL File in VS Code
  • Making use of the JSON_REMOVE() function in MySQL 8
  • MySQL 8: How to count rows in related tables
  • Replication in MySQL 8: A Comprehensive Guide
  • MySQL 8: FIRST_VALUE(), LAST_VALUE(), and NTH_VALUE() functions – Explained with examples