Summary: In this chapter, we’ll learn how to use the MySQL OR operator to combine Boolean expressions for filtering data.
MySQL OR Operator
Introduction to the MySQL OR operator
The MySQL OR operators are used to filter records based on more than one condition and OR operator displays a record if either the first condition OR the second condition is true.
The following illustrates the syntax of the OR operator.
1
| WHERE boolean_expression_1 OR boolean_expression_2 |
The following table shows the result of the OR operator.
TRUE | FALSE | NULL | |
TRUE | TRUE | TRUE | TRUE |
FALSE | TRUE | FALSE | NULL |
NULL | TRUE | NULL | NULL |
Operator precedence
When we use more than one logical operator in a statement, MySQL evaluates the OR operators after the AND operators. This is called operator precedence.
The operator precedence determines the order of evaluation of the operators. MySQL evaluates the operator with the higher precedence first.
See the following example.
1
| SELECT TRUE OR FALSE AND FALSE ; |
How it works
- First, MySQL evaluates the AND operator, therefore, false AND false returns false.
- Second, MySQL evaluates the OR operator hence true OR false returns true.
To change the order of evaluation, you use the parentheses, for example:
1
| SELECT ( TRUE OR FALSE ) AND FALSE ; |
How it works
- First, MySQL evaluates the expression in the parenthesis (true OR false) returns true
- Second, MySQL evaluates the remaining part of the statement, true AND false returns false.
MySQL OR operator examples
Let’s use the employees table in the sample database for the demonstration.
For example, To get only employees who is Software Engineer or Sales Rep. For this scenario we need to use the OR operator in the WHERE clause.
1
2
3
4
5
6
7
| SELECT firstname, lastname, jobtitle, salary FROM employees WHERE jobtitle= "Software Engineer" OR jobtitle= "Sales Rep" ; |
The following statement returns to get only those employees who is Software Engineer OR Sales Rep AND them salaries are more than 20000.
1
2
3
4
5
6
7
| SELECT firstname, lastname, jobtitle, salary FROM employees WHERE (jobtitle= "Software Engineer" OR jobtitle= "Sales Rep" ) AND salary > 20000; |
In this chapter, we have learnt how to use the MySQL OR operator to combine Boolean expressions for filtering data.
MySQL AND MySQL LIMIT
MySQL AND MySQL LIMIT