Course contentsShow
← Databases & SQL
Lesson 95 of 1,9532. Querying and Data RetrievalFree lesson

Filtering with Logical Precedence

Manage operator precedence to avoid common logic bugs in compound filter statements.

Mastering Logic with Parentheses

In this lesson, you will learn how to control the order in which SQL evaluates your filtering conditions to ensure your queries return exactly the data you expect.

The Conflict of AND vs OR

When you combine multiple conditions in a WHERE clause, SQL follows a strict hierarchy similar to "PEMDAS" in mathematics. In the world of SQL, the AND operator is evaluated before the OR operator. If you aren't careful, this can lead to logic bugs where the database returns rows that don't match your true intent.

Imagine you are querying a table of employees and want to find anyone who is either an "Engineer" or a "Manager," but only if they are currently "Active."

If you write this:

SELECT * FROM employees
WHERE job_title = 'Engineer' 
   OR job_title = 'Manager' 
  AND status = 'Active';

Because AND has higher precedence, the database reads this as: "Find me all Engineers, OR find me Managers who are also Active." You will end up with every single Engineer in the company, even those who are inactive, because the OR acts as a barrier that separates the first condition from the AND logic.

Solving Logic Bugs with Parentheses

To override the default precedence, you must use parentheses. Whatever is inside the parentheses is evaluated first, forcing the database to group your logic correctly.

By updating the query like this, you ensure the OR happens first, and then the result is filtered by the status:

SELECT * FROM employees
WHERE (job_title = 'Engineer' OR job_title = 'Manager')
  AND status = 'Active';

Now, the database evaluates the group inside the parentheses first—finding all potential Engineers and Managers—and then applies the AND status = 'Active' filter to that specific subset.

When you start mixing different logical operators, always use parentheses to make your intent explicit, rather than relying on the database's internal default behavior. This makes your code safer, more readable, and much less prone to errors.

Key Takeaway: Always use parentheses to group your logical conditions, as AND is evaluated before OR by default.