๐ SQL AND, OR, NOT โ Combine Conditions Logically
๐งฒ Introduction โ Why Use Logical Operators?
In SQL, logical operators like AND, OR, and NOT are used to combine multiple conditions in the WHERE clause. These operators help you build flexible, powerful, and precise queries.
Use them to:
- ๐ Filter records using complex logic
- ๐ง Apply multiple checks in one query
- ๐ Build layered conditions for decision making
๐ฏ In this guide, youโll learn how to:
- Use
ANDto match multiple true conditions - Use
ORto match at least one condition - Use
NOTto exclude specific conditions - Combine them together with parentheses
โ 1. Using AND โ All Conditions Must Be True
SELECT *
FROM employees
WHERE department = 'Sales' AND salary > 50000;
โ Returns rows where both conditions are true.
๐ 2. Using OR โ At Least One Condition is True
SELECT *
FROM customers
WHERE country = 'USA' OR country = 'Canada';
โ Returns rows that match either of the two countries.
โ 3. Using NOT โ Negate a Condition
SELECT *
FROM users
WHERE NOT verified;
โ Returns users who are not verified.
๐งฎ 4. Combine AND, OR, and NOT
SELECT *
FROM employees
WHERE department = 'HR'
AND (salary > 60000 OR experience > 10)
AND NOT contract = 'temporary';
โ Parentheses ensure logical grouping and avoid confusion.
๐ Best Practices
| โ Do This | โ Avoid This |
|---|---|
| Use parentheses to clarify precedence | Mixing AND/OR without grouping |
| Keep conditions readable and indented | Writing all conditions in one line |
| Test complex logic with sample queries | Assuming condition flow without testing |
๐ Summary โ Recap & Next Steps
Logical operators like AND, OR, and NOT allow you to write advanced WHERE conditions that match complex business rules.
๐ Key Takeaways:
ANDrequires all conditions to be trueORrequires at least one condition to be trueNOTinverts or excludes results- Use parentheses to group conditions logically
โ๏ธ Real-World Relevance:
Used in search filters, fraud detection queries, report generation, and access control rules.
โก๏ธ Next up: Explore SQL IN and BETWEEN for simplified multi-value conditions.
โ FAQ โ SQL AND, OR, NOT
โ Can I use AND and OR together?
โ Yes, but use parentheses to control the condition flow.
โ What happens if I skip parentheses with AND/OR?
โ SQL may evaluate them in the wrong order. Always group your logic.
โ Is NOT the same as !=?
โ
No. NOT negates a whole condition, while != compares individual values.
โ Can I nest multiple conditions?
โ
Yes, you can combine as many AND, OR, NOT as needed using proper grouping.
โ Are these supported in all SQL databases?
โ
Yes, AND, OR, and NOT are part of standard SQL and supported everywhere.
Share Now :
