SQL String Function CONCAT()

‮w‬ww.theitroad.com

In SQL, the CONCAT() function is used to concatenate two or more strings into a single string. It takes two or more string arguments as inputs and returns a single concatenated string.

Here is an example of using the CONCAT() function to concatenate the first name and last name of employees in a employees table:

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

In this example, the CONCAT() function is used to concatenate the first_name and last_name columns of the employees table, separated by a space. The AS keyword is used to alias the resulting column as full_name.

The CONCAT() function can also be used to concatenate strings with other values or expressions. For example, to concatenate the string "Hello, " with the first_name column, we can use the following query:

SELECT CONCAT('Hello, ', first_name) AS greeting FROM employees;

In this example, the CONCAT() function is used to concatenate the string "Hello, " with the first_name column of the employees table. The resulting column is aliased as greeting.

It's important to note that the CONCAT() function returns NULL if any of the input strings are NULL. To handle this, we can use the COALESCE() function to replace NULL values with a default value or an empty string. For example:

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

In this example, the COALESCE() function is used to replace any NULL values in the first_name and last_name columns with an empty string, before using the CONCAT() function to concatenate the strings.