Advertisement
Google Ad Slot: content-top
MySQL AND, OR, NOT
MySQL AND, OR, NOT Operators in WHERE Clause
The AND, OR, and NOT operators in MySQL are used in the WHERE clause to filter records based on multiple conditions.
Demo Database
Below is a selection from the "Students" table in the school_db database:
student_id |
name |
gender |
city |
age |
score |
course_id |
phone_number |
|
|---|---|---|---|---|---|---|---|---|
1 |
Alice |
Female |
Delhi |
20 |
85 |
101 |
NULL |
1234567890 |
2 |
Bob |
Male |
Mumbai |
22 |
75 |
NULL |
bob@email.com |
NULL |
3 |
Charlie |
Male |
Delhi |
21 |
95 |
102 |
NULL |
NULL |
4 |
David |
Male |
Bangalore |
23 |
65 |
101 |
david@email.com |
NULL |
5 |
Eve |
Female |
Mumbai |
20 |
80 |
103 |
NULL |
NULL |
6 |
Frank |
Male |
Delhi |
22 |
90 |
103 |
NULL |
NULL |
7 |
Alice |
Female |
Mumbai |
19 |
60 |
102 |
NULL |
NULL |
AND Operator
The AND operator ensures both conditions must be true for a record to be selected.
Syntax:
SELECT column1, column2 FROM table_name WHERE condition1 AND condition2;
- Retrieves students who are 18 or older AND live in Mumbai.
OR Operator
The OR operator selects records if at least one condition is true.
Syntax:
SELECT column1, column2 FROM table_name WHERE condition1 OR condition2;
- Retrieves students who are younger than 18 OR live in Mumbai.
NOT Operator
The NOT operator negates a condition (returns the opposite result).
Syntax:
SELECT column1, column2 FROM table_name WHERE NOT condition;
- Retrieves students who are NOT 18 years old.
Combining AND, OR, and NOT
You can combine multiple operators using parentheses (()) for clarity.
- Retrieves students who are 18 or older and live in Mumbai OR are NOT female.