← Back to PostgreSQL Course | Chapter 2: Basic Queries | Lesson 4 of 7

Logical operators (AND OR NOT)

AND, OR and NOT combine conditions, with parentheses controlling the order.
Syntax
sql
WHERE condition1 AND condition2
WHERE condition1 OR condition2
WHERE NOT condition

Logical operators (AND OR NOT)

AND requires both conditions, OR requires at least one, and NOT reverses a condition. AND is evaluated before OR, so use parentheses when mixing them. Any comparison with NULL yields NULL (unknown), which WHERE treats as false.

Note: Add parentheses whenever you mix AND and OR.

Example: Logical operators (AND OR NOT)

sql
CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, city TEXT, age INTEGER);
INSERT INTO users VALUES (1, 'Ada', 'London', 36), (2, 'Bob', 'Oslo', 25), (3, 'Cy', 'Oslo', 41), (4, 'Di', 'Rome', 30);
SELECT name FROM users WHERE city = 'Oslo' AND age > 30;
SELECT name FROM users WHERE city = 'Rome' OR age > 40;
SELECT name FROM users WHERE NOT city = 'Oslo';
SELECT name FROM users WHERE (city = 'Oslo' OR city = 'Rome') AND age < 35;

-- Output:
-- name
-- Cy
-- name
-- Cy
-- Di
-- name
-- Ada
-- Di
-- name
-- Bob
-- Di
Related Topics
Common Mistakes
  1. Forgetting AND has higher precedence than OR
  2. Ignoring NULL in NOT conditions
  3. Overly long unparenthesised conditions
Chapter Summary
  • AND both, OR either, NOT reverse
  • AND binds tighter than OR
  • Use parentheses to be explicit
  • NULL makes a condition unknown
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.