1

I'm reading a book Sams Teach Yourself SQL in 10 minutes (although its impossible to read in 10 minutes) and in the answer in one of the exercises confuses me, im not sure whether the answer provided is correct. (Hour 8 Exercise item #2, answer is in the appendix)

Write a SELECT statement that returns customer IDs and customer names (alpha order) for customers who live in Indiana, Ohio, Michigan, and Illinois, with names that begin with the letters A or B.

SELECT CUST_ID, CUST_NAME, CUST_STATE
FROM CUSTOMER_TBL
WHERE CUST_STATE IN ('IN', 'OH', 'MI', 'IL')
AND CUST_NAME LIKE 'A%'
OR CUST_NAME LIKE 'B%'
ORDER BY CUST_NAME;

wont this query return customer IDs and customer names for customers whos name start with the letter B but do not live in the states mentioned?

shouldn't it be

 SELECT CUST_ID, CUST_NAME, CUST_STATE
 FROM CUSTOMER_TBL
 WHERE CUST_STATE IN ('IN', 'OH', 'MI', 'IL')
 AND (CUST_NAME LIKE 'A%' OR CUST_NAME LIKE 'B%')
 ORDER BY CUST_NAME;
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
jantristanmilan
  • 4,188
  • 14
  • 53
  • 69
  • 1
    You are correct. His answer will return all rows that have the specified states and start with the letter A, or the row that has a name that starts with the letter B – steinmas Feb 27 '14 at 19:20
  • 1
    Yes, you are correct. Since [MySQL gives a higher precedence to `AND` than to `OR`](https://dev.mysql.com/doc/refman/5.0/en/operator-precedence.html), the book's example does indeed return all those starting with `B%`, or the combination of `A%` and the states list. – Michael Berkowski Feb 27 '14 at 19:20
  • Additionally, the question is poor in that how many people actually live in 4 states simultaneously, but the wording should have been more like live in one of the following states: Indiana, Ohio, Michigan, or Illinois and the names begin with either A or B. – DRapp Feb 27 '14 at 19:32

0 Answers0