Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL between dates including start and end dates

Tags:

sql

mysql

So I have this:

 (CURDATE() BETWEEN start_date AND end_date) 

Works fine.

But when the CURDATE() is 2011-12-02 and the end_date is 2011-12-02 will it grab the row?

E.g my start_date is 2011-12-01 00:00:00 and my end date is 2011-12-02 23:59:59

So it only works when the date is between but not if it's ON the end_date itself.

Or maybe it should check for the time too, because it still needs to be selected with this query when it's 2011-12-02 15:30:00 for example.

How can I do this?

like image 336
Karem Avatar asked Dec 02 '11 10:12

Karem


People also ask

Does between include start and end date?

The SQL BETWEEN Operator The BETWEEN operator selects values within a given range. The values can be numbers, text, or dates. The BETWEEN operator is inclusive: begin and end values are included.

Does between include the end date?

Yes it includes start and end date and you could easily find this in the documentation.

How do I separate the start date and end date in SQL?

declare @StartDate date = '20170401' , @EndDate date = '20170731'; ;with Months as ( select top (datediff(month, @startdate, @enddate) + 1) [Month] = dateadd(month, row_number() over (order by number) -1, @StartDate), MonthEnd = dateadd(day,-1,dateadd(month, row_number() over (order by number), @StartDate)) from master ...


2 Answers

Since both columns are timestamps, you need to make sure times don't trip you up. To keep the times from tripping you up, cast the timestamps to date.

where current_date between cast(start_date as date) 
                       and cast(end_date as date);
like image 156
Mike Sherrill 'Cat Recall' Avatar answered Oct 02 '22 12:10

Mike Sherrill 'Cat Recall'


Well, you could try

CURDATE() BETWEEN start_date AND DATE_ADD(end_date, INTERVAL 1 DAY)
like image 23
Marco Avatar answered Oct 02 '22 14:10

Marco