Working with databases is constantly associated with obtaining query results. And in some cases, this information must be displayed in a certain way or combined with other data. To solve this problem, there is an SQL function - CONCAT.
What does the CONCAT function do?
When performing some work with databases, there is a need to connect rows with additional data or with each other. To solve this problem, there is an SQL function - CONCAT. When used, two or more lines will be combined into one. In this case, the string concatenation operation will be correctly performed both when working with strings and with numerical variables.
In some SQL databases, CONCAT has several flavors. So, in MySQL, it has its own counterpart - CONCAT_WS. The difference between the functions is insignificant: in the case of the first, when combining with an argument whose value is NULL, the result of concatenation will be NULL, and when using the second variant of combining, the null operand will be simply skipped.
Function Syntax
When using the CONCAT function, SQL syntax requires the programmer to use the arguments in the order in which the operands should be connected. The syntax of the string concatenation operation itself is quite simple: after the CONCAT keyword, in brackets, all necessary arguments or lines are indicated in order, and after the closing bracket, if necessary, the AS keyword and the name of the variable where the result will be written are indicated. The CONCAT function template is as follows:
CONCAT (line1, line2 [, line 3, ...]) [AS variable_name].
It is worth noting that as an argument to the function, you can use either the operand of a numerical or string value, or some function that returns the result. For example, the SQL CONCAT operation itself. Thus, the operation supports the nesting principle.
How to do without using CONCAT?
In the case when there is a need to do without using the operation, or the programmer does not know the CONCAT function, SQL offers another option for performing string concatenation. To do this, you must use the "+" operator, but this approach has a number of features that must be taken into account when working with it.
When using the "+" function, if the operands are numerical values, the result of the operation will be ordinary addition of numbers, and if necessary, combining a number with a string without explicit conversion, the program will give an error. So, when executing the following query, the result will be the value of the number "6":
SELECT 1 + 2 + 3.
Otherwise, both methods are identical and return the same result.