๐ SQL BETWEEN Operator โ Range Queries for Numbers, Dates & Text
๐งฒ Introduction โ What is SQL BETWEEN?
The BETWEEN
operator in SQL is used to filter values within an inclusive range. It works with numbers, text, and dates to return rows where the column’s value lies between two boundary values.
๐ฏ In this guide, youโll learn:
- Syntax and usage of
BETWEEN
andNOT BETWEEN
- How to use it with numeric, date, and text types
- Best practices and real-world scenarios
โ 1. Basic SQL BETWEEN Syntax
SELECT * FROM products
WHERE price BETWEEN 10 AND 50;
โ
Returns rows where price
is greater than or equal to 10 and less than or equal to 50.
๐ 2. NOT BETWEEN to Exclude Ranges
SELECT * FROM employees
WHERE age NOT BETWEEN 30 AND 50;
โ Returns employees younger than 30 or older than 50.
๐ 3. Use BETWEEN with Dates
SELECT * FROM orders
WHERE order_date BETWEEN '2023-01-01' AND '2023-12-31';
โ Includes all orders made during 2023.
๐ค 4. Use BETWEEN with Text (Lexical Range)
SELECT * FROM customers
WHERE last_name BETWEEN 'A' AND 'M';
โ Filters names alphabetically between A and M.
๐ง 5. Combining BETWEEN with AND / OR
SELECT * FROM payments
WHERE amount BETWEEN 100 AND 500
AND method = 'Credit Card';
โ Filters on both value range and category.
โ ๏ธ 6. BETWEEN is Inclusive
BETWEEN x AND y
includes both x and y.- To exclude boundary values, use
>
and<
manually:
WHERE price > 10 AND price < 50;
๐ Best Practices
โ Recommended | โ Avoid This |
---|---|
Use BETWEEN for clean range queries | Rewriting as multiple AND conditions |
Remember it includes boundaries | Expecting exclusive comparisons |
Use proper data formats for dates | Comparing mismatched data types |
๐ Summary โ Recap & Next Steps
The BETWEEN
operator provides a concise way to filter data within ranges, whether you’re checking dates, prices, scores, or names.
๐ Key Takeaways:
- Use
BETWEEN x AND y
for inclusive ranges - Combine with other conditions using
AND
/OR
- Works on numbers, text, and dates
- Use
NOT BETWEEN
to exclude a range
โ๏ธ Real-World Relevance:
Used in reporting timeframes, sales thresholds, alphabetic sorting, and age/range checks.
โก๏ธ Next: Explore CASE WHEN
to apply conditional logic in your queries.
โ FAQ โ SQL BETWEEN Operator
โ Does BETWEEN include the boundary values?
โ Yes. It includes both the start and end values.
โ Can I use BETWEEN with dates?
โ Yes. Make sure the date format matches the columnโs data type.
โ What happens if the first value is greater than the second?
โ
SQL still processes it, but it’s better to ensure x <= y
.
โ Can I use BETWEEN in a JOIN?
โ Yes. Use it in the ON or WHERE clause as needed.
Share Now :