[mysql] using CASE in the WHERE clause

simplified version of my query

SELECT *
FROM logs 
WHERE pw='correct' AND CASE WHEN id<800 THEN success=1 ELSE END 
AND YEAR(timestamp)=2011 

this doesn't work. What i'm trying to do is to add in success=1 only for rows with id<800, else ignore this check.

how do i write this? thanks!

edit: to clarify, this what the table looks like

|id  | pw      | success |
--------------------------
|700 | correct | 1       |
|710 | correct | 1       |
|900 | correct | NULL    |
|999 | correct | 0       |

I'm trying to return all the rows, the column pw cannot be ignored.

This question is related to mysql sql

The answer is


This is working Oracle example but it should work in MySQL too.

You are missing smth - see IN after END Replace 'IN' with '=' sign for a single value.

SELECT empno, ename, job
  FROM scott.emp
 WHERE (CASE WHEN job = 'MANAGER' THEN '1'  
         WHEN job = 'CLERK'   THEN '2' 
         ELSE '0'  END) IN (1, 2)

SELECT *
FROM logs
WHERE pw='correct'
  AND CASE
          WHEN id<800 THEN success=1
          ELSE 1=1
      END
  AND YEAR(TIMESTAMP)=2011

You can transform logical implication A => B to NOT A or B. This is one of the most basic laws of logic. In your case it is something like this:

SELECT *
FROM logs 
WHERE pw='correct' AND (id>=800 OR success=1)  
AND YEAR(timestamp)=2011

I also transformed NOT id<800 to id>=800, which is also pretty basic.