Academic Block

SQL AND, OR, NOT Get Certified

Learn how to combine multiple conditions in SQL using the AND, OR, and NOT logical operators.

What are AND, OR, and NOT?

SQL provides the AND, OR, and NOT operators to combine or reverse conditions. These operators are commonly used with the WHERE clause to filter database records.

AND requires all conditions to be true, OR requires at least one condition to be true, while NOT reverses the result of a condition.

Basic AND Syntax

The AND operator returns records only when all specified conditions are true.

What this code does: Looks through the products table and keeps only the rows where the category is Electronics and the price is above 10,000. Camera and Laptop pass both tests, while Headphones are Electronics but too cheap, and the Tripod is too cheap and not in Electronics. The result lists just the name and price of the two matching products.

WITH products(name, category, price) AS (
  VALUES
    ('Camera', 'Electronics', 45000),
    ('Tripod', 'Accessories', 5000),
    ('Laptop', 'Electronics', 65000),
    ('Headphones', 'Electronics', 8000)
)
SELECT name, price
FROM products
WHERE category = 'Electronics'
  AND price > 10000;

AND with Multiple Conditions

You can use more than two conditions with AND. Every condition must be satisfied for a row to be returned.

What this code does: Chains three conditions together to find top students: marks of at least 80, attendance of at least 90, and a grade of A. A student must pass all three checks to appear, so Michael (attendance too low), Emily (marks too low) and Olivia (attendance too low and grade B) are filtered out. Only James and William are returned.

WITH students(name, marks, attendance, grade) AS (
  VALUES
    ('James', 88, 92, 'A'),
    ('Emily', 76, 95, 'B'),
    ('Michael', 91, 84, 'A'),
    ('Olivia', 82, 78, 'B'),
    ('William', 95, 97, 'A')
)
SELECT name, marks, attendance
FROM students
WHERE marks >= 80
  AND attendance >= 90
  AND grade = 'A';

Basic OR Syntax

The OR operator returns a record when at least one of the specified conditions is true.

What this code does: Returns every employee who works in the Sales department or the Design department. A row only needs to match one of the two conditions, so Sophia (Design), Daniel (Sales) and Jessica (Sales) are included. Matthew (Finance) and Emma (Marketing) match neither condition and are left out.

WITH employees(name, department) AS (
  VALUES
    ('Sophia', 'Design'),
    ('Daniel', 'Sales'),
    ('Matthew', 'Finance'),
    ('Emma', 'Marketing'),
    ('Jessica', 'Sales')
)
SELECT name, department
FROM employees
WHERE department = 'Sales'
   OR department = 'Design';

OR with Numbers

OR can also be used to compare numerical values.

What this code does: Finds books that are either very short (under 200 pages) or very long (over 400 pages), skipping the medium-length ones. Ocean Life (180 pages), Ancient Roads (410) and Hidden Forest (500) are returned, while Blue Planet (220) and Future City (350) fall in the middle range and do not match either condition.

WITH books(title, pages) AS (
  VALUES
    ('Blue Planet', 220),
    ('Ancient Roads', 410),
    ('Future City', 350),
    ('Ocean Life', 180),
    ('Hidden Forest', 500)
)
SELECT title, pages
FROM books
WHERE pages < 200
   OR pages > 400;

Basic NOT Syntax

The NOT operator reverses the result of a condition.

What this code does: Uses NOT to flip the condition status = 'Offline', so every device that is not offline is returned. Router A (Online), Router C (Online) and Router D (Maintenance) are shown, and only Router B, which is Offline, is excluded.

WITH devices(name, status) AS (
  VALUES
    ('Router A', 'Online'),
    ('Router B', 'Offline'),
    ('Router C', 'Online'),
    ('Router D', 'Maintenance')
)
SELECT name, status
FROM devices
WHERE NOT status = 'Offline';

NOT with IN

NOT IN is useful when you want to exclude several specific values from the results.

What this code does: Checks each city’s zone against a list of values and removes every city whose zone appears in that list. Because West and East are excluded, Pune, Surat and Patna are dropped, and only Jaipur (North) and Kochi (South) remain. This is shorter and easier to read than writing several NOT or AND comparisons.

WITH cities(name, zone) AS (
  VALUES
    ('Jaipur', 'North'),
    ('Pune', 'West'),
    ('Kochi', 'South'),
    ('Patna', 'East'),
    ('Surat', 'West')
)
SELECT name, zone
FROM cities
WHERE zone NOT IN ('West', 'East');

AND with OR

AND and OR can be combined to create more specific filtering conditions. Parentheses are recommended to clearly define the intended logic.

What this code does: Selects courses that are either cheap Technology courses (fee under 10,000) or any Arts course. The parentheses group the Technology rule together, so Web Design (9,000) qualifies but Robotics (12,000) does not. Painting and Music are included because they are Arts courses, whatever their fee. Astronomy is neither, so it is excluded.

WITH courses(course, category, fee) AS (
  VALUES
    ('Robotics', 'Technology', 12000),
    ('Painting', 'Arts', 7000),
    ('Web Design', 'Technology', 9000),
    ('Music', 'Arts', 14000),
    ('Astronomy', 'Science', 11000)
)
SELECT course, category, fee
FROM courses
WHERE (category = 'Technology' AND fee < 10000)
   OR category = 'Arts';

Using Parentheses

Parentheses control the order in which conditions are evaluated and make complex expressions easier to understand.

What this code does: Finds well-rated movies in two genres. The parentheses make SQL check the genre first (Sci-Fi or Action) and then require a rating of at least 8.0 on top of it. Sky World (8.5) and Night Chase (8.1) are returned, while Deep Space is the right genre but rated only 7.8, and the Drama titles fail the genre check.

WITH movies(title, genre, rating) AS (
  VALUES
    ('Sky World', 'Sci-Fi', 8.5),
    ('Last Road', 'Drama', 7.2),
    ('Deep Space', 'Sci-Fi', 7.8),
    ('Silent River', 'Drama', 8.7),
    ('Night Chase', 'Action', 8.1)
)
SELECT title, genre, rating
FROM movies
WHERE (genre = 'Sci-Fi' OR genre = 'Action')
  AND rating >= 8.0;

Combining AND, OR, and NOT

All three logical operators can be combined when a query requires multiple levels of filtering.

What this code does: Finds in-stock Electronics priced above 25,000. The first condition (in parentheses) keeps expensive Electronics, and NOT stock = 0 then removes anything that is out of stock. Laptop and Tablet are returned, while the Camera is dropped because its stock is 0, and the Chair and Desk are Furniture.

WITH products(name, category, price, stock) AS (
  VALUES
    ('Laptop', 'Electronics', 70000, 12),
    ('Camera', 'Electronics', 45000, 0),
    ('Chair', 'Furniture', 8000, 20),
    ('Desk', 'Furniture', 15000, 5),
    ('Tablet', 'Electronics', 30000, 8)
)
SELECT name, category, price, stock
FROM products
WHERE (category = 'Electronics' AND price > 25000)
  AND NOT stock = 0;

AND, OR, and NOT with LIKE

Logical operators can also be combined with pattern matching using LIKE.

What this code does: Searches for products whose name starts with “Smart” (the % wildcard matches any text after it) and then uses NOT to exclude the Home category. Smartphone Pro and Smartphone Mini are returned. Smart Lamp matches the name pattern but is removed because it belongs to Home, and the other products do not start with “Smart”.

WITH products(name, category) AS (
  VALUES
    ('Smartphone Pro', 'Mobile'),
    ('Smartphone Mini', 'Mobile'),
    ('Wireless Mouse', 'Computer'),
    ('Smart Lamp', 'Home'),
    ('Bluetooth Speaker', 'Audio')
)
SELECT name, category
FROM products
WHERE name LIKE 'Smart%'
  AND NOT category = 'Home';

AND, OR, and NOT with IN

IN can be combined with logical operators to include or exclude groups of values.

What this code does: Selects employees from the IT or Finance departments, and then uses NOT salary < 60000 to keep only those earning 60,000 or more. Robert, Christopher and Amanda meet both requirements and are returned. Jennifer (Sales) and Ashley (HR) are excluded because their departments are not in the list.

WITH employees(name, department, salary) AS (
  VALUES
    ('Jennifer', 'Sales', 52000),
    ('Robert', 'IT', 75000),
    ('Ashley', 'HR', 48000),
    ('Christopher', 'Finance', 68000),
    ('Amanda', 'IT', 62000)
)
SELECT name, department, salary
FROM employees
WHERE department IN ('IT', 'Finance')
  AND NOT salary < 60000;

Logical Operator Precedence

SQL evaluates logical operators in a specific order. In general, NOT is evaluated before AND, and AND is evaluated before OR.

What this code does: Shows what happens without parentheses. Because AND runs first, SQL reads the condition as “Math, or (Science and score of 85 or more)”. That means every Math student is returned whatever their score, so Ethan (72) and Noah (92) both appear, together with Isabella, the only Science student who scored 85 or higher. This is often not what the author intended.

WITH students(name, subject, score) AS (
  VALUES
    ('Ethan', 'Math', 72),
    ('Sophia', 'Science', 78),
    ('Noah', 'Math', 92),
    ('Isabella', 'Science', 88),
    ('Liam', 'History', 95)
)
SELECT name, subject, score
FROM students
WHERE subject = 'Math'
   OR subject = 'Science'
  AND score >= 85;

Using Parentheses for Clear Logic

Using parentheses makes the intended logic explicit and avoids confusion when combining multiple logical operators.

What this code does: Runs the same data as the previous example, but the parentheses force SQL to check “Math or Science” first and then require a score of 85 or more for every student. Ethan (Math, 72) is now excluded, and only Noah (92) and Isabella (88) are returned. Compare this with the previous result to see how parentheses change the outcome.

WITH students(name, subject, score) AS (
  VALUES
    ('Ethan', 'Math', 72),
    ('Sophia', 'Science', 78),
    ('Noah', 'Math', 92),
    ('Isabella', 'Science', 88),
    ('Liam', 'History', 95)
)
SELECT name, subject, score
FROM students
WHERE (subject = 'Math' OR subject = 'Science')
  AND score >= 85;

AND, OR, NOT Comparison

Operator
Purpose
Example
AND
All conditions must be true
price > 1000 AND stock > 0
OR
At least one condition must be true
category = 'Book' OR category = 'Music'
NOT
Reverses a condition
NOT status = 'Closed'
NOT IN
Excludes specified values
city NOT IN ('Delhi','Pune')

Advantages of AND, OR, and NOT

  • Allows multiple filtering conditions in a single query.
  • Helps create precise database searches.
  • AND can restrict results using multiple requirements.
  • OR can match any one of several conditions.
  • NOT can exclude unwanted records.
  • Parentheses can be used to build complex logical expressions.

Best Practices

  • Use parentheses when combining AND and OR.
  • Keep complex conditions easy to read and understand.
  • Use AND when every condition must be satisfied.
  • Use OR when any one of several conditions can match.
  • Use NOT when you need to exclude a condition.
  • Test complex logical expressions with sample data before using them on large tables.

The AND, OR, and NOT operators are essential for creating flexible SQL conditions. Click Test My Code on any example above to run it live, or Code Explanation to walk through the query block by block.

Ctrl + Enter to run code in the editor Esc to close the editor

🧪 Test Your SQL Code

Edit the SQL code on the left and click “Run Code” to see the result on the right.

📝 SQL Code
👁️ Preview (query result)

Click “Run Code” to see the result here.