PostgreSQL – OR Operator
The OR
operator is a logical operator used to combine multiple conditions in a WHERE
clause or other parts of a query. It’s used to ensure that at least one of the specified conditions is true for a particular row to be included in the query result.
The syntax for using the OR
operator is as follows:
SELECT columns FROM table_name WHERE condition1 OR condition2 OR ... OR conditionN;
Here’s an example of using the OR
operator:
SELECT product_name, price FROM products WHERE category = 'Electronics' OR category = 'Appliances';
In this example, the query will retrieve the product name and price for products that belong to either the ‘Electronics’ category or the ‘Appliances’ category.
You can use the OR
operator to combine any number of conditions to filter rows based on multiple criteria. At least one condition joined by OR
must be true for a row to be included in the query result.
You can also use parentheses to group conditions and control the order of evaluation when mixing AND
and OR
operators. For example:
SELECT first_name, last_name FROM employees WHERE (department = 'HR' AND salary > 50000) OR (department = 'IT' AND salary > 60000);
In this example, the query retrieves the first name and last name of employees who either belong to the ‘HR’ department with a salary greater than $50,000 or belong to the ‘IT’ department with a salary greater than $60,000.