← Back to Chapters

MySQL BETWEEN

? MySQL BETWEEN

? Quick Overview

The BETWEEN operator in MySQL filters results to values that fall within a specified inclusive range. It works with numeric, text (alphabetical range), and date/time types.

? Key Concepts

  • Inclusive range: BETWEEN a AND b includes both a and b.
  • Data types: Works with numbers, dates, and text — order semantics depend on the type.
  • Equivalent expression: x BETWEEN a AND b is the same as x >= a AND x <= b.
  • Use cases: Filtering ages, prices, date ranges, or alphabetical bundles.

? Syntax / Theory

? View Code Example
-- Syntax for BETWEEN
SELECT column_name
FROM table_name
WHERE column_name BETWEEN value1 AND value2;

? Code Example(s)

? View Code Example
-- Get records where age is between 18 and 30 (inclusive)
SELECT * FROM students
WHERE age BETWEEN 18 AND 30;
? View Code Example
-- Get records where price is between 100 and 500
SELECT * FROM products
WHERE price BETWEEN 100 AND 500;
? View Code Example
-- Get records with dates between 2021-01-01 and 2021-12-31
SELECT * FROM orders
WHERE order_date BETWEEN '2021-01-01' AND '2021-12-31';

? Live Output / Explanation

How results behave

All three example queries return rows where the column value lies within the inclusive boundaries. For dates, ensure the literal format matches the column type. For text, BETWEEN 'A' AND 'M' will match alphabetical ordering based on collation.

Note: BETWEEN is inclusive of both ends.

? Tips & Best Practices

  • Prefer explicit comparisons (>= and <=) when you need clarity in complex conditions.
  • When filtering by date-time, consider using full timestamps or CAST/TRUNCATE to avoid timezone/precision pitfalls.
  • Remember text ranges depend on the column collation — test with your DB collation if results seem unexpected.

? Try It Yourself / Practice Tasks

  • Write a query to select all employees whose salary is between 50000 and 100000.
  • Use BETWEEN to retrieve orders between '2020-01-01' and '2020-12-31'.
  • Try using BETWEEN with text fields to filter names starting from 'A' to 'M'.