T-SQL Tutorial

T-SQL Between operator


The SQL Server BETWEEN operator is a logical operator used to select values within a specified range in a database table. It is often used in SQL queries to filter data based on specific criteria.


Syntax

The syntax of the Between operator is as follows:

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

In the above query, column_name represents the name of the column in the table, table_name represents the name of the table, value1 represents the lower bound of the range, and value2 represents the upper bound of the range.


Example

The Between operator is inclusive, meaning that it includes the values of value1 and value2 in the result set. For example, if we have a table called employees with a column named salary, we can use the Between operator to find all employees whose salary is between $50,000 and $100,000:

SELECT *
FROM employees
WHERE salary BETWEEN 50000 AND 100000;

This query will return all employees whose salary is greater than or equal to $50,000 and less than or equal to $100,000.

The BETWEEN operator can also be combined with other operators, such as the NOT BETWEEN operator, to filter data based on specific criteria. For example, if we want to find all employees whose salary is not between $50,000 and $100,000, we can use the Not Between operator:

SELECT *
FROM employees
WHERE salary NOT BETWEEN 50000 AND 100000;

This query will return all employees whose salary is less than $50,000 or greater than $100,000.

In summary, the SQL Server Between operator is a useful tool for filtering data based on a range of values. It is easy to use and can be combined with other operators to create more complex queries.