MySQL numeric functions
MySQL string functions
MySQL Date/Time functions
MySQL aggregate functions
MySQL flow control functions
The CONCAT()
function in MySQL is used to concatenate two or more strings into one string.
Prerequisites:
Tutorial:
To start the mysql
command-line client, open a terminal or command prompt, and enter:
mysql -u [username] -p
Replace [username]
with your MySQL username and enter your password when prompted.
Select the database containing the table you want to query:
USE [database_name];
Replace [database_name]
with the name of your database.
You can use the CONCAT()
function with constant string values:
SELECT CONCAT('Hello', ' ', 'World');
This will return a single string: 'Hello World'.
Suppose you have a users
table with the following columns: id
, first_name
, last_name
. You can use the CONCAT()
function to combine the first_name
and last_name
columns:
SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM users;
This query will return a column full_name
which combines the first_name
and last_name
with a space in between.
If any of the arguments to the CONCAT()
function is NULL
, the function returns NULL
. You can use the CONCAT_WS()
function instead if you want to treat NULL
values as empty strings:
SELECT CONCAT('Hello', NULL, 'World'); -- This will return NULL SELECT CONCAT_WS(' ', 'Hello', NULL, 'World'); -- This will return 'Hello World'
EXIT;
Now you have learned how to use the MySQL CONCAT()
function to concatenate strings. This is a useful function when you need to combine text data in your SQL queries.
How to use CONCAT function in MySQL:
SELECT CONCAT('Hello', ' ', 'World') AS result;
Concatenating strings in MySQL with CONCAT:
SELECT CONCAT('First', 'Second') AS result;
MySQL CONCAT with multiple strings:
SELECT CONCAT('One', ' ', 'Two', ' ', 'Three') AS result;
Concatenation using CONCAT_WS in MySQL:
SELECT CONCAT_WS(', ', 'Apple', 'Banana', 'Orange') AS result;
Examples of using CONCAT in MySQL queries:
SELECT CONCAT(column1, ' - ', column2) AS result FROM your_table;
Concatenating columns with CONCAT in MySQL:
SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM employees;
Concatenating numbers and strings in MySQL:
SELECT CONCAT('ID: ', employee_id) AS employee_info FROM employees;
Handling NULL values with CONCAT in MySQL:
SELECT CONCAT('First Name: ', first_name, ' Last Name: ', COALESCE(last_name, '')) AS full_name FROM users;
Using CONCAT in WHERE clause in MySQL:
SELECT * FROM your_table WHERE CONCAT(column1, ' ', column2) = 'target_value';
Concatenating with separators in MySQL:
SELECT CONCAT(first_name, ', ', last_name) AS full_name FROM employees;
Concatenating date and time values in MySQL:
SELECT CONCAT('Date: ', DATE_FORMAT(date_column, '%Y-%m-%d'), ' Time: ', TIME_FORMAT(time_column, '%H:%i:%s')) AS datetime_info FROM your_table;