MySQL SELECT WHERE based on TIME

Viewed 43

I've a query with a lot of WHERE conditions, but one of them needs to be dynamic. I need that one WHERE is applied only if the actual time is between 09:00 and 18:00. I.e.:

SELECT x,y from z WHERE
x = 'hello'
{ if time between 09:00 and 18:00 then }
AND y = 'world'
{ end if }

How to apply such a where condition?

Many thanks, Simon

2 Answers

You can use a simple HOUR(CURRENT_TIME()) which gives you current hour.

... WHERE HOUR(CURRENT_TIME()) > 9 AND HOUR(CURRENT_TIME()) < 18 ...

You can write the conditions like this:

SELECT x, y 
FROM z 
WHERE x = 'hello'
  AND (time NOT BETWEEN '09:00' AND '18:00' OR y = 'world')

This way the condition y = 'world' will affect the result only if time BETWEEN '09:00' AND '18:00' is true.

Related