SQL OR
With OR, a row is kept when at least one of the conditions is true.
sql
SELECT columns
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;Either condition
Customers from Spain or Portugal:
sql · try it yourself
SELECT name, city, country
FROM customers
WHERE country = 'Spain' OR country = 'Portugal'
ORDER BY name;name | city | country
--------------+--------+---------
Lena Andersen | Lisbon | Portugal
Pixel Studio | Madrid | Spain
(2 rows)
Conditions on different columns
OR conditions can test different columns. Products that are out of stock or very expensive:
sql · try it yourself
SELECT name, price, stock
FROM products
WHERE stock = 0 OR price > 80
ORDER BY name;name | price | stock
----------------------------+-------+------
Avocados | 4.5 | 0
Mechanical Keyboard | 89 | 12
Noise-Cancelling Headphones | 149 | 8
Sparkling Water | 4.6 | 0
(4 rows)
Combining AND with OR
AND binds more tightly than OR — just as * binds more tightly than +. This often surprises people:
sql · try it yourself
-- Intended: cancelled or processing orders of customer 5
SELECT order_id, customer_id, status
FROM orders
WHERE customer_id = 5 AND status = 'cancelled' OR status = 'processing'
ORDER BY order_id;order_id | customer_id | status
---------+-------------+-----------
1 | 5 | cancelled
5 | 5 | cancelled
9 | 5 | processing
25 | 2 | processing
35 | 2 | processing
36 | 22 | processing
37 | 18 | processing
38 | 22 | processing
39 | 15 | processing
40 | 20 | processing
(10 rows)
The database read it as (customer_id = 5 AND status = 'cancelled') OR status = 'processing', so it returned the processing orders of every customer. Parentheses fix it:
sql · try it yourself
SELECT order_id, customer_id, status
FROM orders
WHERE customer_id = 5 AND (status = 'cancelled' OR status = 'processing')
ORDER BY order_id;order_id | customer_id | status
---------+-------------+-----------
1 | 5 | cancelled
5 | 5 | cancelled
9 | 5 | processing
(3 rows)
Tip: Whenever you mix
ANDandOR, add parentheses — even when they are not strictly needed. Your future self will thank you.
Truth table
| A | B | A OR B |
|---|---|---|
| true | true | true |
| true | false | true |
| false | true | true |
| false | false | false |
| true | NULL | true |
| false | NULL | NULL |
OR vs IN
Many ORs on the same column can be written more compactly with IN:
sql
WHERE country = 'Spain' OR country = 'Portugal' OR country = 'Italy'
-- same as
WHERE country IN ('Spain', 'Portugal', 'Italy')Test yourself
How does SQL read a AND b OR c?
- a AND (b OR c)
- (a AND b) OR c
- It is an error
- (a OR c) AND b
What is false OR NULL?
- true
- false
- NULL (unknown)
- 0