Skip to main content

AND, OR, NOT

Learning Focus

Master AND, OR, and NOT to build complex, precise WHERE conditions in DuckDB.

Logical Operators

OperatorDescription
ANDBoth conditions must be true
ORAt least one condition must be true
NOTInverts the condition

Truth Table

ABA AND BA OR BNOT A
truetruetruetruefalse
truefalsefalsetruefalse
falsefalsefalsefalsetrue
NULLtrueNULLtrueNULL
NULLfalsefalseNULLNULL

Examples

-- AND: both must be true
SELECT * FROM employees
WHERE department = 'Engineering' AND salary > 85000;

-- OR: either must be true
SELECT * FROM employees
WHERE department = 'HR' OR active = false;

-- NOT: invert
SELECT * FROM employees
WHERE NOT department = 'HR';
-- equivalent to: WHERE department != 'HR'

-- Combine all three
SELECT * FROM employees
WHERE (department = 'Engineering' OR department = 'Finance')
AND salary > 75000
AND NOT active = false;

Operator Precedence

NOT > AND > OR — use parentheses for clarity:

-- Ambiguous (AND binds before OR)
SELECT * FROM employees
WHERE department = 'HR' OR department = 'Finance' AND salary > 70000;

-- Explicit with parentheses (recommended)
SELECT * FROM employees
WHERE (department = 'HR' OR department = 'Finance') AND salary > 70000;

Common Pitfalls

PitfallConsequencePrevention
Missing parentheses with mixed AND/ORWrong rows filteredAlways group OR conditions with ()
NOT IN with NULLs in listReturns empty resultUse NOT EXISTS or filter NULLs from the list
Redundant conditionsSlower queriesRemove overlapping conditions

Quick Reference

WHERE cond1 AND cond2
WHERE cond1 OR cond2
WHERE NOT cond
WHERE (cond1 OR cond2) AND cond3

What's Next