MySql: if-condition

Sometimes it can be handy to have a if-condition in a SQL query and MySql makes it quite easy. The syntax is quite easy to learn. Here’s an example:

Tabell `Person`:
Id Name Age Gender AddressId 
3	John Doe	50	Male	3
4	Jane Doe	30	Female	4
6	Jake Doe	35	Male	3
7	Jessica Doe	61	Female	4

If we want to fetch all name and prefix them “Mr” or “Mrs” then we could do this:

SELECT IF( Gender = 'Male', CONCAT( 'Mr', ' ', Name ) , CONCAT( 'Mrs', ' ', Name ) ) AS Name
FROM `Person`
LIMIT 0 , 30

This will fetch all the names and prefix them with Mr if they are male and Mrs if they are female (I’m prudent enough to assume that the names of unmarried women are not stored in a database :))

Mr John Doe
Mrs Jane Doe
Mr Jake Doe
Mrs Jessica Doe

2 thoughts on “MySql: if-condition

Leave a Reply