How to concatenate strings using the MySQL CONCAT() function and examples
This tutorial explains how to concatenate strings using the MySQL CONCAT() function.
You will learn how to use the MySQL CONCAT() function, which is a function that adds two or more expressions together.
Learn more: MySQL GROUP_CONCAT() function
MySQL CONCAT() Syntax
CONCAT(expression1, expression2,..., expressionN)
- The first expression is required.
- CONCAT() returns NULL if any expression is NULL.
1. Combine several strings
The following is an example of using the MySQL CONCAT() to concatenate multiple strings:
SELECT CONCAT("I ", "want ", "to visit ", "United State") AS Combined_String;
The statement returns:
I want to visit United State.
2. Combine several strings with NULL
The following statement returns null because the third argument is a NULL value:
SELECT CONCAT("I ", "Like playing football", NULL);
Below is the order list for the demo:
|2||#ORD_00002||#CID_20002||Lisa Ramsey||United State||1350.50|
|5||#ORD_00005||#CID_20002||Lisa Ramsey||United State||3450.00|
|6||#ORD_00006||#CID_20003||Charles Harmon||United State||3470.50|
You can use the MySQL SUM() function to sum the values and combine them with other strings.
Here is an example:
SELECT CONCAT("The total amount is $", SUM(o.amount), ".") AS Result
FROM orders o;
The returned value is as follows:
|The total amount is $15911.00.|
You can also use SUM() and GROUP BY with the CONCAT() function.
Here is an example:
SELECT CONCAT("The total amount ", "ordered by ", o.customer_name, " is $", SUM(o.amount), ".") AS Result
FROM orders o GROUP BY o.customer_name;
The returned result set is as follows:
|The total amount ordered by Charles Harmon is $3470.50.|
|The total amount ordered by Francis Lewis is $1230.80.|
|The total amount ordered by Josh Warner is $4410.40.|
|The total amount ordered by Lisa Ramsey is $4800.50.|
|The total amount ordered by William Barnett is $1998.80.|
In this tutorial, you have learned how to concatenate strings using the MySQL CONCAT() function. You can use MySQL CONCAT() to combine multiple strings.