← Back to Chapters

MySQL BETWEEN & NOT BETWEEN Operator

? MySQL BETWEEN & NOT BETWEEN Operator

? Quick Overview

The BETWEEN operator in MySQL filters records that fall within a specific range of values such as numbers, dates, or text. The NOT BETWEEN operator does the opposite by excluding values inside the range. These operators are widely used in PHP–MySQL applications for data filtering.

? Key Concepts

  • BETWEEN checks a value within a range
  • Both boundary values are included
  • NOT BETWEEN excludes values inside the range
  • Works with numbers, dates, and strings

? Syntax / Theory

? View Code Example
// Generic syntax for BETWEEN operator
SELECT column_name FROM table_name
WHERE column_name BETWEEN value1 AND value2;

? Code Example: Numeric Range

? View Code Example
// Fetch employees aged between 30 and 40
SELECT * FROM employees
WHERE age BETWEEN 30 AND 40;

? Code Example: Date Range

? View Code Example
// Retrieve employees who joined in 2020
SELECT * FROM employees
WHERE join_date BETWEEN '2020-01-01' AND '2020-12-31';

❌ Code Example: NOT BETWEEN

? View Code Example
// Exclude employees aged between 30 and 40
SELECT * FROM employees
WHERE age NOT BETWEEN 30 AND 40;

? Code Example: Text Range

? View Code Example
// Select products with names between A and M
SELECT * FROM products
WHERE product_name BETWEEN 'A' AND 'M';

⚙️ PHP + MySQL Example

? View Code Example
// PHP query using BETWEEN operator
$sql = "SELECT * FROM employees WHERE age BETWEEN 25 AND 35";
$result = mysqli_query($conn, $sql);

? Live Output / Explanation

The queries return records that match the defined range conditions. When used in PHP, the filtered results are typically displayed in tables, reports, or dashboards.

? Use Cases

  • Filtering users by age range
  • Fetching records between two dates
  • Product price filtering in e-commerce
  • Generating reports within time periods

? Tips & Best Practices

  • Always remember BETWEEN includes both limits
  • Use proper date formats for date comparisons
  • Combine with indexes for better performance

? Try It Yourself

  • Write a query to find customers aged between 18 and 25
  • Use NOT BETWEEN to exclude products priced between 100 and 500
  • Create a PHP script that filters orders by date range