๐ฏ SQL BETWEEN Operator โ Filter Values Within a Range Easily
Want to retrieve records that fall within a specific range of numbers, dates, or text?
The SQLBETWEENoperator is the perfect tool to simplify range-based filtering in your queries.
๐ What is SQL BETWEEN?
The SQL BETWEEN operator allows you to filter rows based on a range of values, including both lower and upper bounds.
๐ง It works with:
- Numbers
- Dates
- Text (alphabetical ranges)
๐งพ SQL BETWEEN Syntax
SELECT column1, column2, ...
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
๐ This returns rows where column_name is:
- Greater than or equal to
value1 - Less than or equal to
value2
โ Example: Filter by Salary Range
SELECT employee_name, salary
FROM employees
WHERE salary BETWEEN 40000 AND 80000;
๐ฏ This returns employees earning โน40,000 to โน80,000, inclusive.
๐ Example: Filter by Date Range
SELECT order_id, order_date
FROM orders
WHERE order_date BETWEEN '2024-01-01' AND '2024-12-31';
Returns all orders placed in 2024.
๐ Example: Filter by Text Range
SELECT product_name
FROM products
WHERE product_name BETWEEN 'A' AND 'M';
This retrieves product names that alphabetically fall between A and M.
โ NOT BETWEEN
To exclude a range, use NOT BETWEEN:
SELECT employee_name, age
FROM employees
WHERE age NOT BETWEEN 25 AND 35;
๐ This returns employees younger than 25 or older than 35.
โ ๏ธ Important Notes
BETWEENis inclusive โ it includes both boundary values.- For date comparisons, use
'YYYY-MM-DD'format for compatibility. - Works with
AND,OR, and other filters for more complex queries.
๐ Combine BETWEEN with Other Conditions
SELECT *
FROM orders
WHERE order_date BETWEEN '2024-01-01' AND '2024-06-30'
AND status = 'Delivered';
๐ก Returns only orders delivered in H1 of 2024.
๐งช Practice Challenge
Task: Retrieve products priced between โน1,000 and โน5,000 that are in stock.
SELECT product_name, price, stock_status
FROM products
WHERE price BETWEEN 1000 AND 5000
AND stock_status = 'Available';
๐ Final Thoughts
The SQL BETWEEN operator is a clean, readable, and high-performance way to filter values within ranges.
โ
Simplifies queries
โ
Works across numbers, dates, and text
โ
Makes conditions easier to understand for any SQL user