Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use case in where clause

Tags:

mysql

I want to get only status = 1 records. But I don't have status column in my table. So I derived the value using CASE... WHEN... THEN. But when I try to use case in where clause, It shows syntax error.

my query

SELECT SQL_CALC_FOUND_ROWS *,
    CASE
        WHEN quantity > num_used AND (CURDATE() BETWEEN coupon_start_date AND coupon_end_date) THEN '1'
        ELSE '0'
    END AS STATUS
FROM
    table_coupon_code
WHERE
    (CASE
        WHEN quantity > num_used AND (CURDATE() BETWEEN coupon_start_date AND coupon_end_date) THEN '1'
        ELSE '0'
    END AS STATUS) = '1' AND coupon_status <> '2'

How can I do this ?

like image 752
Gowri Avatar asked Jul 25 '11 06:07

Gowri


3 Answers

remove AS STATUS from where clause

SELECT SQL_CALC_FOUND_ROWS * ,
  CASE WHEN quantity > num_used AND (CURDATE( ) BETWEEN coupon_start_date AND coupon_end_date)
  THEN '1'
  ELSE '0'
  END AS STATUS
FROM table_coupon_code
WHERE 
CASE WHEN quantity > num_used AND (CURDATE( ) BETWEEN coupon_start_date AND coupon_end_date)
  THEN '1'
  ELSE '0'
  END = '1'
AND coupon_status <> '2'

But your CASE is really unnecessary. Just use your CASE condition as stand-alone WHEREcondition, like

[...]
WHERE quantity > num_used AND
CURDATE( ) BETWEEN coupon_start_date AND coupon_end_date AND
coupon_status <> '2'
like image 67
rabudde Avatar answered Sep 24 '22 19:09

rabudde


If you do not want to repeat the case statement you could wrap the select in a subselect or make a view. Subselect is something like

select status 
  from (select case 
          when zip like '4321%' then 1 else 0 end as status
          from adr 
       ) t 
 where status = 1;
like image 21
Olaf Avatar answered Sep 23 '22 19:09

Olaf


Nobody Suggested the HAVING Clause?

This allows you to query the selected columns, instead of the actual results. Great for using case and function calls.

like image 44
Adam F Avatar answered Sep 24 '22 19:09

Adam F