Database

MySQL CONCAT() Function

MySQL CONCAT() Function

In this tutorial, we will learn about MySQL CONCAT Function with some examples. We can use this function to concatenate strings. Concatenation is combining strings together into one string.

CONCAT() function concatenates the given arguments into one combined string.

Syntax

The general syntax of the function is as follows:

CONCAT(<arg1> [,<arg2>, …., <argn>])

The concatenation operation works with strings and MySQL will convert any other data types to strings first to perform the concatenation.

CONCAT(string1, string2, ..., stringN)
  • string1, string2, …, stringN: These are the strings or column names to be concatenated.
  • If any argument is NULL, the result will also be NULL. To handle NULL values, you can use the CONCAT_WS() function (covered below).

Examples

Basic Usage

Let’s concatenate two strings into one string.

mysql> SELECT CONCAT(‘Hello’,’World’);

Output
+————————-+
| CONCAT(‘Hello’,’World’) |
+————————-+
| HelloWorld |
+————————-+
1 row in set (0.00 sec)

CONCAT String Function

In the example, we have used the CONCAT() function to combine two strings ‘Hello’ and ‘World’ 

#

Let’s concatenate three strings into one string.

mysql> SELECT CONCAT(‘Testing’,’Docs’,’.com’);

+———————————+
| CONCAT(‘Testing’,’Docs’,’.com’) |
+———————————+
| TestingDocs.com |
+———————————+
1 row in set (0.01 sec)

 

MySQL CONCAT Function

mysql> SELECT CONCAT(‘A’,’quick’,’brown’,’fox’);
+———————————–+
| CONCAT(‘A’,’quick’,’brown’,’fox’) |
+———————————–+
| Aquickbrownfox |
+———————————–+

MySQL CONCAT Function

#

We can also concatenate database table columns using this function.

Handling NULL Values

SELECT CONCAT('Hello', NULL, 'World!');

Output:

NULL

 Using CONCAT_WS() to Handle NULL

The CONCAT_WS() function (Concatenate With Separator) allows you to specify a separator and ignores NULL values.

SELECT CONCAT_WS(' - ', 'MySQL', NULL, 'Database');

Output:

MySQL - Database

MySQL Tutorials

MySQL Tutorials on this website:

https://www.testingdocs.com/mysql-tutorials-for-beginners/