SQL And, Or, Not
In SQL, “AND,” “OR,” and “NOT” are logical operators used to combine or negate conditions in a query’s WHERE clause. These operators allow you to create more complex and specific conditions for filtering data from database tables. Here’s a brief explanation of each operator:
- AND: The AND operator is used to specify that all conditions separated by it must be true for a row to be included in the result set. It narrows down the result by making the query more restrictive. For example:sql
SELECT * FROM customers WHERE age >= 18 AND country = 'USA';
This query selects all customers who are at least 18 years old and reside in the USA.
OR: The OR operator is used to specify that at least one of the conditions separated by it must be true for a row to be included in the result set. It broadens the result by making the query less restrictive. For example:
sql
SELECT * FROM products WHERE category = 'Electronics' OR price < 1000;
This query selects all products that belong to the Electronics category or have a price below 1000.
NOT: The NOT operator is used to negate a condition, excluding rows that meet the specified condition. It reverses the logical meaning of the condition. For example:
sql
SELECT * FROM employees WHERE NOT department = 'HR';
This query selects all employees who do not work in the HR department.
These logical operators can be combined to create more complex conditions using parentheses to establish the desired order of evaluation.