Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a given date fits between a range of dates

Tags:

If I have 2 date columns in a table, startDate and endDate. How do I return rows where a given date fits between those 2 dates? For example:

If the given date is 2012-10-25

It should return the following rows

startDate   -   endDate 2012-10-25  -   2012-10-25 2011-09-10  -   2013-11-15 2012-10-20  -   2012-10-25 2012-10-23  -   2012-10-28 2012-09-14  -   2012-10-28 

from the following rows:

startDate   -   endDate 2012-10-25  -   2012-10-25 2011-09-10  -   2013-11-15 2012-01-11  -   2012-10-11 2012-10-20  -   2012-10-25 2012-04-15  -   2012-04-16 2012-05-20  -   2012-05-25 2012-12-01  -   2012-12-10 2012-10-23  -   2012-10-28 2012-09-14  -   2012-10-28 2012-11-13  -   2012-12-15 

Is this possible with sql?

I am using sql server 2008.

like image 474
oshirowanen Avatar asked Oct 31 '12 15:10

oshirowanen


People also ask

How do you check if a date exists between two dates?

To check if a date is between two dates: Use the Date() constructor to convert the dates to Date objects. Check if the date is greater than the start date and less than the end date. If both conditions are met, the date is between the two dates.

How do you check if a date is within a date range in Java?

We can use the simple isBefore , isAfter and isEqual to check if a date is within a certain date range; for example, the below program check if a LocalDate is within the January of 2020. startDate : 2020-01-01 endDate : 2020-01-31 testDate : 2020-01-01 testDate is within the date range.

How can I get date between two dates in SQL?

The DATEDIFF() function returns the difference between two dates.


2 Answers

With SQL Server it's actually as simple as:

SELECT startDate, endDate FROM YourTable WHERE '2012-10-25' between startDate and endDate 
like image 197
Chad Avatar answered Oct 18 '22 23:10

Chad


Check BETWEEN keyword.

Syntax is simple:

SELECT col1, col2 FROM table1 WHERE '2012-10-25' BETWEEN col1 and col2 

where col1 and col2 are the start and end dates respectively.

like image 32
Azodious Avatar answered Oct 18 '22 23:10

Azodious