SQL AND, OR and NOT

Real questions usually have more than one condition: customers in Germany who signed up this year, products that are cheap or out of stock. AND, OR and NOT let you combine conditions in a single WHERE clause.

AND requires both conditions to be true. OR requires at least one. NOT reverses a condition. When you mix AND and OR, use parentheses: AND is evaluated first, which often surprises people.

Syntax

WHERE condition1 AND condition2
WHERE condition1 OR condition2
WHERE NOT condition

Try it yourself

Run the example below on a real PostgreSQL database, then change it and run it again. Nothing to install, no sign-up.

and-or-not.sql · PostgreSQL
Loading editor…

Examples

1. AND

SELECT first_name, salary FROM employees WHERE department_id = 1 AND salary > 80000;

Both conditions must hold.

2. OR with parentheses

SELECT name, category, price FROM products WHERE (category = 'Books' OR category = 'Toys') AND price < 30;

Without the parentheses, the price filter would only apply to Toys.

3. NOT

SELECT id, status FROM orders WHERE NOT status = 'delivered';

Same as status <> 'delivered'.

Common mistakes

  • Mixing AND and OR without parentheses and getting rows you didn't expect.
  • Writing WHERE country = 'Japan' OR 'France'. Each side of OR needs a full condition (or use IN).

Practice: test yourself

This challenge is from our interactive course. Write the query and press Check answer.

Challenge · 10 pts

Return first_name, last_name and salary of employees in department 1 who earn more than 80000.

challenge.sql · PostgreSQL
Loading editor…

FAQ

Which runs first, AND or OR?

AND binds more tightly than OR, like multiplication before addition. Add parentheses to make your intention explicit.

Learn SQL step by step

65 hands-on exercises, streaks, a leaderboard and a certificate.

Start free →