SQL - Concat full name, and a space only if last name is present
You could use a TRIM()
function call to strip off any leading or trailing spaces :
TRIM(CONCAT(customers.firstname, ' ', customers.lastname))
TRIM()
also allows you to specific the characters you which to remove along with the location within the string (i.e. beginning, end, both, etc.) using the following syntax :
TRIM([LEADING | TRAILING | BOTH] [characters] FROM YourColumnOrString)
I use this:
trim(both from COALESCE(firstname, '') || ' ' || COALESCE(lastname, '')
if both first and last name can be null.
This worked for me:
case when customers.lastname = '' then customers.firstname else concat(customers.firstname, ' ', customers.lastname)end
Documentation for case: https://www.postgresql.org/docs/7.4/static/functions-conditional.html.
Special thanks to daf.