SQL OR Operator
The SQL OR operator is a logical operator used in SQL (Structured Query Language) to combine multiple conditions in a WHERE clause to retrieve rows from a database table. It allows you to retrieve rows that meet at least one of the specified conditions, as opposed to the AND operator, which requires all conditions to be true for a row to be included in the result set.
The syntax for using the OR operator in SQL is as follows:
1 2 3 |
SELECT column1, column2, ... FROM table_name WHERE condition1 OR condition2 OR condition3 ...; |
Here’s a simple example to illustrate how the OR operator works:
Suppose you have a table called “employees,” and you want to retrieve all employees who are either in the “Sales” department or have a salary greater than $50,000. You can use the OR operator as follows:
1 2 3 |
SELECT * FROM employees WHERE department = 'Sales' OR salary > 50000; |
In this query, the OR operator is used to combine two conditions: one that checks if the department is “Sales” and another that checks if the salary is greater than $50,000. The result will include all rows that meet either of these conditions.
Suppose you have a “products” table with the following columns: “product_id,” “product_name,” “category,” and “price.” You want to retrieve products that are either in the “Electronics” category or have a price less than $100.
Here’s how you can use the SQL OR operator for this query:
1 2 3 |
SELECT product_id, product_name, category, price FROM products WHERE category = 'Electronics' OR price < 100; |
In this query:
- The
WHERE
clause specifies two conditions separated by theOR
operator:- The first condition checks if the “category” column is equal to ‘Electronics.’
- The second condition checks if the “price” column is less than 100.
- The
OR
operator combines these conditions. As a result, the query will return products that are either in the “Electronics” category or have a price less than $100.
So, the SQL OR operator allows you to retrieve rows that satisfy at least one of the specified conditions, making your queries more flexible and versatile.