Was wondering whether anyone would know why do we use the parentheses in this SQL:
So, the format goes as follows:
Name,location and department of the service of the employees whose name starts with A or B. (A rough translation from French).
I answered the following way:
SELECT service.nom_serv, localite.ville, localite.departemen
FROM service, localite, employe
WHERE service.code_loc=localite.code_loc
AND employe.service=service.code_serv
AND ((employe.nom LIKE 'A%') OR (employe.nom LIKE 'B%'))
Basically, where the last AND is concerned for the WHERE, couldn't I simply do without the parenthesis in order to have the SQL select for me employees with their name starting either with an A or a B? What difference does positioning a parenthesis in that way make? And ahy is there a double use of parentheses? Or is it to prioritize the OR in the last clause, since an AND is preceding it?
Take a look at the Operator Precedence in SQL Server (You've not specified that, but I'd imagine it's the same for all RDBMS). What this means is that ANDs (without parenthesis) are evaluated before1 bind more tightly than ORs.
So in your specific case, without the parenthesis, the conditions are:
employe.service=service.code_serv AND employe.nom LIKE 'A%'
OR
1Evaluation order is deliberately not specified in SQL, allowing many more possible re-orderings that languages that guarantee left-to-right or precedence ordered evaluation.
You use it to specify grouping of the clause, not priority. SQL does not allow you to specify priority as the optimizer will create the best priority for you.
AND ()
Will take both of the OR
conditions in one statement. So if either is true then the AND
is true as well. The inner parentheses are not necessary, but help in visualizing the separation.
Without the outer parentheses it would allow anything with the final clause as true as well.
There are extra parenthesis. The rule in math is to add the parenthesis to clarify the logic. In this case if you remove all of the parenthesis you'll get the wrong answer. What you have is a AND ((b) OR (c)). Removing all of the parenthesis would take it from (a OR b) AND (a OR c) to (a AND b) OR c which is incorrect.