The OR keyword in SQL is used in a WHERE clause to combine multiple conditions, and it returns records that satisfy at least one of the conditions. When you use OR, you specify multiple conditions, and if any of the conditions is true, the record is selected.
Syntax:
SELECT column1, column2, ...
FROM table_name
WHERE condition1
OR condition2
OR condition3;
Example 1: Using OR in a Query
Suppose you have a table called Employees and you want to retrieve the employees who either work in the "HR" department or have a salary greater than 50000. The query would look like this:
SELECT EmployeeID, Name, Department, Salary
FROM Employees
WHERE Department = 'HR'
OR Salary > 50000;
In this example, employees who belong to the "HR" department or have a salary greater than 50000 will be included in the result.
Example 2: Combining Multiple Conditions with OR
You can combine multiple conditions using OR. For example, if you want to find employees who are either in the "Sales" department, have a salary greater than 60000, or have been hired before 2020:
SELECT EmployeeID, Name, Department, Salary, HireDate
FROM Employees
WHERE Department = 'Sales'
OR Salary > 60000
OR HireDate < '2020-01-01';
Precedence of OR and AND
If you use both OR and AND in a single query, AND takes precedence over OR. You can use parentheses to explicitly define the order of evaluation. For example:
SELECT EmployeeID, Name, Department, Salary
FROM Employees
WHERE (Department = 'Sales' OR Department = 'HR')
AND Salary > 50000;
In this case, employees who are either in "Sales" or "HR" and have a salary greater than 50000 will be returned.
Summary
ORallows you to combine multiple conditions and retrieve rows that meet at least one of the conditions.- It is often used when you want to filter records based on multiple options or criteria.
No comments:
Post a Comment