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



In MySQL, the ENUM data type is used to limit column values to a specified set of options which is useful for categories like colors, status, and gender. Sometimes, it is helpful to display these ENUM values as more descriptive like converting 'P' to "pass" and 'F' to "Fail".

The IF() function in MySQL makes this easy by allowing conditional logic within SQL queries. The example below will demonstrate how to use the IF() function to convert ENUM values into user-friendly.

Example

To understand first let us create a table, DemoTable, which contains an ENUM column UserGender to store gender values('M' for male and 'F' for female). The query is as follows ?

CREATE TABLE DemoTable
   (
   UserId int,
   UserName varchar(40),
   UserGender ENUM('M','F')
   );
Inserting Records

Now let us insert some sample data with different values for the UserGender column:

To Insert records in the table use INSERT command ?

INSERT INTO DemoTable values(1,'John','M');
INSERT INTO DemoTable values(2,'Maria','F');
INSERT INTO DemoTable 
values
  (3,'David','M'), 
  (4,'Emma','F');
Fetching the data

Display all records from the table using SELECT statement ?

SELECT * FROM DemoTable;

Following is the output of the above query ?

UserId UserName UserGender
1 John M
2 Maria F
3 David M
4 Emma F
IF() function to map ENUM values

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

SELECT 
    UserId, 
    UserName, 
    IF(UserGender = 'M', 'Male', 'Female') AS `UserGender`
FROM 
    DemoTable;

Following is the output of the above query ?

UserId UserName UserGender
1 John Male
2 Maria Female
3 David Male
4 Emma Female

This way you can convert 'M' as Male and 'F' as Female using IF() function.

Updated on: 2025-02-04T16:21:04+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements