Start Coding

Topics

SQL AND, OR, and NOT Operators

SQL logical operators are essential tools for filtering data and creating complex conditions in database queries. The AND, OR, and NOT operators allow you to combine multiple conditions and refine your search criteria.

AND Operator

The AND operator is used to combine two or more conditions. It returns true only if all the conditions are true.

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

This query retrieves all employees in the Sales department with a salary greater than 50,000.

OR Operator

The OR operator returns true if at least one of the conditions is true. It's useful for creating inclusive filters.

SELECT * FROM products
WHERE category = 'Electronics' OR price < 100;

This example selects all products that are either in the Electronics category or cost less than 100.

NOT Operator

The NOT operator negates a condition. It's often used with other operators to create exclusions.

SELECT * FROM customers
WHERE NOT country = 'USA';

This query retrieves all customers who are not from the USA.

Combining Operators

You can combine these operators to create more complex conditions. Parentheses help clarify the order of operations.

SELECT * FROM orders
WHERE (status = 'Shipped' OR status = 'Processing')
AND NOT total_amount < 1000;

This example selects orders that are either Shipped or Processing, with a total amount of 1000 or more.

Best Practices

  • Use parentheses to group conditions and ensure clarity
  • Consider the order of evaluation: AND is typically evaluated before OR
  • Test complex conditions separately to verify expected results
  • Use SQL Index Optimization techniques for better performance on frequently used conditions

Related Concepts

To further enhance your SQL querying skills, explore these related topics:

By mastering these logical operators, you'll be able to create precise and efficient SQL queries, enhancing your data retrieval and analysis capabilities.