441

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.

shA.t
  • 16,580
  • 5
  • 54
  • 111
Neeraj
  • 7,945
  • 5
  • 19
  • 9

25 Answers25

674

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'

Filippos Zofakis
  • 561
  • 6
  • 12
Deepak
  • 7,507
  • 3
  • 24
  • 26
  • 49
    SQL Server defaults a date without a time to 00:00:00. So won't this query return anything from 2011/02/25 and 2011/02/26 at midnight? – Matt Aug 21 '12 at 14:27
  • 6
    @Deepak, your second bit should say >= and <= – IndoKnight Jun 26 '13 at 10:49
  • 7
    You might mention that the order matters in the BETWEEN function. It has to go from oldest on the left and more recent on the right. This is unintuitive as = is a comparative operator in sql and works for both "EmployeeId = 1" or "1 = EmployeeId" in the where clause. – Fi Horan Dec 22 '15 at 15:36
  • 1
    @Matt, according to the documentation for [between](https://msdn.microsoft.com/en-us/library/ms187922.aspx), if a row had a date of 2011/02/27 without a time, then that row is equivalent to having a date of 2011/02/27 00:00 and would be returned in the query, because it is less than or equal to 2011/02/27 00:00. So if you aren't dealing with time, `between` should work as expected. – timctran Jun 02 '16 at 17:22
  • 2
    @timctran Right, but 2011/02/27 00:00 is what we would call midnight of 2011/02/26. Presumably, the query means to include the 27th in the results set -- but an entry with a timestamp of 2011/02/27 5:00 wouldn't be included. – Sinjai Feb 08 '19 at 22:45
  • @Sinjai Since the field is named `Date` and not `Datetime`, I assume that the values are only dates and the `between` statement would include all entries with value `2011/02/27`. On a different note, technically a given midnight belongs to both/neither the day before and after it. For example, 2011/02/26 would have 2011/02/26 00:00 and 2011/02/26 24:00. Thus, it's advisable to avoid saying "Let's escape on the midnight of the 26th" (ambiguous); instead "Let's escape at 11:59 pm on the 26th or 12:01 am on the 27th" or "Let's escape at 24:00 on the 26th or 00:00 on the 27th". – timctran Apr 09 '19 at 06:46
  • -1 "the second is exclusive, as it effectively is '2011/02/27 00:00:00'" only if you can guarantee that the time will never be exactly midnight, which is much more likely than you might think because it's the default if you omit the time altogether. The only reasonable answer, especially for the unsuspecting StackOverflow reader, is to use strict inquality for the end: `col >= start and col < end` – Arthur Tacca Jun 03 '21 at 14:26
  • I m using ```SELECT * FROM `0986` WHERE date BETWEEN '01/06/2021' AND '07/06/2021'```. It doesn't return any data. If I use id as a column and use 1 to 5 it will return data. – tru_shar Oct 22 '21 at 11:21
171

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'
Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
WelshDragon
  • 1,711
  • 1
  • 10
  • 3
  • 46
    People still look at these questions and answers, even if they were originally posed some time back. I came looking for an answer, and much of what I saw here was incomplete or absolutely incorrect. My answer won't help the original poster, but it might help someone, perhaps even three years from now. – WelshDragon Feb 28 '14 at 14:01
  • 4
    Your answer helped me greatly, @WelshDragon -- The other answers left out the fact that the date format needs to be "simple date" on the server to ignore the hours. "<= END_DATE" assumes 12AM, which I didn't know. I was performing a query with "... <= 01/01/2014" and I couldn't figure out why orders on that date weren't showing for the 1st. Thank you very much. – Keith Jun 24 '14 at 20:13
  • @WelshDragon - your answer is a very good material for using dates as where clause. Thank you – Jack Frost Mar 14 '16 at 01:37
  • whats wrong if it return `'2011/02/28 00:00:00.000'` ? – Muflix Feb 14 '17 at 15:03
  • 1
    Tried this today, you could also use `convert(date, Date) between '2011/02/25' and '2011/02/27'` (at least with a recent MS SQL Server). The `convert()` part will take care of stripping the time part and the between comparison will then work as expected. – sensei Jan 10 '19 at 09:16
  • @sensei That's not the best idea, if you're selecting from a table where that column is indexed, using `convert(date, Date) between '2011/02/25' and '2011/02/27'` may prevent the use of the index, impacting performance. – Richard Abey-Nesbit Nov 19 '20 at 00:22
  • 2
    Do not use `Date >= '2011/02/25' and Date <= '2011/02/27 23:59:59.999'`, or the between version. These are both wrong, will return a records with the value `'2011-02-28T00:00:00'`. Don't be too tempted to use the magic time of 23:59.59.997 either, which is more reliable - but only for datetime columns. Datetime2 can have much greater precision, so these kind of comparisons are not habit you want to get into. Use `Date >= '2011-02-25T00:00:00' and Date < '2011-02-28T00:00:00'` instead; there's no downside with this one. – Richard Abey-Nesbit Nov 19 '20 at 00:28
  • Onek upokar hoilo bhai – jubair hridoy Jun 10 '21 at 12:07
  • 1
    @RichardAbey-Nesbit WelshDragon hasn't been seen here for several years - would you be so kind as to edit this answer to align with your comment? – Andrew Morton May 04 '23 at 18:08
  • @AndrewMorton Thanks - I've just submitted an edit for review now. Not sure if I had the reputation to do that at the time I made my comment =) – Richard Abey-Nesbit May 05 '23 at 03:03
21

Try this:

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

The date values need to be typed as strings.

To ensure future-proofing your query for SQL Server 2008 and higher, Date should be escaped because it's a reserved word in later versions.

Bear in mind that the dates without times take midnight as their defaults, so you may not have the correct value there.

  • 1
    Date is not a keyword and does not need to be escaped. Syntax highlighting is just syntax highlighting, keywords only need to be escaped if they cause a syntax error. It's also a good practice to use explicit conversion instead of implicit conversion of datestring constants. - and Date between CAST('2011/02/25'AS DATETIME) and CAST('2011/02/27'AS DATETIME) – tponthieux Feb 26 '11 at 09:27
  • 5
    Naturally you're right if this is SQL Server 2005, which the OP tagged. However, Date is reserved in 2008 and up, so for future-proofing, there's no harm in escaping it. I've edited my answer. –  Feb 26 '11 at 16:42
  • 1
    If he would specify the single date for both it would return zero rows but I guess that is not op's requirement – Zo Has Apr 03 '13 at 11:09
18
select * from table_name where col_Date between '2011/02/25' 
AND DATEADD(s,-1,DATEADD(d,1,'2011/02/27'))

Here, first add a day to the current endDate, it will be 2011-02-28 00:00:00, then you subtract one second to make the end date 2011-02-27 23:59:59. By doing this, you can get all the dates between the given intervals.

output:
2011/02/25
2011/02/26
2011/02/27
Sabyasachi Mishra
  • 1,677
  • 2
  • 31
  • 49
Chandra Prakash
  • 781
  • 4
  • 13
  • 23
9
select * from test 
     where CAST(AddTime as datetime) between '2013/4/4' and '2014/4/4'

-- if data type is different

7

This query stands good for fetching the values between current date and its next 3 dates

SELECT * FROM tableName  WHERE columName 
BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 3 DAY)

This will eventually add extra 3 days of buffer to the current date.

Tony
  • 9,672
  • 3
  • 47
  • 75
Vinit Kadkol
  • 1,221
  • 13
  • 12
7

This is very old, but given a lot of experiences I have had with dates, you might want to consider this: People use different regional settings, as such, some people (and some databases/computers, depending on regional settings) may read this date 11/12/2016 as 11th Dec 2016 or Nov 12, 2016. Even more, 16/11/12 supplied to MySQL database will be internally converted to 12 Nov 2016, while Access database running on a UK regional setting computer will interpret and store it as 16th Nov 2012.

Therefore, I made it my policy to be explicit whenever I am going to interact with dates and databases. So I always supply my queries and programming codes as follows:

SELECT FirstName FROM Students WHERE DoB >= '11 Dec 2016';

Note also that Access will accept the #, thus:

SELECT FirstName FROM Students WHERE DoB >= #11 Dec 2016#;

but MS SQL server will not, so I always use " ' " as above, which both databases accept.

And when getting that date from a variable in code, I always convert the result to string as follows:

"SELECT FirstName FROM Students WHERE DoB >= " & myDate.ToString("d MMM yyyy")

I am writing this because I know sometimes some programmers may not be keen enough to detect the inherent conversion. There will be no error for dates < 13, just different results!

As for the question asked, add one day to the last date and make the comparison as follows:

dated >= '11 Nov 2016' AND dated < '15 Nov 2016' 
Hannington Mambo
  • 998
  • 2
  • 13
  • 28
  • your information helped be complete my task. i have worked on this for more than 10 hours and non of the answers would work for me. When i concatenate like you have shown my project works great. but the rule seems to be to not write a SQL statement like this. when ever i try to set the SqlCommand's to add the date parameters to the SQL statement the parameters will not attach and i get the error that i must declare "@startDate" and "@endDate". i can not get passed this issue. I tried your date format "dd MMM yyyy" which worked and i also tried "yyyy MMM dd" which also performed the same. – Dave Hampel Mar 13 '20 at 03:49
  • Great it helped! Above are code samples. It's always better to declare and use parameters to avoid SQL Injection. And it seems you are already required/protected by the rules in your project, which is good. – Hannington Mambo Mar 14 '20 at 18:34
6

Try putting the dates between # # for example:

#2013/4/4# and #2013/4/20#

It worked for me.

halfer
  • 19,824
  • 17
  • 99
  • 186
Aleksandar
  • 3,558
  • 1
  • 39
  • 42
  • 2
    What does # do in this context? – B.K. Oct 29 '14 at 20:23
  • @B.K. it is a delimiter, like quotation marks for strings. "When supplying values to an SQL statement, for example as query criteria, their data type must be correctly defined by a "qualifier". This is done by enclosing the value between a pair of appropriate characters." reference --> [link](http://www.fontstuff.com/access/acctut15pfv.htm) – Aleksandar Oct 31 '14 at 15:01
  • 1
    @B.K. If it is a TSql syntax, You will need to use single quotation marks (**'**) in order to get what You need. references *[basics of sql-fontstuff.com](http://www.fontstuff.com/access/acctut15pfv.htm) * [Beginning SQL - Paul Wilton, John Colby](http://books.google.rs/books?id=9eqbXSnji84C&printsec=frontcover#v=onepage&q&f=false) – Aleksandar Oct 31 '14 at 15:16
  • 1
    It couldn't be any more clear that the question is for SQL Server and T-SQL. T-SQL and SQL Server don't accept dates between hash tags, it accepts dates between single quotes. This answer is wrong. – TT. May 29 '19 at 05:48
  • 1
    @TT. the number of upvotes says that it still helped someone. At the time I wrote my answer, the accepted answer was already chosen. Still, I wrote this to help anyone who might come here from Google or somewhere else :) – Aleksandar May 29 '19 at 06:38
6
select Date,TotalAllowance 
from Calculation 
where EmployeeId=1
  and convert(varchar(10),Date,111) between '2011/02/25' and '2011/02/27'
shA.t
  • 16,580
  • 5
  • 54
  • 111
njtd
  • 105
  • 2
  • 7
4

if its date in 24 hours and start in morning and end in the night should add something like :

declare @Approval_date datetime
set @Approval_date =getdate()
Approval_date between @Approval_date +' 00:00:00.000' and @Approval_date +' 23:59:59.999'
Sheryar Nizar
  • 285
  • 4
  • 5
4
SELECT CITY, COUNT(EID) OCCURENCES FROM EMP 
WHERE DOB BETWEEN '31-JAN-1900' AND '31-JAN-2900' 
GROUP BY CITY 
HAVING COUNT(EID) > 2;

This query will find Cities with more than 2 occurrences where their DOB is in a specified time range for employees.

Damini Suthar
  • 1,470
  • 2
  • 14
  • 43
  • Not really sure what this has to do with OP. Could you elaborate? – theking2 Nov 07 '21 at 16:01
  • this is real answer to the question . The question is how to use between and what is wrong with his query and it is the ' or " and not to divide the clause in 2 – Sonja Feb 23 '22 at 04:53
3

In your query, the date values in the between clause are not enclosed in single quotes, which can cause an error. Additionally, when specifying date literals, it's recommended to use the ISO 8601 format 'YYYY-MM-DD' for clarity and to avoid any ambiguity.

Here's the corrected query:

SELECT Date, TotalAllowance
FROM Calculation
WHERE EmployeeId = 1
  AND Date BETWEEN '2011-02-25' AND '2011-02-27';

In this query, the date values '2011-02-25' and '2011-02-27' are enclosed in single quotes to indicate that they are string literals representing dates. By using the ISO 8601 format, you ensure that the dates are interpreted correctly.

Utilizing dbForge Studio's SQL editor, you can execute your queries and efficiently accomplish a wide range of database management tasks.

2

I would go for

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

The logic being that >= includes the whole start date and < excludes the end date, so we add one unit to the end date. This can adapted for months, for instance:

select Date, ... from ...
             where Date >= $start_month_day_1 and Date < DATEADD(m, 1, $end_month_day_1)
entonio
  • 2,143
  • 1
  • 17
  • 27
2

It worked for me

SELECT 
  * 
FROM 
  `request_logs` 
WHERE 
  created_at >= "2022-11-30 00:00:00" 
  AND created_at <= "2022-11-30 20:04:50" 
ORDER BY 
  `request_logs`.`id` DESC

Akbarali
  • 688
  • 7
  • 16
1

best query for the select date between current date and back three days:

  select Date,TotalAllowance from Calculation where EmployeeId=1 and Date BETWEEN       
DATE_SUB(CURDATE(), INTERVAL 3 DAY)  AND CURDATE() 

best query for the select date between current date and next three days:

  select Date,TotalAllowance from Calculation where EmployeeId=1 and Date BETWEEN   
   CURDATE()  AND DATE_ADD(CURDATE(), INTERVAL 3 DAY)   
Paresh Mayani
  • 127,700
  • 71
  • 241
  • 295
1

I like to use the syntax 1 MonthName 2015 for dates ex:

   WHERE aa.AuditDate>='1 September 2015'
     AND aa.AuditDate<='30 September 2015'

for dates

Rakesh kumar Oad
  • 1,332
  • 1
  • 15
  • 24
J.J
  • 881
  • 16
  • 29
  • Why would that be? – theking2 Nov 07 '21 at 16:02
  • To make it more readable for other developers and avoid bugs, different countries have different format for dates dd/mm/yy vs mm/dd/yy etc https://calendars.wikia.org/wiki/Date_format_by_country – J.J Nov 07 '21 at 18:38
  • March is spelled März where I'm coming from – theking2 Nov 29 '21 at 20:36
  • English is not my main language neither, but if I see 03/06/11 I may assume that is 6th of March 2011 but it may as well be 3th of June 2011 . I wont make that mistake with the syntax I mentioned – J.J Nov 29 '21 at 20:51
1

Check below Examples: Both working and Non-Working.

select * from tblUser Where    
convert(varchar(10),CreatedDate,111) between '2015/04/01' and '2016/04/01' //--**Working**

OR

select * from tblUser Where
(CAST(CreatedDate AS DATETIME) between CAST('2015/04/01' AS DATETIME) And CAST('2016/4/30'AS DATETIME)) //--**Working**

OR

select * from tblUser Where
(YEAR(CreatedDate) between YEAR('2015/04/01') And YEAR('2016/4/30')) 
//--**Working**

AND below is not working:

select * from tblUser Where
Convert(Varchar(10),CreatedDate,111) >=  Convert(Varchar(10),'01-01-2015',111) and  Convert(Varchar(10),CreatedDate,111) <= Convert(Varchar(10),'31-12-2015',111) //--**Not Working**


select * from tblUser Where
(Convert(Varchar(10),CreatedDate,111) between Convert(Varchar(10),'01-01-2015',111) And Convert(Varchar(10),'31-12-2015',111)) //--**Not Working**
Eloims
  • 5,106
  • 4
  • 25
  • 41
1

You ca try this SQL

select * from employee where rec_date between '2017-09-01' and '2017-09-11' 
Keyur Padalia
  • 2,077
  • 3
  • 28
  • 55
Kamran
  • 669
  • 6
  • 9
0
Select 
    * 
from 
    Calculation 
where 
    EmployeeId=1 and Date between #2011/02/25# and #2011/02/27#;
shA.t
  • 16,580
  • 5
  • 54
  • 111
Saad Sheikh
  • 29
  • 1
  • 7
0

we can use between to show two dates data but this will search the whole data and compare so it will make our process slow for huge data, so i suggest everyone to use datediff:

qry = "SELECT * FROM [calender] WHERE datediff(day,'" & dt & "',[date])>=0 and datediff(day,'" & dt2 & "',[date])<=0 "

here calender is the Table, dt as the starting date variable and dt2 is the finishing date variable.

Bipul Roy
  • 163
  • 1
  • 14
0

Really all sql dates should be in yyyy-MM-dd format for the most accurate results.

Rakesh kumar Oad
  • 1,332
  • 1
  • 15
  • 24
  • Dates in a database are dates in a database. On presentation layer you might want to use `DATE_FORMAT` and `STR_TO_DATE` functions – theking2 Nov 07 '21 at 16:16
0

There are a lot of bad answers and habits in this thread, when it comes to selecting based on a date range where the records might have non-zero time values - including the second highest answer at time of writing.

Never use code like this: Date between '2011/02/25' and '2011/02/27 23:59:59.999'

Or this: Date >= '2011/02/25' and Date <= '2011/02/27 23:59:59.999'

To see why, try it yourself:

DECLARE @DatetimeValues TABLE
    (MyDatetime datetime);
INSERT INTO @DatetimeValues VALUES
    ('2011-02-27T23:59:59.997')
    ,('2011-02-28T00:00:00');

SELECT MyDatetime
FROM @DatetimeValues
WHERE MyDatetime BETWEEN '2020-01-01T00:00:00' AND '2020-01-01T23:59:59.999';

SELECT MyDatetime
FROM @DatetimeValues
WHERE MyDatetime >= '2011-02-25T00:00:00' AND MyDatetime <= '2011-02-27T23:59:59.999';

In both cases, you'll get both rows back. Assuming the date values you're looking at are in the old datetime type, a date literal with a millisecond value of 999 used in a comparison with those dates will be rounded to millisecond 000 of the next second, as datetime isn't precise to the nearest millisecond. You can have 997 or 000, but nothing in between.

You could use the millisecond value of 997, and that would work - assuming you only ever need to work with datetime values, and not datetime2 values, as these can be far more precise. In that scenario, you would then miss records with a time value 23:59:59.99872, for example. The code originally suggested would also miss records with a time value of 23:59:59.9995, for example.

Far better is the other solution offered in the same answer - Date >= '2011/02/25' and Date < '2011/02/28'. Here, it doesn't matter whether you're looking at datetime or datetime2 columns, this will work regardless.

The other key point I'd like to raise is date and time literals. '2011/02/25' is not a good idea - depending on the settings of the system you're working in this could throw an error, as there's no 25th month. Use a literal format that works for all locality and language settings, e.g. '2011-02-25T00:00:00'.

0

Two things:

  1. use quotes

  2. make sure to include the last day (ending at 24)

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

If Date is a DateTime.

I tend to do range checks in this way as it clearly shows lower and upper boundaries. Keep in mind that date formatting varies wildly in different cultures. So you might want to make sure it is interpreted as a date. Use DATE_FORMAT( Date, 'Y/m/d').

(hint: use STR_TO_DATE and DATE_FORMAT to switch paradigms.)

theking2
  • 2,174
  • 1
  • 27
  • 36
-1
/****** Script for SelectTopNRows command from SSMS  ******/
SELECT TOP 10 [Id]
  ,[Id_parvandeh]
  ,[FirstName]
  ,[LastName]
  ,[RegDate]
  ,[Gilder]
  ,[Nationality]
  ,[Educ]
  ,[PhoneNumber]
  ,[DueInMashhad]

  ,[EzdevajDate]


  ,[MarriageStatus]
  ,[Gender]
  ,[Photo]

  ,[ModifiedOn]
  ,[CreatorIp]
   From
  [dbo].[Socials] where educ >= 3 or EzdevajDate  >= '1992/03/31' and EzdevajDate <= '2019/03/09' and MarriageStatus = 1
Mojtaba Nava
  • 858
  • 7
  • 17
-7
SELECT Date, TotalAllowance  
FROM Calculation  
WHERE EmployeeId = 1 
  AND Date BETWEEN to_date('2011/02/25','yyyy-mm-dd') 
               AND to_date ('2011/02/27','yyyy-mm-dd');
Philipp
  • 67,764
  • 9
  • 118
  • 153
Ankita
  • 15
  • 1
    You were probably thinking of Oracle SQL when you wrote this answer. This is valid in Oracle. Not so much in SQL Server (from what I can see). – Charles Caldwell Aug 27 '14 at 18:14