OR Condition
This SQL tutorial explains how to use the SQL OR condition with syntax and examples.
Description
The SQL OR Condition is used to test multiple conditions, where the records are returned when any one of the conditions are met. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.
Syntax
The syntax for the SQL OR Condition is:
WHERE condition1 OR condition2 ... OR condition_n;
Parameters or Arguments
- condition1, condition2, ... condition_n
- Any of the conditions can be met for the records to be selected.
Note
- The SQL OR condition allows you to test 2 or more conditions.
- The SQL OR condition requires that any of the conditions (ie: condition1, condition2, condition_n) be must be met for the record to be included in the result set.
Example - With SELECT Statement
The first SQL OR condition example that we'll take a look at involves a SQL SELECT statement with 2 conditions:
SELECT * FROM suppliers WHERE city = 'New York' OR available_products >= 250;
This SQL OR condition example would return all suppliers that reside in either New York or have available_products greater than or equal to 250. Because the * is used in the SELECT statement, all fields from the suppliers table would appear in the result set.
Example - With SELECT Statement (3 conditions)
The next SQL OR example takes a look at a SQL SELECT statement with 3 conditions. If any of these conditions is met, the record will be included in the result set.
SELECT supplier_id FROM suppliers WHERE supplier_name = 'IBM' OR city = 'New York' OR offices > 5;
This SQL OR condition example would return all supplier_id values where the supplier's name is either IBM, city is New York, or offices is greater than 5.
Example - With INSERT Statement
The SQL OR condition can be used in the SQL INSERT statement.
For example:
INSERT INTO suppliers (supplier_id, supplier_name) SELECT account_no, name FROM customers WHERE city = 'New York' OR city = 'Newark';
This SQL OR condition example would insert into the suppliers table, all account_no and name records from the customers table that reside in either New York or Newark.
Example - With UPDATE Statement
The SQL OR condition can be used in the SQL UPDATE statement.
For example:
UPDATE suppliers SET supplier_name = 'HP' WHERE supplier_name = 'IBM' OR available_products > 36;
This SQL OR condition example would update all supplier_name values in the suppliers table to HP where the supplier_name was IBM or its available_products was greater than 36.
Example - With DELETE Statement
The SQL OR condition can be used in the SQL DELETE statement.
For example:
DELETE FROM suppliers WHERE supplier_name = 'IBM' OR employees <= 100;
This SQL OR condition example would delete all suppliers from the suppliers table whose supplier_name was IBM or its employees was less than or equal to 100.