MySQL AND, OR and NOT
To use more than one condition in WHERE, join them with AND, OR and NOT.
| Operator | Row is returned when |
|---|---|
AND | Both conditions are true |
OR | At least one condition is true |
NOT | The condition is not true |
AND
SELECT name, city, marks FROM students
WHERE city = 'Mumbai' AND marks > 50;
Result
| name | city | marks |
|---|---|---|
| Maria | Mumbai | 92 |
Neha is in Mumbai too, but her marks are 45, so she is not returned.
OR
SELECT name, city FROM students
WHERE city = 'Delhi' OR city = 'Pune';
Result
| name | city |
|---|---|
| Robin | Delhi |
| John | Pune |
| Vikram | Delhi |
NOT
SELECT name, city FROM students
WHERE NOT city = 'Delhi';
Result
| name | city |
|---|---|
| Maria | Mumbai |
| John | Pune |
| Asha | Jaipur |
| Neha | Mumbai |
Use brackets
AND is checked before OR. Use brackets to make your meaning clear.
SELECT name, city, marks FROM students
WHERE (city = 'Delhi' OR city = 'Mumbai') AND marks >= 70;
Result
| name | city | marks |
|---|---|---|
| Robin | Delhi | 85 |
| Maria | Mumbai | 92 |
Note:
Without the brackets, MySQL reads city = 'Delhi' OR (city = 'Mumbai' AND marks >= 70), and Vikram from Delhi would also be returned.
Summary
ANDneeds both,ORneeds one,NOTreverses.- Use brackets when you mix
ANDandOR. - Next: ORDER BY.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |