← Back to Chapters

MySQL AND, OR, NOT Operators

? MySQL AND, OR, NOT Operators

? Quick Overview

MySQL logical operators AND, OR, and NOT are used inside the WHERE clause to filter records based on multiple conditions. They are heavily used in PHP-driven applications where dynamic queries are required.

? Key Concepts

  • AND → All conditions must be true
  • OR → At least one condition must be true
  • NOT → Excludes matching records
  • Parentheses control evaluation order

? Syntax / Theory

Logical operators are combined inside the WHERE clause. MySQL evaluates AND before OR unless parentheses are used.

? AND Operator

? View Code Example
// Select users older than 30 AND living in New York
SELECT * FROM users
WHERE age > 30 AND city = 'New York';

⚡ OR Operator

? View Code Example
// Select users older than 30 OR living in New York
SELECT * FROM users
WHERE age > 30 OR city = 'New York';

❌ NOT Operator

? View Code Example
// Exclude users who live in New York
SELECT * FROM users
WHERE NOT city = 'New York';

? Combining AND, OR, and NOT

? View Code Example
// Combine OR with AND and exclude inactive users
SELECT * FROM users
WHERE (age > 30 OR city = 'New York') AND NOT status = 'inactive';

?️ Example: Using Multiple Operators

? View Code Example
// Filter users by city, age, and active status
SELECT * FROM users
WHERE (city = 'Chicago' OR city = 'Houston')
AND age > 25
AND NOT status = 'inactive';

? Live Explanation

The database evaluates grouped conditions first. Records are returned only when all final logical expressions resolve to true. This logic is commonly used in PHP-backed dashboards, admin panels, and reports.

? Visual Logic Diagram

Condition A Condition B Result

? Use Cases

  • User filtering in PHP + MySQL applications
  • Search functionality with multiple conditions
  • Admin dashboards and reports
  • Access control and role-based queries

✅ Tips & Best Practices

  • Always use parentheses when mixing AND and OR
  • Write readable conditions for maintainability
  • Test queries directly in MySQL before embedding in PHP
  • Use prepared statements in PHP for safety

? Try It Yourself

  • Fetch users from Los Angeles or age above 25
  • Retrieve users not from New York or Los Angeles
  • Filter users younger than 30 and not active
  • Create a custom query combining all three operators