Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query to select dates between two dates

I have a start_date and end_date. I want to get the list of dates in between these two dates. Can anyone help me pointing the mistake in my query.

select Date,TotalAllowance  from Calculation  where EmployeeId=1   and Date between 2011/02/25 and 2011/02/27 

Here Date is a datetime variable.

like image 980
Neeraj Avatar asked Feb 26 '11 04:02

Neeraj


People also ask

How do I select between two dates in SQL?

The SQL BETWEEN OperatorThe 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.

How do I select a specific date range in SQL?

SELECT * FROM PERSONAL WHERE BIRTH_DATE_TIME BETWEEN '2001-03-01 11:00:00' AND '2005-03-01 22:00:00';


2 Answers

you should put those two dates between single quotes like..

select Date, TotalAllowance from Calculation where EmployeeId = 1              and Date between '2011/02/25' and '2011/02/27' 

or can use

select Date, TotalAllowance from Calculation where EmployeeId = 1              and Date >= '2011/02/25' and Date <= '2011/02/27' 

keep in mind that the first date is inclusive, but the second is exclusive, as it effectively is '2011/02/27 00:00:00'

like image 173
Deepak Avatar answered Sep 19 '22 09:09

Deepak


Since a datetime without a specified time segment will have a value of date 00:00:00.000, if you want to be sure you get all the dates in your range, you must either supply the time for your ending date or increase your ending date and use <.

select Date,TotalAllowance from Calculation where EmployeeId=1  and Date between '2011/02/25' and '2011/02/27 23:59:59.999' 

OR

select Date,TotalAllowance from Calculation where EmployeeId=1  and Date >= '2011/02/25' and Date < '2011/02/28' 

OR

select Date,TotalAllowance from Calculation where EmployeeId=1  and Date >= '2011/02/25' and Date <= '2011/02/27 23:59:59.999' 

DO NOT use the following, as it could return some records from 2011/02/28 if their times are 00:00:00.000.

select Date,TotalAllowance from Calculation where EmployeeId=1  and Date between '2011/02/25' and '2011/02/28' 
like image 25
WelshDragon Avatar answered Sep 20 '22 09:09

WelshDragon