Home / Databases / MySQL / How can I add a conditional statement in the field list of my sql statement?
How can I add a conditional statement in the field list of my sql statement?
Last updated: 06/30/2009
Suppose you are selecting records from a database, and you want to add some logic to the resulting output. For example, assume I am outputting a person's name, and I have three fields:
first_name last_name middle_initial
I want to display the output like so:
firstname middle_initial. last_name
However, if there's no middle_initial, I'm going to end up with a "." between the first and last names, and it'll look stupid. I can fix this by adding a conditional to the sql call:
SELECT first_name, CONCAT(middle_initial, IF(middle_initial != '','.','')) as middle, last_name from names
Now, the field "middle" can be used in your output and will either by empty, or contain the middle initial with a "." after it.