[SOLVED] How to implement If else condition in MySQL select statement

Issue

I want to check the value present in two fields of the table and based on that I want to display either field 1 or field 2.
For Example:

Select name from users if address1='Mars' 
else select age from users if address2='Mars';

I want to achieve this using plane SQL because I need to implement this in the controller of Rails using ActiveRecord::Base.connection.select_values("sql query")

What should be the SQL query to achieve this?

Solution

use CASE

SELECT  CASE 
            WHEN address1='Mars' THEN name 
            WHEN address2='Mars' THEN age
        END
FROM    users

Answered By – John Woo

Answer Checked By – Cary Denson (BugsFixing Admin)

Leave a Reply

Your email address will not be published.