๐ What Youโll Learn
- What the
OR
operator does - Syntax and structure
- Combining multiple conditions
- Real-world examples
- Common pitfalls to avoid
๐ What Is the OR Operator?
The OR
operator in SQL allows you to filter rows that match any of the given conditions. It returns rows if at least one condition is true.
๐งฑ Basic Syntax
SELECT column1, column2
FROM table_name
WHERE condition1 OR condition2;
This means:
Return rows where either condition1 or condition2 is true.
๐ Example: Using OR
Suppose we have a table customers
with columns: name
, city
, country
.
SELECT name
FROM customers
WHERE country = 'USA' OR country = 'Canada';
โ This will return customers from either the USA or Canada.
๐งช More Examples
Products that are either on sale or out of stock
SELECT product_name
FROM products
WHERE on_sale = 1 OR stock = 0;
Employees in either the Marketing or Sales department
SELECT name, department
FROM employees
WHERE department = 'Marketing' OR department = 'Sales';
โ ๏ธ Common Pitfalls
- โ Forgetting parentheses when mixing
AND
andOR
:
-- Might not behave as expected
SELECT * FROM users
WHERE country = 'USA' OR country = 'UK' AND active = 1;
-- โ
Better with parentheses
SELECT * FROM users
WHERE (country = 'USA' OR country = 'UK') AND active = 1;
- โ Assuming
OR
is inclusive of all conditions unless grouped properly
๐ Recap
OR
returns results if any condition is true- Useful when filtering multiple possible values
- Always use parentheses when combining with
AND
- Clear logic prevents unexpected results