Jump to: navigation, search

Mysql IF

From w3cyberlearnings

Contents

MySQL If Function

This operator uses to check a condition within a context.

Syntax If

When expr1 is TRUE, return expre2, and otherwise returns expre3.

IF(expr1,expr2,expr3)

Example 1

mysql> SELECT IF(1>2,2,3);
+-------------+
| IF(1>2,2,3) |
+-------------+
|           3 | 
+-------------+
1 row in set (0.00 sec)

Example 2

Select records

mysql> SELECT * FROM myscore;
+----+-------+--------------+
| id | score | student_name |
+----+-------+--------------+
|  1 |    30 | Bob          | 
|  2 |    40 | Jing         | 
|  3 |    34 | Kim          | 
+----+-------+--------------+
3 rows in set (0.01 sec)

Use IF

mysql> SELECT IF(score<31,'failed','good') as checkscore,
    -> id, student_name
    -> FROM myscore;
+------------+----+--------------+
| checkscore | id | student_name |
+------------+----+--------------+
| failed     |  1 | Bob          | 
| good       |  2 | Jing         | 
| good       |  3 | Kim          | 
+------------+----+--------------+
3 rows in set (0.00 sec)


Related Links


--CASE-- IF-- IFNULL-- NULLIF--

Navigation
Web
SQL
MISC
References