MySQL AND, OR, and NOT Operators
MySQL provides logical operators to combine conditions in SQL queries: AND
, OR
, and NOT
.
Using the AND Operator:
Example: Using AND
SELECT * FROM users
WHERE age > 25 AND gender = 'Male';
Selects all columns from the users
table where the age
is greater than 25 and the gender
is ‘Male’.
Using the OR Operator:
Example: Using OR
SELECT * FROM users
WHERE city = 'New York' OR city = 'Los Angeles';
Selects all columns from the users
table where the city
is either ‘New York’ or ‘Los Angeles’.
Using the NOT Operator:
Example: Using NOT
SELECT * FROM products
WHERE NOT category = 'Clothing';
Selects all columns from the products
table where the category
is not ‘Clothing’.
Combining Operators:
Example: Combining AND, OR, and NOT
SELECT * FROM orders
WHERE (total_amount > 1000 AND status = 'Delivered') OR (customer_id = 5 AND status = 'Pending');
Selects all columns from the orders
table where the total_amount
is greater than 1000 and the status
is ‘Delivered’, or the customer_id
is 5 and the status
is ‘Pending’.
Conclusion
The AND, OR, and NOT operators in MySQL allow for complex conditions to be constructed in SQL queries, enabling flexible and precise data retrieval based on specific criteria.