SQL Standard

SQL Between Two Dates

The between operator in SQL allows you to select records within a specific range. You often specify the range as an integer or a date type in most cases.

This article will explore how you can select records between a range of two dates using the between operator.

SQL Between Operator

The between operator is very straightforward. You only need to specify the start and end bounds. However, keep in mind that the between operators is inclusive. Therefore, the start and end bounds are included in the resulting set.

We can express the between operator as shown below:

SELECT column_name(s)

FROM table_name

WHERE column_name BETWEEN start_bound AND end_bound;

SQL Between Two dates

Let us illustrate how we can use the between operator to fetch values between a range of two dates.

Let us create a sample table as shown in the query below:

CREATE TABLE

sample.inventory ( product_name VARCHAR(255) NOT NULL,

price INT NOT NULL,

purchase_date DATE );

The above query creates a table called inventory in the sample database. We then add 3 columns containing the product name, price, and the purchase date.

We can add sample data as shown:

INSERT INTO

sample.inventory

VALUES

('Smart Wallet', 89, '2022-04-23');

INSERT INTO

sample.inventory

VALUES

('AirTag Tracker', 30, '2022-02-02');

INSERT INTO

sample.inventory

VALUES

('iPad Pro', 999, '2021-12-12');

INSERT INTO

sample.inventory

VALUES

('Flash Drive', 40, '2021-01-01');

Once all the sample data are inserted, it can be verified by running the query below:

SELECT * from sample.inventory;

This should return all the data as shown:

Example

To learn how to use the between operator with a date range, let us retrieve the records where the purchase date is between 2021-01-01 and 2021-12-31

We can run the query as shown:

SELECT

*

FROM

sample.inventory

WHERE

purchase_date BETWEEN '2021-01-01'

AND '2021-12-31';

The above query should match the records where the date is within the specified range. This should return two products as shown below:

Conclusion

In this article, we discussed how to retrieve records between a range of two date values using the between operator in SQL.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list