SQL – Time or Date range query with examples
Today in this article, we will cover SQL – Time or Date range query with examples.
We will see how to get records with greater than date or less than date/time or in between 2 given dates.
We will see SQL queries for greater than OR Less than or equal to dates or specific time ranges.
SQL Query – Less Than Specific Date Range
If you need to retrieve records where the date is greater than a specific date, please use the below query command.
Command
SELECT * FROM [Table_Name] WHERE [Data_Column_Name] < [Date]
In this query:
SELECT *
: Retrieves all records from the table.FROM Table_Name
: Specifies the table from which to pick data.WHERE Data_Column_Name
<
[Date]: Defines the date range query to get the records where Data_Column_Name is greater than the specified date.
Example
SELECT * FROM EMPLOYEE WHERE DATE_JOINED < '2023-11-11'
The above query returns all the columns of the EMPLOYEE table where DATE_JOINED is greater than the specified date i.e ‘2023-11-11’
SQL Query – Greater Than Specific Date Range
If you need to retrieve records where the date is greater than a specific date, please use the below query command.
Command
SELECT * FROM [Table_Name] WHERE [Data_Column_Name] > [Date]
Example
SELECT * FROM EMPLOYEE WHERE DATE_JOINED > '2023-07-15'
SQL Query – Greater Than and Less Than Specific Date Range
If you need to retrieve records between two dates where the date is greater than a specific date and less than a specific date, please use the below query command.
We will use BETWEEN operator to get records between 2 dates.
Command
SELECT * FROM [Table_Name] WHERE [Data_Column_Name] BETWEEN [Date1] AND [Date2];
Example
SELECT * FROM EMPLOYEE WHERE DATE_JOINED BETWEEN '2022-01-01' AND '2023-01-01';
In this query:
SELECT *
: Get all columns from the specified table.FROM EMPLOYEE
: Specifies the table from which to read the dataWHERE DATE_JOINED BETWEEN '2022-01-01' AND '2023-01-01'
: This query will return all the employees who joined between Jan 1, 2022, and Jan 1, 2023 year.
That’s all! Happy coding!
Does this help you fix your issue?
Do you have any better solutions or suggestions? Please sound off your comments below.
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.