MySQL CASE WHEN with SELECT to display odd and even ids?


Let us first create a table −

mysql> create table DemoTable
(
   PageId int
);
Query OK, 0 rows affected (0.85 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(233);
Query OK, 1 row affected (0.36 sec)
mysql> insert into DemoTable values(34);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(76);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(89);
Query OK, 1 row affected (0.26 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+--------+
| PageId |
+--------+
|    233 |
|     34 |
|     76 |
|     89 |
+--------+
4 rows in set (0.00 sec)

Following is the query for CASE WHEN with SELECT −

mysql> select PageId, case when PageId %2 !=0 then 'PageId is odd' else 'PageId is even' end AS Result from DemoTable;

This will produce the following output −

+--------+----------------+
| PageId | Result         |
+--------+----------------+
|    233 |  PageId is odd |
|     34 |  PageId is even|
|     76 |  PageId is even|
|     89 |   PageId is odd|
+--------+----------------+
4 rows in set (0.00 sec)
raja
Published on 10-Oct-2019 15:05:32
Advertisements