datalitico.com

Using Logical Operators (AND, OR) in WHERE Clauses

In SQL, logical operators such as AND and OR can be used in the WHERE clause to combine multiple conditions and create more complex filtering criteria. These operators allow you to specify conditions that involve multiple columns or comparisons, which makes queries more efficient in getting right results.

AND Operator

The AND operator is used to combine multiple conditions, and all conditions must be true for a row to be included in the result set.

SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2;
  • condition1, condition2: Represents individual conditions that you want to combine using the AND operator.

Let’s write a query to retrieve all columns from the “employees” table where the department is ‘Sales’ and the salary is greater than 50,000.

SELECT *
FROM employees
WHERE department = 'Sales' AND salary > 50000;

OR Operator

The OR operator is used to specify that at least one of the conditions must evaluate to true for a row to be included in the result set.

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

Following query will retrieve all columns from the “employees” table where the department is either ‘Sales’ or ‘Marketing’.

SELECT *
FROM employees
WHERE department = 'Sales' OR department = 'Marketing';

Combining AND and OR

You can use both the AND and OR operators together to create more complex conditions. Parentheses are used to group conditions and define the order of evaluation.

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

Now we will retrieve all columns from the “employees” table where the department is either ‘Sales’ and the salary is greater than 50,000, or the department is ‘Marketing’.

SELECT *
FROM employees
WHERE (department = 'Sales' AND salary > 50000) OR department = 'Marketing';

Logical operators (AND, OR) in WHERE clauses allow you to create more complex filtering conditions by combining multiple conditions. By utilizing these operators effectively, you can retrieve the specific data that meets your criteria and gain more control over the result set.

Scroll to Top