OR Operator in SQL

The OR operator in SQL is used to combine multiple conditions in a WHERE clause. If any of the conditions separated by the OR operator is true, the row is included in the result set.

SQL Syntax

SELECT column_name(s)
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;

Examples: 1. Basic Usage of OR Operator: Suppose we have a table Employees with the columns EmployeeID, FirstName, LastName, and City.

SQL

SELECT EmployeeID, FirstName, LastName, City
FROM Employees
WHERE City = 'New York' OR City = 'Los Angeles';

This query selects all employees who are located in either New York or Los Angeles.
2. Combining OR with AND: We can combine the OR operator with the AND operator to create more complex conditions.

SQL

SELECT EmployeeID, FirstName, LastName, City, Department
FROM Employees
WHERE (City = 'New York' OR City = 'Los Angeles')
AND Department = 'Sales';

This query selects all employees who are located in either New York or Los Angeles and work in the Sales department.

3. Using OR with Subqueries: The OR operator can also be used with subqueries to create dynamic conditions.

Suppose we have two tables, Orders and Customers. We want to find orders that were placed by customers from either New York or have a total amount greater than $1000.

SQL

SELECT OrderID, CustomerID, TotalAmount
FROM Orders
WHERE CustomerID IN (SELECT CustomerID FROM Customers WHERE City = 'New York')
OR TotalAmount > 1000;

This query selects all orders where the customer is from New York or the total amount of the order is greater than $1000.

4. More Complex Subquery Example: Suppose we want to find employees who either work in the same city as the company's headquarters or have a hire date within the first year of the company's existence. Assume the company's headquarters is in the city found in the CompanyDetails table.

SQL

SELECT EmployeeID, FirstName, LastName, City, HireDate
FROM Employees
WHERE City = (SELECT HeadquartersCity FROM CompanyDetails)
OR HireDate BETWEEN '2022-01-01' AND '2022-12-31';

This query selects all employees who work in the city where the company's headquarters is located or who were hired in the year 2022. Important Notes

Using the OR operator in SQL helps in writing queries that can filter data based on multiple conditions, making it a versatile tool for database querying.