Explain BETWEEN Operator in SQL
The BETWEEN
operator in SQL is used to filter the result set within a certain range. It can be applied to numeric, date, or text data types. The syntax for the BETWEEN
operator is:
expression BETWEEN value1 AND value2
Where:
expression
is the column or value you are checking.
value1
and value2
define the range.
The BETWEEN
operator is inclusive, meaning it includes the boundary values specified.
Example 1: Numeric Range
Suppose you have a table named Products
with a column Price
, and you want to select all products with prices between 10 and 50.
SELECT *
FROM Products
WHERE Price BETWEEN 10 AND 50;
Output
ProductID |
ProductName |
Price |
1 |
Widget A |
15 |
2 |
Widget B |
30 |
3 |
Widget C |
45 |
Example 2: Date Range
Assume you have a table named Orders
with a column OrderDate
, and you want to select all orders placed between January 1, 2024, and December 31, 2024.
SELECT *
FROM Orders
WHERE OrderDate BETWEEN '2024-01-01' AND '2024-12-31';
Output
OrderID |
CustomerID |
OrderDate |
TotalAmount |
101 |
5001 |
2024-02-15 |
200.00 |
102 |
5002 |
2024-05-23 |
150.00 |
103 |
5003 |
2024-11-30 |
300.00 |
Example 3: Text Range
If you have a table named Employees
with a column LastName
, and you want to select all employees whose last names fall between 'Johnson' and 'Smith'.
SELECT *
FROM Employees
WHERE LastName BETWEEN 'Johnson' AND 'Smith';
Output
EmployeeID |
FirstName |
LastName |
1 |
Alice |
Johnson |
2 |
Bob |
Jones |
3 |
Carol |
King |
4 |
Dave |
Smith |
In this example, BETWEEN
will include all last names alphabetically between 'Johnson' and 'Smith', inclusive of those values.