SQL OR Operator
The OR
operator in SQL combines multiple conditions in a WHERE
clause. It selects rows where *at least one* of the conditions is true.
OR: Definition and Usage
OR
acts as a logical disjunction. It's like saying "this condition *or* that condition (or both) must be true". If any of the conditions connected by OR
is true, the entire expression is true, and the row is included in the results. Only if *all* conditions linked by `OR` are false will the row be excluded.
Syntax
Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
Example Database: Customers Table
The examples below use this sample 'Customers' table:
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
1 | Alfreds Futterkiste | Maria Anders | Obere Str. 57 | Berlin | 12209 | Germany |
2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Avda. de la Constitución 2222 | México D.F. | 05021 | Mexico |
3 | Antonio Moreno Taquería | Antonio Moreno | Mataderos 2312 | México D.F. | 05023 | Mexico |
4 | Around the Horn | Thomas Hardy | 120 Hanover Sq. | London | WA1 1DP | UK |
5 | Berglunds snabbköp | Christina Berglund | Berguvsvägen 8 | Luleå | S-958 22 | Sweden |
6 | Gusto Grezzo | Giovanni Rovelli | Via Degli Ortolani, 10 | Reggio Emilia | 42100 | Italy |
Examples
Simple OR Condition
This query selects customers from Germany or Spain.
Syntax
SELECT * FROM Customers
WHERE Country = 'Germany' OR Country = 'Spain';
Output
(Customers from Germany and Spain will be returned.)
Multiple OR Conditions
This query selects customers from Berlin, those whose names start with 'G', or those from Norway.
Syntax
SELECT * FROM Customers
WHERE City = 'Berlin' OR CustomerName LIKE 'G%' OR Country = 'Norway';
Output
(Customers matching any of the three conditions will be returned.)
Combining AND and OR
This example demonstrates combining AND
and OR
. Parentheses are crucial for correct logic.
Syntax
SELECT * FROM Customers
WHERE Country = 'Spain'
AND (CustomerName LIKE 'G%' OR CustomerName LIKE 'R%');
Output
(Spanish customers whose names start with 'G' or 'R' will be returned.)
Combining AND and OR (without parentheses - incorrect)
Illustrating the importance of parentheses. Without them, the logic changes.
Syntax
SELECT * FROM Customers
WHERE Country = 'Spain'
AND CustomerName LIKE 'G%' OR CustomerName LIKE 'R%';
Output
(This returns all customers whose names start with 'R', plus any customers from Spain whose names start with 'G'. The result is different from the previous example because of the missing parentheses.)