Richa Sinha
Richa Sinha

Reputation: 1456

How to implement If else condition in MySQL select statement

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?

Upvotes: 0

Views: 1102

Answers (2)

John Woo
John Woo

Reputation: 263763

use CASE

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

Upvotes: 3

Alejandro Babio
Alejandro Babio

Reputation: 5229

Please, try User.find_by_sql("your sql query")

Upvotes: 0

Related Questions