user1620152
user1620152

Reputation: 134

Is it possible to append a string in an statement if the value is not null in MYSQL

So say I have something like this

SELECT CONCAT(fname, " " IFNULL(mname, ""), lname) FROM name

how would I add a space to that statement if mname is not null? Nothing i've tried has worked and I'm kind of lost. Obviously I can do something like

SELECT CONCAT(fname, " " IFNULL(mname, ""), " " lname) FROM name

but then that gives me two spaces instead of 1.

Upvotes: 1

Views: 34

Answers (1)

gaborsch
gaborsch

Reputation: 15758

Use another CONCAT in the middle name:

SELECT CONCAT(fname, 
              IF(mname is null, "", CONCAT(" ", mname)), 
              " " lname) 
  FROM name

Upvotes: 1

Related Questions