MySQL: Multiple AND queries with using BETWEEN?

John picture John · Oct 5, 2010 · Viewed 8.7k times · Source

I had seen a colleague use this to fetch users from a table under these conditions:

SELECT * FROM users WHERE gender ='male' 
AND activated='yes' 
AND date_registered BETWEEN '$date1' AND '$date2' 

He said there was an problem (it not outputting any rows when the AND activated='yes' was put there as well, but no MySQL error was thrown.

Can you not do this? Do you need to put it in brackets or something crazy to associate the BETWEEN and AND?

Dates are in correct format by the way.

Answer

Wrikken picture Wrikken · Oct 5, 2010

Nope, it will work just fine. However, you might want to format your query so it is clear which AND is standalone, and which belongs to a BETWEEN .. AND ... statement:

SELECT * FROM users 
WHERE gender ='male' 
   AND activated='yes' 
   AND date_registered BETWEEN '$date1' AND '$date2'