Skip to content
Advertisement

How to change query result into another value in MYSQL?

For example, I have a column named ‘form_type’ consisted of int (1-4)

id_event|form_type
--------|----------
001     |1
001     |3
001     |4
002     |2
002     |1

When i query

SELECT form_type FROM some_table WHERE id_event = 001

I would get 1,3 and 4 of course. But is it possible to change those values to something else on the database layer? For example, I would get strings instead of int like so, 1 = ‘Name’, 3 = ‘Email’, 4 = ‘City’ etc. If it’s possible, what would be the query? Or is the only way to do that would be on the application side?

Advertisement

Answer

Yes, you can do something like this:

SELECT
    CASE
        WHEN form_type = 1 THEN 'Name'
        WHEN form_type = 3 THEN 'Email'
        WHEN form_type = 4 THEN 'City'
        ELSE 'some default value'
    END
FROM some_table
WHERE id_event = 001

Using CASE you define what you want returned for the value in your table. CASE example here.

Hope that helps!

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement