MySQL query to select ENUM('M', 'F') as 'Male' or 'Female'?

MySQLMySQLi Database

You can use IF() for this. Let us first create a table. One of the columns here is having ENUM type

mysql> create table DemoTable
   (
   UserId int,
   UserName varchar(40),
   UserGender ENUM('M','F')
   );
Query OK, 0 rows affected (1.11 sec)

Insert records in the table using insert command −

mysql> insert into DemoTable values(1,'John','M');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values(2,'Maria','F');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(3,'David','M');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values(4,'Emma','F');
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+--------+----------+------------+
| UserId | UserName | UserGender |
+--------+----------+------------+
| 1      | John     | M          |
| 2      | Maria    | F          |
| 3      | David    | M          |
| 4      | Emma     | F          |
+--------+----------+------------+
4 rows in set (0.00 sec)

Following is the query to select ENUM('M', 'F') as 'Male' or 'Female'−

mysql> SELECT UserId,UserName,IF(UserGender='F','Female', 'Male') AS `UserGender` from DemoTable;

This will produce the following output−

+--------+----------+------------+
| UserId | UserName | UserGender |
+--------+----------+------------+
| 1      | John     | Male       |
| 2      | Maria    | Female     |
| 3      | David    | Male       |
| 4      | Emma     | Female     |
+--------+----------+------------+
4 rows in set (0.00 sec)
raja
Published on 03-May-2019 11:15:28
Advertisements