To insert an IF statement into a MySQL query, use the below syntax::
select yourColumnName ,if(yourCondition, yourStatement1,yourStatement2) from yourTableName;
Let us first create a table −
mysql> create table DemoTable1571 -> ( -> Id int, -> Value int -> ); Query OK, 0 rows affected (5.63 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1571 values(101,500); Query OK, 1 row affected (1.07 sec) mysql> insert into DemoTable1571 values(102,450); Query OK, 1 row affected (0.47 sec) mysql> insert into DemoTable1571 values(103,300); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable1571 values(104,700); Query OK, 1 row affected (0.23 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1571;
This will produce the following output
+------+-------+ | Id | Value | +------+-------+ | 101 | 500 | | 102 | 450 | | 103 | 300 | | 104 | 700 | +------+-------+ 4 rows in set (0.00 sec)
Here is the query to properly insert an if statement into a MySQL query.
mysql> select Value,if(Value > 550, 'Value is greater than 550','Value is less than 550') from DemoTable1571;
This will produce the following output −
+-------+-----------------------------------------------------------------------+ | Value | if(Value > 550, 'Value is greater than 550','Value is less than 550') | +-------+-----------------------------------------------------------------------+ | 500 | Value is less than 550 | | 450 | Value is less than 550 | | 300 | Value is less than 550 | | 700 | Value is greater than 550 | +-------+-----------------------------------------------------------------------+ 4 rows in set (0.00 sec)