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?
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.
We can use a literal in CONCAT Function. A literal is a number, character, or date that includes the SELECT statement.
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.
SELECT CONCAT(forename,' ',IFNULL(CONCAT(initials,' '), ''),surname) AS name FROM users
Use SELECT CONCAT(forename, ' ', CASE WHEN initials IS NULL THEN '' ELSE initials || ' ' END, surname) ...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With