SQL OR Operator

📘 SQL OR Operator

The OR operator in SQL is used inside the WHERE clause to combine conditions.
A row is returned if at least one of the conditions is TRUE.


1. Basic Syntax

SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2;

2. Example: Simple OR Condition

Get employees from either the IT or HR department:

SELECT name, department
FROM employees
WHERE department = 'IT'
OR department = 'HR';

If either condition matches, the row is returned.


3. Using OR with Different Columns

SELECT *
FROM products
WHERE price < 50
OR in_stock = FALSE;

This returns:

  • Items priced under 50

  • OR items that are out of stock


4. Combining OR with AND

Logical grouping matters!

❌ Without parentheses (may cause unexpected results):

SELECT *
FROM orders
WHERE status = 'pending'
OR customer_id = 10
AND amount > 100;

AND has higher precedence than OR.

✔ Correct (use parentheses):

SELECT *
FROM orders
WHERE (status = 'pending' OR customer_id = 10)
AND amount > 100;

5. OR with IN (Cleaner Syntax)

Instead of:

WHERE department = 'HR' OR department = 'IT' OR department = 'Finance';

Use:

WHERE department IN ('HR', 'IT', 'Finance');

6. OR with LIKE

SELECT *
FROM customers
WHERE name LIKE 'A%'
OR name LIKE 'B%';

7. Real-World Example

Return users who are:

  • located in the US or

  • have verified their email

SELECT user_id, email
FROM users
WHERE country = 'USA'
OR email_verified = TRUE;

8. Common Mistake to Avoid

Don’t overuse OR when an index can’t help.

If conditions are very different, OR can slow down queries.
You can often rewrite OR as a UNION for better performance.

Example:

SELECT * FROM users WHERE status = 'active'
UNION
SELECT * FROM users WHERE role = 'admin';

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *