Aral Code

Filtering & Sorting Lesson 5 of 21

SQL AND, OR and NOT

Combine several conditions in WHERE with AND, OR and NOT, and use parentheses to make complex filters work correctly.

Real questions often have more than one condition: "drinks that cost less than ₱30", "customers from Poblacion or Rizal". Combine conditions with AND, OR and NOT.

AND: all conditions must be true

SQL Drinks under ₱30
SELECT name, category, price
FROM products
WHERE category = 'Drinks' AND price < 30;
SQL Grade 10 students in section Rizal
SELECT first_name, last_name
FROM students
WHERE grade = 10 AND section = 'Rizal';

OR: at least one condition must be true

SQL Customers from Poblacion or Rizal
SELECT name, barangay
FROM customers
WHERE barangay = 'Poblacion' OR barangay = 'Rizal';

NOT: reverse a condition

SQL Everything except drinks
SELECT name, category
FROM products
WHERE NOT category = 'Drinks';

NOT category = 'Drinks' means the same as category <> 'Drinks'. NOT is more useful with IN, LIKE and BETWEEN, which you'll learn soon.

Mixing AND and OR: use parentheses

AND is evaluated before OR, like multiplication before addition. This can give surprising results. Suppose Aling Nena wants "Drinks or Snacks that cost more than ₱20":

SQL Without parentheses: wrong!
SELECT name, category, price
FROM products
WHERE category = 'Drinks' OR category = 'Snacks' AND price > 20;

Coffee (₱8) and Bottled Water (₱20) appear, even though they aren't more than ₱20! SQL read the condition as "Drinks" OR ("Snacks" AND price > 20), so every drink was included. Parentheses fix it:

SQL With parentheses: correct
SELECT name, category, price
FROM products
WHERE (category = 'Drinks' OR category = 'Snacks') AND price > 20;

Now only the Softdrink (₱75) is left, which is the right answer.

A practical example: who to remind

SQL Unpaid orders from early November
SELECT id, customer_id, order_date
FROM orders
WHERE status = 'utang' AND order_date < '2026-11-15';

Honor students

SQL Scores of 90 and above in Math or Science
SELECT student_id, subject, score
FROM grades
WHERE (subject = 'Math' OR subject = 'Science') AND score >= 90;

Truth table

ABA AND BA OR B
truetruetruetrue
truefalsefalsetrue
falsetruefalsetrue
falsefalsefalsefalse

Quick Quiz

Check what you learned. Walang grade ito, practice lang. 🙂

1. Which finds Grade 9 students in section Mabini?
2. Which is evaluated first?
3. What does WHERE NOT stock > 50 return?
4. When should you add parentheses?

By Sir Reyel · Last updated 2026-12-04