In SQL, the BETWEEN
operator is used to filter the result set within a specified range of values. It allows you to retrieve rows where a column value falls within a specified range, including the boundary values.
Here's the syntax for using the BETWEEN
operator:
SELECT column1, column2, ...
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Example:
Suppose we have a table called employees
with a column named age
, and we want to retrieve employees whose ages fall between 25 and 35:
SELECT employee_id, first_name, last_name, age
FROM employees
WHERE age BETWEEN 25 AND 35;
In this example:
age BETWEEN 25 AND 35
specifies the range of values we are interested in. It includes all rows where the value of the age
column is greater than or equal to 25 and less than or equal to 35.It's important to note that the BETWEEN
operator is inclusive, meaning it includes both boundary values (value1
and value2
). If you want to exclude one or both of the boundary values, you can use comparison operators (>
and <
) in combination with logical operators (AND
or OR
). For instance:
SELECT column1, column2, ...
FROM table_name
WHERE column_name > value1 AND column_name < value2;
This query will retrieve rows where the column value is greater than value1
and less than value2
, effectively excluding both boundary values.