How do I use properly CASE..WHEN in MySQL How do I use properly CASE..WHEN in MySQL sql sql

How do I use properly CASE..WHEN in MySQL


Remove the course_enrollment_settings.base_price immediately after CASE:

SELECT   CASE    WHEN course_enrollment_settings.base_price = 0      THEN 1    ...    END

CASE has two different forms, as detailed in the manual. Here, you want the second form since you're using search conditions.


CASE case_value    WHEN when_value THEN statements    [WHEN when_value THEN statements]    ELSE statementsEND 

Or:

CASEWHEN <search_condition> THEN statements[WHEN <search_condition> THEN statements] ELSE statementsEND 

here CASE is an expression in 2nd scenario search_condition will evaluate and if no search_condition is equal then execute else

SELECT   CASE course_enrollment_settings.base_price    WHEN course_enrollment_settings.base_price = 0      THEN 1

should be

SELECT   CASE     WHEN course_enrollment_settings.base_price = 0      THEN 1


CASE course_enrollment_settings.base_price is wrong here, it should be just CASE

SELECT CASE WHEN course_enrollment_settings.base_price = 0      THEN 1 WHEN course_enrollment_settings.base_price<101      THEN 2 WHEN course_enrollment_settings.base_price>100 AND                      course_enrollment_settings.base_price<201 THEN 3     ELSE 6 END AS 'calc_base_price', course_enrollment_settings.base_price FROM   course_enrollment_settings WHERE course_enrollment_settings.base_price = 0 

Some explanations. Your original query will be executed as :

SELECT CASE 0WHEN 0=0 THEN 1 -- condition evaluates to 1, then 0 (from CASE 0)compares to 1 - falseWHEN 0<1 THEN 2 -- condition evaluates to 1,then 0 (from CASE 0)compares to 1 - falseWHEN 0>100 and 0<201 THEN 3 -- evaluates to 0 ,then 0 (from CASE 0)compares to 0 - trueELSE 6, ...

it's why you always get 3