Are parentheses necessary in SQL: In this article will explain the difference between a simple SQL select query using with parentheses and using without parentheses, and you will notice the different results of each query. One day, my junior asked me one question why I am using parentheses ( brackets ) in most of my SQL queries and is it really necessary to use round brackets? Then I thought why not make a post on it, so it helps others?My answer was YES, I use parenthesis to bind components of where clauses, i.e., If the query has multiple and or conditions, then it's necessary to use parentheses to ensure the correct order of operations. In short for complex queries, it is necessary to use a round Bracket and for a simple query, you can avoid a round bracket. Let's see with an example:
Example 1: Simple SQL query with/without parenthesis
- Simple Query without parenthesis:
Here's the output of the above simple SQL query:
SELECT * FROM employee WHERE department_id=1
- Simple Query with Parenthesis: Now we write the same query with parenthesis.
Here's the output of the above query:
SELECT * FROM employee WHERE (department_id=1)
As you will see both give the same result. In example 1, it won't affect the result as it's a simple query. Now let's see Example 2
Example 2: Complex SQL query with/without parenthesis (using and/or condition)
- Complex SQL Query without parenthesis:
Here's the result: SQL query without parenthesis.
SELECT * FROM employee WHERE department_id=1 OR department_id=2 AND salary < 3000
- Complex SQL Query without parenthesis: Now we write the same query with parenthesis .i.e using a round bracket over and/or condition.
Here's the result of the above query:
SELECT * FROM employee WHERE (department_id=1 OR department_id=2) AND (salary < 3000)
You can easily get an idea both results are different. Here in example 2, round brackets determine the order that the AND and OR conditions are evaluated, the same as what we learned in math order of operation (BODMAS).
Parentheses tell SQL Server to ignore the order of evaluation and assess what is in the parentheses first then evaluate the second part of the WHERE clause. Using SQL and or queries without parentheses gives incorrect records.
Other Reference Link:
Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.
PS: If you found this content valuable and want to thank me? 👳 Buy Me a Coffee