Ranges with SQL BETWEEN Operator

The BETWEEN operator in SQL is used to filter data within a specified range. This range can include numeric, date, or even text values, making BETWEEN one of the most versatile and useful operators for data filtering. It simplifies querying by allowing you to specify a lower and an upper boundary, and SQL automatically includes all values within that range, inclusive of the endpoints.

In this chapter, we will explore the BETWEEN operator in-depth, starting from its syntax and basic usage to advanced scenarios involving dates, times, and text data. By the end of this chapter, you’ll have a comprehensive understanding of the BETWEEN operator and how to apply it effectively in various SQL queries.

What is the SQL BETWEEN Operator?

The BETWEEN operator is used in SQL to select values that fall within a given range. The range can consist of numbers, dates, or even strings. Importantly, the BETWEEN operator includes both the starting and ending values in the result set.

Syntax:

				
					SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;

				
			
  • column_name(s): The column(s) you are selecting.
  • table_name: The table where the data resides.
  • value1: The lower boundary of the range.
  • value2: The upper boundary of the range.

Key Points:

  • The BETWEEN operator is inclusive of both boundaries.
  • BETWEEN can be applied to numbers, dates, and even text.
  • To exclude the boundary values, we would use a combination of > or < operators.

Using BETWEEN with Numeric Values

The most common use case for BETWEEN is to work with numeric ranges. For example, imagine you have a table named products with a column price, and you want to find products priced between $100 and $500.

Example 1: Numeric Ranges

				
					SELECT product_name, price
FROM products
WHERE price BETWEEN 100 AND 500;

				
			

Output:

Product NamePrice
Laptop400
Smartphone300
Tablet150

Explanation:

  • The query returns products that have a price between 100 and 500, including 100 and 500.

Using BETWEEN with Dates

The BETWEEN operator is highly useful when working with date ranges. For instance, you might want to retrieve all orders placed between two specific dates from an orders table.

Example 2: Date Ranges

				
					SELECT order_id, order_date
FROM orders
WHERE order_date BETWEEN '2024-01-01' AND '2024-06-30';

				
			

Output:

Order IDOrder Date
10012024-02-15
10022024-05-10
10052024-06-29

Explanation:

  • This query returns all orders placed between January 1, 2024, and June 30, 2024. The results include orders on both the start and end dates.

Using BETWEEN with Text Data

Although less common, you can also use the BETWEEN operator with text data, as SQL considers the alphabetical order of characters. For example, you might want to retrieve all customers whose names fall alphabetically between “A” and “M”.

Example 3: Text Data Ranges

				
					SELECT customer_name
FROM customers
WHERE customer_name BETWEEN 'A' AND 'M';

				
			

Output:

Customer Name
Alice
Bob
Mary

Explanation:

  • The query returns all customers whose names start with letters between ‘A’ and ‘M’. The query considers the alphabetical order of the first letter of each name.

Combining BETWEEN with AND Clause

You can combine the BETWEEN operator with other SQL clauses like AND for more precise filtering. For instance, if you want to find orders placed between two dates but only for customers who have spent over $500, you can combine BETWEEN with another condition.

Example 4: Combining BETWEEN with AND

				
					SELECT order_id, order_date, total_amount
FROM orders
WHERE order_date BETWEEN '2024-01-01' AND '2024-06-30'
AND total_amount > 500;

				
			

Output:

Order IDOrder DateTotal Amount
10022024-03-10600
10052024-06-29750

Explanation:

  • This query filters the orders based on two conditions: the order date must be between January 1, 2024, and June 30, 2024, and the total amount must be greater than 500.

Using NOT BETWEEN

You can also negate the BETWEEN operator using NOT. This is helpful when you want to exclude values that fall within a specified range.

Example 5: Using NOT BETWEEN

				
					SELECT product_name, price
FROM products
WHERE price NOT BETWEEN 100 AND 500;

				
			

Output:

Product NamePrice
Headphones50
Smartwatch600
Camera550

Explanation:

  • This query retrieves products that are not priced between $100 and $500.

BETWEEN with NULL Values

One important thing to note is that BETWEEN does not return NULL values in the result set. If any NULL values exist in the column, they will not be included unless explicitly handled.

Example 6: Handling NULL Values

If you want to ensure that NULL values are included, you need to add an additional condition using IS NULL.

				
					SELECT product_name, price
FROM products
WHERE price BETWEEN 100 AND 500
OR price IS NULL;

				
			

Output:

Product NamePrice
Laptop400
Smartphone300
Tablet150
Unknown ProductNULL

Explanation:

  • This query includes rows with a price between $100 and $500, as well as those with NULL prices.

Advanced Usage of BETWEEN

Example 7: Using BETWEEN with Time Data

In addition to numeric, date, and text data, you can use BETWEEN to filter time data. For example, if you have a meetings table with a start_time column, you can filter meetings scheduled between two specific times.

				
					SELECT meeting_id, start_time
FROM meetings
WHERE start_time BETWEEN '09:00:00' AND '12:00:00';

				
			

Output:

Meeting IDStart Time
200109:30:00
200511:15:00

Explanation:

  • The query retrieves meetings that are scheduled between 9 AM and 12 PM.

Example 8: Using BETWEEN with Negative Values

You can also apply BETWEEN to negative values. Let’s assume you have a table of temperatures with daily temperature readings. You can filter readings between -10 and 0 degrees.

				
					SELECT day, temperature
FROM temperatures
WHERE temperature BETWEEN -10 AND 0;

				
			

Output:

DayTemperature
Monday-5
Wednesday0
Thursday-8

Explanation:

  • The query returns temperature readings between -10 and 0, inclusive of both boundaries.

Performance Considerations

When using the BETWEEN operator in SQL, performance is generally good, but it is always advisable to ensure the columns used in BETWEEN queries are indexed. Indexing can improve the speed of range-based queries, especially on large datasets.

  • Indexed Columns: If the column involved in the BETWEEN query is indexed, the query will perform faster as SQL can quickly locate the range of values.
  • Use Proper Data Types: Ensure that the data types of the column and the values being compared are compatible to avoid unnecessary data conversion.

The BETWEEN operator in SQL is a highly effective way to filter data within a range of values, making it suitable for handling numbers, dates, times, and even text. Its simplicity and flexibility make it a go-to operator for queries involving ranges.From basic numeric and date range queries to more advanced cases with times, negative values, and even combinations with other operators like NOT, BETWEEN is essential for data querying. Understanding its behavior with different data types and edge cases, such as NULL values, ensures that you can apply it effectively in a variety of scenarios. Happy coding !❤️

Table of Contents

Contact here

Copyright © 2025 Diginode

Made with ❤️ in India