IMG-LOGO

TSQL Between

andy - 01 Dec, 2020 810 Views 0 Comment

The TSQL Between operator function is used to return results based on comparing between two expression values. Those expression values are in numbers or date format.

Let says we have the following product table.


We are going to use this table to exercise the Between operator so we can narrow the result by comparing the start and end expression values. 

1. We want to get all the products that have a price value between $50 and $200 dollars. To get those results we are going to comparing the price value field.


SELECT *
FROM PRODUCTS
WHERE Price BETWEEN 50 AND 200

2. If you want to get all products with a range price of $50 and $200. You can easily include a NOT operator before the BETWEEN operator. See the below example.


SELECT *
FROM PRODUCTS
WHERE Price NOT BETWEEN 50 AND 200

3. The BETWEEN operator can also compare between two dates. Let says we want to get all products that are listed between 1 Dec 2020 to 31 Dec 2020.


SELECT *
FROM PRODUCTS
WHERE PromotionDate BETWEEN '2020-12-31' AND '2020-12-01'

p>

Please remember the start expression always using the lower value compared to the end expression.

See the following example. If you try to run the following query. It will not return any result.


SELECT *
FROM PRODUCTS
WHERE Price BETWEEN 200 AND 50

Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.

Related Articles

How to restore database using SQL query in TSQL?

If you have a database backup bak file extension and want to restore it using SQL query You can use the built in RESTORE DATABASE function Remember in order to be able to restore a database successfully You need to ...

How to get all table sizes in TSQL?

To get the information about how much space or size used by tables You can retrieve the size information by linking multiple tables in sys tables There are two tables that hold this information The first one is the sys ...