Combining Multiple Logical Operators
You'll learn how to mix AND, OR, and NOT operators in a single WHERE clause to create sophisticated filters that match complex business requirements.
The Core Idea
In real-world scenarios, you rarely need just one simple condition. You often need to express logic like "find customers who are either in New York OR California, but NOT those who purchased in the last 30 days, AND whose account status is active." This requires combining multiple logical operators in one query.
When you chain operators together, SQL evaluates them in a specific order: NOT first, then AND, then OR. Just like multiplication happens before addition in math, SQL has its own priority rules. Use parentheses () to make your logic crystal clear and override the default order when needed.
Building Complex Filters
Think of it like a restaurant order: "I want pasta AND (marinara OR pesto), but NOT with mushrooms." The parentheses group the sauce choices together.
Here's how that looks in SQL:
SELECT *
FROM orders
WHERE status = 'active'
AND (region = 'NY' OR region = 'CA')
AND NOT order_date >= '2024-01-01';
This finds active orders from NY or CA that were placed before 2024. Without parentheses around the OR condition, SQL might interpret your logic differently than you intended.
Why Parentheses Matter
Always use parentheses when mixing AND with OR. This makes your intent explicit and prevents subtle bugs. It's like showing your work in math—it helps you and others understand the logic.
Key Takeaway: Combine AND, OR, and NOT operators with parentheses to build precise, multi-condition filters that express complex business rules clearly and correctly.