0

i have a very large DB. I need to run a query to search by email and load_date (date/timestamped field). I need to pull 3 email users from 3 different dates.

So I need a single table to display the emails (email field):

[email protected] [email protected] finalemail.yosite.com 

for the dates (load_date field):

2014-08-01 2014-08-06 2014-08-09 

If i run this:

SELECT email, load_date FROM table1 WHERE email = '[email protected]' or email = '[email protected]' or email = 'finalemail.yosite.com 

The results are correct.

If i run:

SELECT email, load_date FROM table1 WHERE load_date LIKE "2014-08-01%" or load_date LIKE "2014-08-06%" or load_date LIKE "2014-08-09%" 

The results are correct.

But if i combine them:

SELECT email, load_date FROM table1 WHERE email = '[email protected]' or email = '[email protected]' or email = 'finalemail.yosite.com' and load_date LIKE "2014-08-01%" or load_date LIKE "2014-08-6%" or load_date LIKE "2014-08-09%" 

I get everything!?

What am i doing wrong??

1
  • You need some parentheses. Commented Aug 14, 2014 at 17:35

3 Answers 3

3

The AND function has a higher order of precedence than the OR function. You need to encapsulate your ORs in parentheses.

SELECT email, load_date FROM table1 WHERE (email = '[email protected]' or email = '[email protected]' or email = 'finalemail.yosite.com') and (load_date LIKE "2014-08-01%" or load_date LIKE "2014-08-6%" or load_date LIKE "2014-08-09%") 
Sign up to request clarification or add additional context in comments.

Comments

3

You need to use parenthesis:

SELECT email, load_date FROM table1 WHERE (email = '[email protected]' or email = '[email protected]' or email = 'finalemail.yosite.com'( and (load_date LIKE "2014-08-01%" or load_date LIKE "2014-08-6%" or load_date LIKE "2014-08-09%") 

Comments

0

Binary operators are evaluated from left to right, and and has precedence over or.

Example: If condX are boolean conditions, then cond1 or cond2 and cond3 or cond4 is evaluated like this:

  1. cond1 or cond2
  2. [result of above] and cond3
  3. [result of above] and cond4

If you want to "alter" the order of evaluation of your conditions, you must enclose them in parenthesis.

In your specific case, you must enclose in parenthesis the email comparissons and the load_date comparissons:

WHERE (email = '[email protected]' or email = '[email protected]' or email = 'finalemail.yosite.com') and (load_date LIKE "2014-08-01%" or load_date LIKE "2014-08-6%" or load_date LIKE "2014-08-09%") 

The alternative: Use in:

WHERE email in ('[email protected]', '[email protected]', 'finalemail.yosite.com') AND date(load_date) in ("2014-08-01", "2014-08-6", "2014-08-09") -- date(load_date) extracts the date part of the field 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.