Last Updated: 02 July, 2023
In MySQL, we can use the AND and OR operators to combine multiple conditions in our queries. These operators are used to create more complex conditions that involve multiple criteria.
The AND operator is used when we want both conditions to be true for a particular row to be included in the result set. The OR operator is used when we want at least one of the conditions to be true for a row to be included in the result set.
The basic syntax for using AND and OR in a WHERE clause is as follows:
SELECT column1, column2, ... FROM table_name WHERE condition1 AND/OR condition2 AND/OR condition3 ...;
Let's look at some examples:
Suppose we have a table called "employees" and we want to retrieve employees who are in the "Sales" department and have a salary greater than 50000.
SELECT * FROM employees WHERE department = 'Sales' AND salary > 50000;
Suppose we have a table called "products" and we want to retrieve products that are either in the "Electronics" category or have a price less than 100.
SELECT * FROM products WHERE category = 'Electronics' OR price < 100;
Suppose we have a table called "orders" and we want to retrieve orders that are either from the "New York" region and placed after a specific date, or from the "California" region and placed by a specific customer.
SELECT * FROM orders WHERE (region = 'New York' AND order_date > '2023-01-01') OR (region = 'California' AND customer_id = 12345);
In this example, we used parentheses to group conditions together and make sure the logical operators are applied correctly.
Remember to properly structure our queries using parentheses when we have complex conditions to ensure the correct logical evaluation.
That's all, guys. I hope this MySQL article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com