totn MySQL

MySQL: OR Condition

This MySQL tutorial explains how to use the MySQL OR condition with syntax and examples.

Description

The MySQL OR Condition is used to test two or more conditions where 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 OR Condition in MySQL is:

WHERE condition1
OR condition2
...
OR condition_n;

Parameters or Arguments

condition1, condition2, ... condition_n
Any of the conditions that must be met for the records to be selected.

Note

  • The MySQL OR condition allows you to test 2 or more conditions.
  • The MySQL OR condition requires that any of the conditions (ie: condition1, condition2, condition_n) must be met for the record to be included in the result set.

Example - With SELECT Statement

The first MySQL OR condition example that we'll take a look at involves a SELECT statement with 2 conditions:

SELECT *
FROM contacts
WHERE state = 'California'
OR contact_id < 1000;

This MySQL OR condition example would return all customers that reside in either the state of California or have a contact_id less than 1000. Because the * is used in the SELECT statement, all fields from the contacts table would appear in the result set.

Example - With SELECT Statement (3 conditions)

The next MySQL OR example looks at a SELECT statement with 3 conditions. If any of these conditions is met, the record will be included in the result set.

SELECT supplier_id, supplier_name
FROM suppliers
WHERE supplier_name = 'Microsoft'
OR state = 'Florida'
OR offices > 10;

This MySQL OR condition example would return all supplier_id and supplier_name values where the supplier_name is either Microsoft, the state is Florida, or offices is greater than 10.

Example - With INSERT Statement

The MySQL OR condition can be used in the INSERT statement.

For example:

INSERT INTO suppliers
(supplier_id, supplier_name)
SELECT customer_id, customer_name
FROM customers
WHERE state = 'Florida'
OR state = 'California';

This MySQL OR example would insert into the suppliers table, all customer_id and customer_name records from the customers table that reside in the state of Florida or California.

Example - With UPDATE Statement

The MySQL OR condition can be used in the UPDATE statement.

For example:

UPDATE suppliers
SET supplier_name = 'Apple'
WHERE supplier_name = 'RIM'
OR available_products > 25;

This MySQL OR condition example would update all supplier_name values in the suppliers table to Apple where the supplier_name was RIM or its available_products was greater than 25.

Example - With DELETE Statement

The MySQL OR condition can be used in the DELETE statement.

For example:

DELETE FROM customers
WHERE last_name = 'Johnson'
OR first_name = 'Joe';

This MySQL OR condition example would delete all customers from the customers table whose last_name was Johnson or first_name was Joe.