How do you use the CONCAT function to concatenate strings with NULL values?
Posted by PaulAnd
Last Updated: June 30, 2024
In SQL, the CONCAT function can be used to concatenate multiple strings together, and it handles NULL values effectively. When you use CONCAT, if any of the values being concatenated are NULL, they are treated as empty strings. Here's a quick overview of how to use CONCAT with NULL values:
Syntax
CONCAT(string1, string2, ..., stringN)
Behavior with NULL
- If any of the arguments are NULL, they are treated as empty strings (i.e., ''), and concatenation proceeds as if that argument were just an empty string. - Thus, CONCAT will not return NULL as a result unless all inputs are NULL.
Example
Consider the following table named students: | first_name | last_name | |------------|--------------| | John | Doe | | NULL | Smith | | Jane | NULL | | NULL | NULL | Here’s how you can use CONCAT to combine first_name and last_name:
SELECT 
    CONCAT(first_name, ' ', last_name) AS full_name 
FROM 
    students;
Results
The output of the query would be: | full_name | |--------------| | John Doe | | Smith | | Jane | | | - For John Doe, both first_name and last_name are present, so they are concatenated. - For the student with the first name as NULL (NULL Smith), it becomes Smith (a leading space). - For Jane, it results in Jane (a trailing space). - For the record with both NULL values, it results in an empty string.
Conclusion
Using CONCAT is a straightforward way to concatenate strings in SQL, and it conveniently ignores NULL values by treating them as empty strings. This behavior is particularly useful when working with optional fields in databases. Remember to account for any extra spaces that might be added when fields are NULL while formatting your final output.