Use MySQL CASE for a fixed number of arguments.
The syntax is as follows
SELECT *, CASE WHEN yourColumName1>yourColumName2 THEN 'yourMessage1' ELSE 'yourMessage2' END AS anyAliasName FROM yourTableName;
To understand the above syntax, let us create a table. The query to create a table is as follows
mysql> create table CaseFunctionDemo -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Value1 int, -> Value2 int -> ); Query OK, 0 rows affected (0.56 sec)
Insert some records in the table using insert command.
The query is as follows
mysql> insert into CaseFunctionDemo(Value1,Value2) values(10,20); Query OK, 1 row affected (0.21 sec) mysql> insert into CaseFunctionDemo(Value1,Value2) values(100,40); Query OK, 1 row affected (0.10 sec) mysql> insert into CaseFunctionDemo(Value1,Value2) values(0,20); Query OK, 1 row affected (0.15 sec) mysql> insert into CaseFunctionDemo(Value1,Value2) values(0,-50); Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement.
The query is as follows
mysql> select *from CaseFunctionDemo;
The following is the output
+----+--------+--------+ | Id | Value1 | Value2 | +----+--------+--------+ | 1 | 10 | 20 | | 2 | 100 | 40 | | 3 | 0 | 20 | | 4 | 0 | -50 | +----+--------+--------+ 4 rows in set (0.00 sec)
Here is the query for CASE statement
mysql> select*, case when Value1>Value2 then 'Value1 is Greater' else 'Value2 is Greater' end AS Comparision from CaseFunctionDemo;
The following is the output
+----+--------+--------+-------------------+ | Id | Value1 | Value2 | Comparision | +----+--------+--------+-------------------+ | 1 | 10 | 20 | Value2 is Greater | | 2 | 100 | 40 | Value1 is Greater | | 3 | 0 | 20 | Value2 is Greater | | 4 | 0 | -50 | Value1 is Greater | +----+--------+--------+-------------------+ 4 rows in set (0.00 sec)