SQL And, Or, Not
The AND, OR, and NOT operators are used to filter data by combining or reversing conditions within a WHERE clause.
These logical operators allow you to move past basic single-condition filtering and build highly specific, conditional rules for your datasets.
The AND Operator (Both Must Be True)
The AND operator displays a record only if all the separated conditions evaluate to true.
SELECT column1, column2 FROM table_name
WHERE condition1 AND condition2;
Example:
Find all inventory items that are classified as "Electronics" and have less than 10 units remaining in stock.
SELECT product_name, stock_count
FROM inventory
WHERE category = 'Electronics' AND stock_count < 10;
The OR Operator (At Least One Must Be True)
The OR operator displays a record if any of the separated conditions evaluate to true.
SELECT column1, column2 FROM table_name
WHERE condition1 OR condition2;
Example:
Find customers who live either in "New York" or in "Los Angeles".
SELECT customer_name, cityFROM customers
WHERE city = 'New York' OR city = 'Los Angeles';
The NOT Operator (Reverse the Condition)
The NOT operator reverses the boolean outcome of a condition. It displays records where the specified condition is false.
SELECT column1, column2 FROM table_name
WHERE NOT condition;
Example:
Find all active employees who do not work in the "Sales" department.
SELECT first_name, department
FROM employees
WHERE NOT department = 'Sales';
Combining AND, OR, and NOT (Order of Operations)
When you mix these operators in a single query, SQL evaluates them in a strict chronological order:
- NOT is processed first.
- AND is processed second.
- OR is processed last.
Because AND takes precedence over OR, you must use parentheses () to group your conditions whenever you want to change this order. Without parentheses, your query will likely return incorrect, messy data.
Incorrect Syntax (Prone to errors):
This query attempts to find items under $20 that belong to either the Electronics or Toys category. However, because AND runs first, it actually finds all Electronics regardless of price, plus Toys under $20.
SELECT product_name, category, price
FROM products
WHERE category = 'Electronics' OR category = 'Toys' AND price < 20;
Correct Syntax (Using Parentheses):
Isolating the OR logic in parentheses forces SQL to group the categories first, and then apply the price ceiling filter to both.
SELECT product_name, category, price
FROM products
WHERE (category = 'Electronics' OR category = 'Toys') AND price < 20;