Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL: Best way to handle NULL values in string concatenation

If in a SELECT statement I'm selecting a concatenated string that uses values from the table(s) I'm selecting from, what's the best way to handle NULLs for those values so that I still have my string? As in, if I'm selecting City, State, and Country for a User, and I want a third field that concatenates them all:

SELECT City, State, Country,
City + ', ' + State + ', ' + Country AS 'Location'
FROM Users

However, 'Location' is NULL if any of the three fields is NULL (which is happens whenever the user is not from the US).

My current solution is this:

SELECT City, State, Country,
City + ', ' + COALESCE(State + ', ', '') + Country AS 'Location'
FROM Users

But I wasn't sure if this was just a hack and if there's a much better way to do it. Thoughts?

like image 514
JoeCool Avatar asked Feb 10 '11 18:02

JoeCool


People also ask

How do you concatenate NULL values in a string in SQL?

When SET CONCAT_NULL_YIELDS_NULL is ON, concatenating a null value with a string yields a NULL result. For example, SELECT 'abc' + NULL yields NULL . When SET CONCAT_NULL_YIELDS_NULL is OFF, concatenating a null value with a string yields the string itself (the null value is treated as an empty string).

Can you concatenate a string with NULL?

To concatenate null to a string, use the + operator. Let's say the following is our string. String str = "Demo Text"; We will now see how to effortlessly concatenate null to string.

How does concat handle NULL?

In SQL Server, NULL is a special pointer that specifies a value that is undefined or does not exist. When passing a NULL value as a parameter to the CONCAT function, the NULL values are converted to an empty string.

Can we concatenate NULL values?

When you concatenate any string with a NULL value, it will result in NULL. To avoid this, you can use the COALESCE function. The COALESCE function returns the first non-Null value. So, when there is a value in the column that is not null, that will be concatenated.


2 Answers

You can use the Concat function in SQL 2012 and later

SELECT City, State, Country,
Concat(City, ', ', State, ', ', Country) AS 'Location'
FROM Users
like image 177
cedd Avatar answered Oct 10 '22 08:10

cedd


To predictably look correct with commas between every two fields, you can use this form

;with users(City, State, Country) as (
select 'a', null, 'c' union all
select 'a', 'b', 'c' union all
select null, null, 'c')

-- ignore above this line
SELECT City, State, Country,
    STUFF(
        ISNULL(', ' + City, '')+
        ISNULL(', ' + State, '')+
        ISNULL(', ' + Country, ''), 1, 2, '') AS 'Location'
FROM Users

Output

City State Country Location
---- ----- ------- --------
a    NULL  c       a, c
a    b     c       a, b, c
NULL NULL  c       c
like image 23
RichardTheKiwi Avatar answered Oct 10 '22 06:10

RichardTheKiwi