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.
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.
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.
The DATEDIFF() function returns the difference between two dates.
With SQL Server it's actually as simple as:
SELECT startDate, endDate FROM YourTable WHERE '2012-10-25' between startDate and endDate
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With