How to apply the IF ELSE condition to selecting a column?

Asked

Viewed 1,608 times

8

In Mysql, I have an old table entities where the column gender is in the format ENUM, containing values of the type: "i", "m", "f".

When migrating this data to the new structure of this table, I intended to execute a database query collecting the values as they will be in the target table:

Example:

┌─────────────┬────────────────────┐
│ Valor atual │  Valor pretendido  │
├─────────────┼────────────────────┤
│      i      │  undifferentiated  │
├─────────────┼────────────────────┤
│      m      │  male              │
├─────────────┼────────────────────┤
│      f      │  female            │
└─────────────┴────────────────────┘

How can I apply a condition IF ELSE in the selection of this column, indicating the desired value for each of the existing options?

1 answer

9


One way is to apply the case operator the selection of the desired column indicating each of the "conversions" to take place:

Example of consultation:

SELECT CASE gender
  WHEN 'i' THEN 'undifferentiated'
  WHEN 'm' THEN 'male'
  WHEN 'f' THEN 'female'
END AS gender
FROM `entities`
WHERE 1

What is being done is to select the column gender of all rows in the table entities, where for each row we check the value of the same and assign the new desired value.

Example of the result:

┌────────────────────┐
│  gender            │
└────────────────────┘
┌────────────────────┐
│  undifferentiated  │
├────────────────────┤
│  undifferentiated  │
├────────────────────┤
│  male              │
├────────────────────┤
│  female            │
└────────────────────┘

Browser other questions tagged

You are not signed in. Login or sign up in order to post.