In this tutorial, we’ll work on the MySQL OR operator. Suppose you are a teacher and you want to find out students who scored above 90 in their Maths or Science exams to be considered for the position of class monitor. So, in short, if a student scores above 90 in either Maths or Science, he is eligible for being the class monitor. You have two conditions and you need any one of them to be true.
MySQL provides you with the OR
logical operator when we want to specify multiple such “either-or” conditions as a part of the WHERE clause. The OR
operator combines two or more conditions and returns true if any one of the conditions evaluates to true. It returns false if and only if all the conditions evaluate to false.
Syntax of the MySQL OR Operator
Boolean_expression_1 OR Boolean_expression_2
Code language: SQL (Structured Query Language) (sql)
Examples of the MySQL OR
Let us dive into a couple of examples to demonstrate the use of the MySQL OR
Operator. Consider the following Marks table.
1. Single OR Operator Example
Let us try to find out the students who scored above 90 in Maths or Science. We will use the SELECT command with the WHERE Clause for filtering out the results.
SELECT StudentID, Maths, Science FROM Marks WHERE Maths>90 OR Science>90;
Code language: SQL (Structured Query Language) (sql)
OR
filters through all the records in the Marks table and returns only those records who satisfy either of the conditions, or both.
We get the output as follows,
2. Multiple OR operators example
Let us now try to find students who have scored 100 in Maths or Science or above 90 in English. We will use the following query for it.
SELECT * FROM Marks WHERE English>90 OR Maths=100 OR Science=100;
Code language: SQL (Structured Query Language) (sql)
We get the output as follows,
Conclusion
The OR
operator is a very important logical operator that lets you filter through the records in the table and returns only those records which satisfy any one of the given conditions. For further reading, I would encourage you to use the following links.
References
- JournalDev article on Logical Operators.
- MySQL official documentation on Logical Operators.