Between SQL

Galaxy Glossary

How do you filter data within a specific range using SQL?

The BETWEEN operator in SQL is used to select values within a given range. It's a convenient way to filter data based on upper and lower bounds.
Sign up for the latest in SQL knowledge from the Galaxy Team!
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Description

The BETWEEN operator in SQL is a useful clause for selecting rows where a column's value falls within a specified range. It simplifies the process of filtering data compared to using multiple comparison operators. Instead of writing `column > lower_bound AND column < upper_bound`, you can use `BETWEEN lower_bound AND upper_bound`. This makes your queries more readable and maintainable. The BETWEEN operator is inclusive, meaning that the lower and upper bounds are part of the range. It's particularly helpful when dealing with date ranges, numerical ranges, or character ranges (e.g., alphabetical ranges). For example, you might want to find all orders placed between two specific dates or all products priced between a minimum and maximum value.

Why Between SQL is important

The BETWEEN operator enhances query efficiency and readability by concisely specifying a range of values. It's a standard SQL feature found in various database systems, making it a crucial skill for any SQL developer.

Example Usage


-- Sample table: Orders
CREATE TABLE Orders (
    OrderID INT PRIMARY KEY,
    OrderDate DATE,
    TotalAmount DECIMAL(10, 2)
);

INSERT INTO Orders (OrderID, OrderDate, TotalAmount) VALUES
(1, '2023-01-15', 100.50),
(2, '2023-02-20', 150.00),
(3, '2023-03-10', 200.25),
(4, '2023-04-05', 120.75);

-- Query to find orders placed between January 15th and March 10th, 2023
SELECT OrderID, OrderDate, TotalAmount
FROM Orders
WHERE OrderDate BETWEEN '2023-01-15' AND '2023-03-10';

Common Mistakes

Want to learn about other SQL terms?