Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL CONCAT with an IF statement

Tags:

sql

concat

I have this:

SELECT CONCAT(forename,' ',IFNULL(initials, ''),' ',surname) AS name FROM users

How do I change it so that if the initials field is null it also doesn't include the space after it?

like image 798
bcmcfc Avatar asked Feb 15 '11 10:02

bcmcfc


People also ask

What can I use instead of concat in SQL?

Re: Alternatives to using Concat for SQL queriesTextJoin() is used to combine contents from different cells. You can specify a delimiter and you can ignore empty cells.

Can we use concat in select statement?

We can use a literal in CONCAT Function. A literal is a number, character, or date that includes the SELECT statement.

What is the use of || in SQL?

The concatenation operator is a binary operator, whose syntax is shown in the general diagram for an SQL Expression. You can use the concatenation operator ( || ) to concatenate two expressions that evaluate to character data types or to numeric data types.


3 Answers

SELECT CONCAT(forename,' ',IFNULL(CONCAT(initials,' '), ''),surname) AS name FROM users
like image 88
Matt Avatar answered Sep 28 '22 08:09

Matt


Use SELECT CONCAT(forename, ' ', CASE WHEN initials IS NULL THEN '' ELSE initials || ' ' END, surname) ...

like image 36
Benoit Avatar answered Sep 28 '22 10:09

Benoit


I would use CONCAT_WS. For example:

SELECT CONCAT_WS(' ', NULL, 'First', NULL, 'Last', NULL);

This will return the string "First Last" with no spaces anywhere other than one CONCAT_WS has put between the two strings that are not NULL.

The first argument of CONCAT_WS is the glue that appears between the non-NULL values.

In your case this would be:

SELECT CONCAT_WS(' ', forename, initials, surname) AS name FROM users;

From here:

http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat-ws

Edit: This only works in MySQL.

like image 29
Nick Pyett Avatar answered Sep 28 '22 09:09

Nick Pyett