Bloomberg
Bloomberg

Reputation: 2367

how to use if conditions in mysql

I am trying to get some results through query that would be in range from -50 to +50. now according to the range I need to have value in column comment.

The conditions are

    >=-50 and < -30 = very negative
    =< -30 and < -10 = negative
    =< -10 and < +10 = neutral
    =< +10 and < +30 = positive
    =< +30 and < +50 = very positive

the output i am trying to get is:

range  comment
-45     very negative
-20     negative

I can just get the value how can i set comment according to it.

Upvotes: 0

Views: 57

Answers (3)

KaeL
KaeL

Reputation: 3659

You can use CASE syntax.

CASE 
   WHEN range BETWEEN -50 AND -31 THEN 'very negative'
   WHEN range BETWEEN -30 AND -11 THEN 'negative'
   ...
   ELSE 'very positive'
END CASE

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522741

This sounds like you want to use a CASE WHEN expression:

SELECT range,
    CASE WHEN range BETWEEN -50 AND -30 THEN 'very negative'
         WHEN range BETWEEN -30 AND -10 THEN 'negative'
         WHEN range BETWEEN -10 AND 10  THEN 'neutral'
         WHEN range BETWEEN 10  AND 30 THEN 'positive'
         WHEN range BETWEEN 30  AND 50 THEN 'very positive'
    END AS comment
FROM yourTable

Upvotes: 0

dmitryro
dmitryro

Reputation: 3516

Your query is:

SELECT * FROM your_table WHERE range BETWEEN -50 AND 50;

Upvotes: 1

Related Questions