OR Operator
SQL · Filtering Rows
Theory
OR combines two conditions and is TRUE when at least one of them is TRUE. WHERE dept = 'IT' OR dept = 'HR' keeps employees from either department. Each extra OR can only widen the result, which is the opposite of AND.
OR has lower precedence than AND, so WHERE dept = 'HR' OR dept = 'IT' AND salary > 80000 means HR employees plus high-paid IT employees, which may not be what you meant. Write (dept = 'HR' OR dept = 'IT') AND salary > 80000 to apply the salary rule to both. With NULLs, TRUE OR UNKNOWN is TRUE, but FALSE OR UNKNOWN is UNKNOWN and the row is dropped. Several ORs on the same column are clearer as IN ('IT', 'HR').
Why we use it
Many questions accept alternatives: either of two cities, any of several statuses. OR lets one query match rows meeting any of the rules instead of running separate queries and combining them.
When to use it
Use OR when any one condition is enough. For many values of the same column, IN is shorter and easier to read. Wrap OR groups in parentheses whenever AND is also present.
How it works
- Read a row
- Evaluate the first condition
- Is it TRUE? Yes: Keep the row (one TRUE is enough). No: Evaluate the next condition.
- Any remaining condition TRUE? Yes: Keep the row. No: Discard the row.
- Move to the next row
Syntax
SELECT columns FROM table
WHERE cond1 OR cond2;Example
SELECT * FROM employees WHERE department = 'IT' OR department = 'HR';Key points
- Only one condition needs to be true
- Mixing AND/OR needs parentheses to control precedence
- Each OR can only widen the result
- Many ORs on one column read better as IN (...)
- TRUE OR UNKNOWN is TRUE; FALSE OR UNKNOWN drops the row