Wednesday, May 11

Using Conditional statements in mysql query

I had a field in mysql table which stored a boolean value.
While retrieving it from the database using mysql query, i wanted to display 'yes' / 'No' instead of 0 or 1. I could have done this in php, but this can also been directly using mysql query

if(field_name > 0, 'Yes', 'No') as required_field
FROM mysql_table

If the condition succeeds, then it return 'Yes'  and if the condition fails it returns 'No'

You can find further information on mysql documentation here

IF(expr1, expr2, expr3)

If Expr1 is TRUE (Expr1 <> NULL and Expr1 <> 0 ) then IF() returns Expr2 otherwise it returns Expr3
IF() returns a numeric or string value, depending on the context in which it is used.

Be the first one to Comment!!!

Post a Comment