← Back to Chapters

MySQL AND, OR, NOT

? MySQL AND, OR, NOT

? Quick Overview

Learn how to use the logical operators AND, OR, and NOT in MySQL to filter query results based on multiple conditions. These operators let you combine or negate conditions in WHERE clauses to precisely control which rows are returned.

? Key Concepts

  • AND — all combined conditions must be true for a row to be included.
  • OR — at least one of the combined conditions must be true for a row to be included.
  • NOT — negates a condition; use to exclude rows that match a condition.
  • Use parentheses (...) to group conditions and control evaluation order when mixing AND and OR.

? Syntax / Theory

? View Code Example
// Basic usage patterns for AND, OR, NOT in a WHERE clause
-- AND: Combines conditions, all must be true
SELECT * FROM students WHERE age > 18 AND department = 'Engineering';
-- OR: Combines conditions, only one must be true
SELECT * FROM students WHERE age < 20 OR department = 'Engineering';
-- NOT: Reverses a condition
SELECT * FROM students WHERE NOT department = 'Engineering';

? Code Examples

? View Code Example
// Using AND to select students older than 18 AND in Engineering
SELECT * FROM students WHERE age > 18 AND department = 'Engineering';
? View Code Example
// Using OR to select students who are from Engineering OR older than 20
SELECT * FROM students WHERE department = 'Engineering' OR age > 20;
? View Code Example
// Using NOT to exclude students from the Engineering department
SELECT * FROM students WHERE NOT department = 'Engineering';

? Live Output / Explanation

How rows are selected

AND requires all conditions to be true; for example, age > 18 AND department = 'Engineering' returns only students who meet both criteria. OR returns rows that match any condition. When mixing AND and OR, use parentheses to ensure the intended logic — e.g. (department = 'Engineering' OR department = 'CS') AND age > 18.

✅ Tips & Best Practices

  • Prefer parentheses to make complex logical expressions clear and avoid unexpected precedence issues.
  • Remember that NOT applies to the immediate condition — use parentheses when negating combined conditions.
  • Test queries incrementally: start with a single condition, then add more to verify expected rows are returned.
  • Use explicit comparisons (e.g., department = 'Engineering') instead of relying on truthy/falsy behavior.

? Try It Yourself / Practice Tasks

  • Write a query that uses AND to select students who are both older than 20 and are from 'Computer Science'.
  • Write a query that uses OR to select students who are either from 'Engineering' or are under 18 years old.
  • Write a query that uses NOT to exclude students who have 'Mathematics' as their department.