In this tutorial, we’ll be talking about the MySQL AND Operator. Suppose you are playing a video game and you pass a level only if you earn $50,000 and complete 2 missions. So, the logic is that you have two conditions you need to satisfy to pass the level. What if you encounter a similar situation in databases where you need two (or more) conditions to be satisfied to get a particular result-set?
MySQL provides you with the AND
logical operator when we want to specify multiple conditions as a part of the WHERE clause. The AND
operator combines two or more conditions and returns true if and only if all the conditions are satisfied. It returns false if any one of the conditions evaluates to false.
Syntax of the MySQL AND Operator
Boolean_expression_1 AND Boolean_expression_2
Code language: SQL (Structured Query Language) (sql)
Examples of the MySQL AND Operator
Let us take a look at a few examples to demonstrate the use of the AND
Operator. Consider the following Students table.
1. Single AND Operator Example
Let us try to find out the students whose ID is greater than 3 and were present for more than 70 days. We will use the following SELECT command query for it.
SELECT * FROM Students WHERE ID>3 AND DaysPresent>70;
Code language: SQL (Structured Query Language) (sql)
MySQL AND
operator looks up all the records in the Students table and filters those who match both the conditions mentioned as a part of the WHERE
clause.
We get the output as follows,
2. Multiple AND operator example
Now, how about finding out the students whose ID is greater than 3, were present for more than 70 days and are from Pune. We will use the following query for it.
SELECT * FROM Students WHERE ID>3 AND DaysPresent>70 and City=’Pune’;
Code language: SQL (Structured Query Language) (sql)
We get the output as follows,
Conclusion
The AND
operator is a powerful operator when you want to filter through the table such that all conditions specified should evaluate to true. The AND
operator is widely used in MySQL and you need to have a clear understanding of it’s working. I highly recommend you to check out the following links for further reading.
References
- JournalDev article on Logical Operators.
- MySQL official documentation on Logical Operators.