Logical Operators
Logical operators in SQL are used to combine multiple conditions in WHERE clauses, HAVING clauses, or in join conditions. They allow you to create complex filters and conditions in your queries.
List of Logical Operators
Operator | Description |
---|---|
AND | Returns true if all the conditions separated by AND are TRUE |
OR | Returns true if any of the conditions separated by OR is TRUE |
NOT | Reverses the result, returns false if the condition is true |
Examples
AND Operator
SELECT * FROM products
WHERE category = 'Electronics' AND price < 500;
This query selects all electronic products priced under 500.
OR Operator
SELECT * FROM employees
WHERE department = 'Sales' OR department = 'Marketing';
This query selects all employees in either the Sales or Marketing departments.
NOT Operator
SELECT * FROM orders
WHERE NOT status = 'Shipped';
This query selects all orders that have not been shipped.
Combining AND and OR
SELECT * FROM customers
WHERE (country = 'USA' OR country = 'Canada')
AND (credit_limit > 1000);
This query selects customers from the USA or Canada with a credit limit over 1000.
Using Parentheses for Complex Conditions
SELECT * FROM products
WHERE (category = 'Electronics' AND price < 500)
OR (category = 'Books' AND price < 20);
This query selects electronics under 500 or books under 20.
Remember to use parentheses to group conditions when combining AND and OR operators to ensure your query is interpreted correctly.