How to Use the CONCAT() Function in MySQL

08/05/2021

Contents

In this article, you will learn how to use the CONCAT() function in MySQL.

Using the CONCAT() function in MySQL

The CONCAT() function in MySQL is used to concatenate two or more strings into a single string.

Syntax

The syntax for using the CONCAT() function in MySQL is as follows:

CONCAT(string1, string2, ..., stringN)

Where “string1”, “string2”, …, “stringN” are the strings to be concatenated.

Examples

Suppose we have a table named “employees” with columns “employee_id”, “first_name”, “last_name”, and “salary”. We can use the CONCAT() function to concatenate the “first_name” and “last_name” columns into a single column named “full_name” as follows:

SELECT employee_id, CONCAT(first_name, ' ', last_name) AS full_name, salary FROM employees;

This query will return the employee ID, full name (with a space in between the first and last names), and salary of all employees in the “employees” table.

We can also use the CONCAT() function to concatenate multiple columns or literals. For example, suppose we want to create a column that contains the employee’s name and salary. We can use the following query:

SELECT CONCAT(first_name, ' ', last_name, ': $', salary) AS employee_info FROM employees;

This query will return a single column named “employee_info” that contains the employee’s first and last name, separated by a space, followed by a colon and their salary with a dollar sign in front of it.

We can also use the CONCAT() function with NULL values. If any of the arguments to CONCAT() is NULL, the resulting string will also be NULL. For example, suppose we want to create a column that contains the employee’s name and department. We can use the following query:

SELECT CONCAT(first_name, ' ', last_name, ' - ', department) AS employee_info FROM employees;

If an employee doesn’t have a department assigned, the value for the “department” column will be NULL and the resulting value for “employee_info” will also be NULL.