Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does MySQL CONCAT IFNULL work with more than two values?

I need to CONCAT two fields, if they both exist and add parentheses around the second field. Otherwise I just need to list the first field.

Here's the simple version:

SELECT id, CONCAT(name,' (',nickname,')') as name FROM user;

As long as name and nickname both exist you should get results like:

1 | Adam (Alpha Dog)
2 | Bob (Bobby)
3 | Charles (Charlie)

But if there is no nickname it just skips the whole thing as null. For example: id 4, name Doug, nickname null gives the result:

4 | null

What I'd like to see is it to list just the name... like this:

4 | Doug

So I started looking at CONCAT IFNULL. But I'm having a hard time getting it right. Can you help?

Here are a few examples of things I've tried:

SELECT id, CONCAT(IFNULL(name, ' (', nickname, ')', name) as name FROM user;
SELECT id, CONCAT(name, IFNULL(' (', nickname, ')')) as name FROM user;
like image 335
Ryan Avatar asked Dec 13 '12 19:12

Ryan


People also ask

How does concat work in MySQL?

CONCAT() function in MySQL is used to concatenating the given arguments. It may have one or more arguments. If all arguments are nonbinary strings, the result is a nonbinary string. If the arguments include any binary strings, the result is a binary string.

What is the difference between concat and Concat_ws?

Both CONCAT() and CONCAT_WS() functions are used to concatenate two or more strings but the basic difference between them is that CONCAT_WS() function can do the concatenation along with a separator between strings, whereas in CONCAT() function there is no concept of the separator.

What is the difference between concat and Group_concat in MySQL?

The difference here is while CONCAT is used to combine values across columns, GROUP_CONCAT gives you the capability to combine values across rows. It's also important to note that both GROUP_CONCAT and CONCAT can be combined to return desired results.


2 Answers

You could use CONCAT_WS which skips null strings:

SELECT id, CONCAT_WS(' ', name, concat('(',nickname,')')) as name FROM user;
like image 62
fthiella Avatar answered Oct 18 '22 16:10

fthiella


You can concatenate the parens and the nickname, and then use the IFNULL to check to see if the result of that expression is NULL.

If it's null, replace the NULL with an empty string, and then concatenate that expression to the name column.

SELECT id
     , CONCAT(name,IFNULL(CONCAT(' (',nickname,')'),'')) AS name
  FROM user

NOTE: The IFNULL function is shorthand for:

IF(expr1 IS NULL,expr2,expr1)

or the ANSI equivalent:

CASE WHEN expr1 IS NULL THEN expr2 ELSE expr1 END 

There are other approaches that will work just as well. But they all basically need to do the same thing: check if nickname is NULL, and then conditionally include the parens and the nickname, or an empty string.

like image 4
spencer7593 Avatar answered Oct 18 '22 18:10

spencer7593