π What Youβll Learn
- What the
ANDoperator does - Syntax and logic
- Combining multiple conditions
- Real-world examples
- Common mistakes
π What Is the AND Operator?
The AND operator is used in SQL to combine multiple conditions in a WHERE clause. All conditions joined by AND must be true for a row to be included in the result.
π§± Basic Syntax
SELECT column1, column2
FROM table_name
WHERE condition1 AND condition2;
This means:
Only return rows where both condition1 and condition2 are true.
π Example: Filtering with AND
Suppose we have a table employees with columns: name, age, department.
SELECT name
FROM employees
WHERE age > 30 AND department = 'Sales';
β This query returns employees who are over 30 and work in the Sales department.
βοΈ More Examples
Find users from USA who are active
SELECT name
FROM users
WHERE country = 'USA' AND status = 'active';
Get products in stock and under $50
SELECT product_name, price
FROM products
WHERE stock > 0 AND price < 50;
π§ Common Mistakes
β Forgetting parentheses when mixing
ANDwithOR:-- Can lead to unexpected results: SELECT * FROM users WHERE country = 'USA' OR country = 'UK' AND active = 1; -- β Better: SELECT * FROM users WHERE (country = 'USA' OR country = 'UK') AND active = 1;β Using
ANDwhen you meantOR, or vice versa β read your logic carefully!
π Recap
ANDcombines multiple conditions and all must be true- Helps you write precise and powerful filters
- Use parentheses when combining with
ORfor clarity - Always test your conditions for accuracy