Saturday, November 10, 2012

"OR" Condition in SQL

The SQL "OR" condition allows you to create an SQL statement where records are returned when any one of the conditions are met. It can be used in any valid SQL statement - SQL SELECT statement, SQL INSERT Statement, SQL UPDATE Statement, SQL DELETE Statement.


The syntax for the SQL OR condition is:
SELECT columns
FROM tables
WHERE column1 = 'value1'
or column2 = 'value2';
The SQL "OR" condition requires that any of the conditions be must be met for the record to be included in the result set. In this case, column1 has to equal 'value1' OR column2 has to equal 'value2'.

SQL "OR" Condition - SQL SELECT Statement example

The first SQL "OR" Condition example that we'll take a look at involves an SQL SELECT statement with 2 conditions:
SELECT *
FROM suppliers
WHERE city = 'New York'
or city = 'Newark';
This SQL "OR" Condition example would return all suppliers that reside in either New York or Newark. Because the * is used in the SELECT statement, all fields from the suppliers table would appear in the result set.

SQL "OR" Condition - SQL SELECT Statement with 3 conditions example

The next example SQL OR Condition example takes a look at an 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 name = 'IBM'
or name = 'Hewlett Packard'
or name = 'Gateway';
This SQL "OR" Condition example would return all supplier_id values where the supplier's name is either IBM, Hewlett Packard or Gateway.

SQL "OR" Condition - SQL INSERT Statement example

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.

SQL "OR" Condition - SQL UPDATE Statement example

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 supplier_name = 'Dell';
This SQL "OR" Condition example would update all supplier_name values in the suppliers table to HP where the supplier_name was either IBM or Dell.

SQL "OR" Condition - SQL DELETE Statement example

The SQL "OR" Condition can be used in the SQL DELETE statement.
For example:.
DELETE FROM suppliers
WHERE supplier_name = 'IBM'
or supplier_name = 'Dell';
This SQL "OR" Condition example would delete all suppliers from the suppliers table whose supplier_name was either IBM or Dell.

No comments:

Post a Comment