Wednesday, December 18, 2024

SQL OR Operator

 The OR operator in SQL is used to combine multiple conditions in a WHERE clause. When you use OR, at least one of the conditions must be true for a record to be included in the result set. If any of the conditions connected by OR evaluates to TRUE, the entire condition will be TRUE.

Syntax

SELECT column1, column2, ... FROM table_name WHERE condition1 OR condition2 OR condition3 ... ;

Example 1: Simple Use of OR

Suppose we have a table called Employees and we want to find employees who are either in the "Sales" or "Marketing" department.

SELECT name, department FROM Employees WHERE department = 'Sales' OR department = 'Marketing';

In this example, the query will return all employees who belong to either the Sales or Marketing department.

Example 2: Combining OR with Other Conditions

You can also combine the OR operator with other operators like AND to create more complex conditions.

SELECT name, department, salary FROM Employees WHERE (department = 'Sales' OR department = 'Marketing') AND salary > 50000;

This query will return the names, departments, and salaries of employees who are either in the Sales or Marketing department and have a salary greater than 50,000.

Example 3: Using OR with NULL

You can also use OR to check for NULL values. For example, you might want to find employees whose department is either Sales or whose department is unknown (i.e., NULL).

SELECT name, department FROM Employees WHERE department = 'Sales' OR department IS NULL;

This will return all employees from the Sales department or those who do not have a department assigned (i.e., NULL).

No comments:

Post a Comment