MySQL AND, OR and NOT

To use more than one condition in WHERE, join them with AND, OR and NOT.

OperatorRow is returned when
ANDBoth conditions are true
ORAt least one condition is true
NOTThe 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

  • AND needs both, OR needs one, NOT reverses.
  • Use brackets when you mix AND and OR.
  • Next: ORDER BY.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Write a query to get data of selected columns from a table
Write a query to select the student with the maximum marks
Write a query to select top 3 students by marks
Write a query to select the rows if a column has no value
Write a query to find the names of students that begin with ‘A’
Write a query to fetch the top 2 records
Interview Questions & Answers
How to select Top 10 records in MySQL?
Write a MySQL query to select students with less than 50% marks
Write a MySQL query to select students with marks between 70 and 80
Write a query to fetch top N records
Write a query to find the names of employees that begin with ‘S’
Write a query to select if column has no/empty value
What is NULL in MySQL? Is NULL the same as 0 or an empty string?