OR: Match Either Condition
The OR keyword combines conditions in a WHERE clause when any one of them can be true.
If at least one condition is true, the row is included in the result.
Syntax
SELECT column1, column2, ... FROM table_name
WHERE condition1 OR condition2 OR ...;
Example 1: Employees in HR or Marketing
SELECT name, department FROM employees
WHERE department = 'HR' OR department = 'Marketing';
Output:
name | department
-------+------------
Alice | HR
David | Marketing
Ryan | Marketing
Anna | HR
(4 rows)
This returns the employees from either department.
Example 2: Employees in HR or younger than 25
SELECT name, age, department FROM employees
WHERE department = 'HR' OR age < 25;
Output:
name | age | department
-------+-----+------------
Alice | 28 | HR
Mike | 24 | IT
Anna | 24 | HR
(3 rows)
This returns employees who are in HR, or are younger than 25. Anna matches both conditions, but she appears only once.
Combining AND and OR
You can combine AND and OR in one condition. Use parentheses () to group conditions and control the logic.
Example: Male employees in HR or Marketing
SELECT name, department, gender FROM employees
WHERE (department = 'HR' OR department = 'Marketing')
AND gender = 'male';
Output:
name | department | gender
-------+------------+--------
David | Marketing | male
Ryan | Marketing | male
(2 rows)
The parentheses matter. PostgreSQL checks AND before OR, just like multiplication comes before addition in math. Without the parentheses, this query would mean "HR employees, or male Marketing employees", and Alice and Anna would be in the result too.
Tip
Use OR when you want rows that match at least one of the conditions.
In the exercises, use OR on its own, and then together with AND.