SQL Date/Time BETWEEN And Comparison Operators Work With Floats

Posted August 4, 2006 at 2:17 PM by Ben Nadel

Tags: SQL

I don't want to beat a dead horse here, but I just discovered that you can interchange DATETIME and FLOAT values when using comparison operators like BETWEEN and > and <. So, if you accept that today, August 4, 2006 has the FLOAT equivalent of 38931.0, then you could query for records like this:

  • SELECT
  • s.id,
  • s.referer_url
  • FROM
  • web_stats_session s
  • WHERE
  • s.date_created BETWEEN 38930 AND 38932

In this case, 38930 stands for August 3, 2006 and 38932 stands for August 5, 2006. Keep in mind that the first value is inclusive (includes 08/03) and the second value is exlusive (excludes 08/05). I just think that is wicked cool.

I came across this answering a question on CF-Talk. Some guy was querying for dates but he knew that some dates would be null. I suggested this (after some testing):

  • SELECT
  • id
  • FROM
  • [table]
  • WHERE
  • [date] BETWEEN
  • ISNULL( date_started, 0 ) AND
  • ISNULL( date_ended, getDate() )

In this example, the line:

  • ISNULL( date_started, 0 )

... tells the query to use the database date if it exists, and if it does not exist (is null), then use the zero date. This will not limit the query on that end of the BETWEEN. The second line:

  • ISNULL( date_ended, getDate() )

... tells the query to use the database date if it exists, and if it does not exist (is null), then use the current date. Now that I think about it though, if the second BETWEEN value is exclusive, you might have to add one day to the getDate().



Reader Comments

Aug 4, 2006 at 4:41 PM // reply »
153 Comments

For a more database-agnostic solution, try:

COALESCE(date_started,0)

The other nice thing about COALESCE (besides working on every DB platform I can think of) is that you can also do multiple fallback options:

a = COALESCE(b,c,d,e,f,g)


Aug 4, 2006 at 4:45 PM // reply »
74 Comments

Rick, I have never used the COALESCE function, but it looks very cool. I have to say that ISNULL() rocked my world at the very foundation and completely changed the way I run SQL statements that have NULL values. Who knows, COALESCE might be a second revolutions.

Thanks for the hot tip.


Feb 10, 2007 at 9:07 AM // reply »
1 Comments

Only problem is if the 2 floats match

Works: s.date_created BETWEEN 38930 AND 38932

Does Not: s.date_created BETWEEN 38930 AND 38930

If you convert them to an INT, the above will work.


Feb 11, 2007 at 12:11 AM // reply »
1 Comments

"... the second value is exlusive (excludes 08/05). I just think that is wicked cool."

Why is that cool? It breaks BETWEEN.

Also if you want to have a range with one day, you'd have
to use 39120.0 AND 39120.9.

Using INTs rather than FLOATS resolves this, because it ignores
time in a DateTime field.


Feb 11, 2007 at 8:09 AM // reply »
11,238 Comments

Markus,

Thanks for the tip. I give that a go.


Aug 5, 2007 at 4:08 PM // reply »
1 Comments

ben
I have a problem
access database with the following SQL

" Select " & _
" EmployeeID, Date, MorningTimeIn, MorningTimeOut, " & _
" AfternoonTimeIn, AfternoonTimeOut, TotalHours " & _
" From " & _
" TimeClock " & _
" Where Date Like '%/%/%%%%'" & _
" And Date Between '" & DateT & "'" & _
" And " & _
"'" & DateF & "'" & _
" And " & _
" EmployeeID = " & "'" & EmpID & "'" & _
" Order By " & _
" Date Asc "

The problem is if DateF is 7/10/2007 & DateT is 8/4/2007 everything is fine. (I guess thats not a problem I get a proper retrieval of records)

However, if DateF is 7/9/2007 & DateT is 8/4/2007 everything goes wrong. (it retrieves record 7/9/2007 and records 8/1/2007-8/4/2007 so the problem is it is recognizing a 2 digit dayin the first ex. but when asked the look between a 1 digit day & and a 1 digit day does not recognise 2 digit days)


Aug 10, 2007 at 8:48 AM // reply »
11,238 Comments

@Tim,

That is a very strange issue. Unfortunately, I know very little about Access. What language are you using (Not ColdFusion from the looks of it). I would say, force the day to always be two digits (ie. "09" vs "9"), but that is a ghetto hack.

Also, I don't like the looks of this: %/%/%%%%... if you are querying a "Date" field, should that always be the case? And I am not sure you need 4 % in a row for the year; I think one should suffice. Are you trying to check to see if that field is NULL?


Sep 19, 2007 at 7:48 AM // reply »
1 Comments

i am facing problem when using the condition like this
this is one
create procedure P
(
@clientip varchar(50),
@Name varchar(50)
)
as

select * from tblReourse where clienip like @clientip and Name like @Name or Name is Null

here if we consider there are 6 records in the table like this

clientip Name
--------- ----------
123.2.3.4 sys
123.2.3.4 Null
123.2.3.4 www
123.2.3.4 Null
123.2.3.4 Null

here in this if i give the 'clientip' along wiht that ' Name' for the procedure it will return the corect records from the procedure

if i give only 'Name' then all the records will be returned there will be no filteringby for the particular name which we give..

i tried with isnull operator same problem exists can u plz give how to alter this procedure if i remove 'oR' condition then also we are not getting the correct answer


Sep 19, 2007 at 8:24 AM // reply »
11,238 Comments

@Rajesh,

I have very little experience with stored procedures. But I am curious, when you say you only pass in the Name, are you passing in anything for the ClientIP? Are you passing in NULL for it?


Apr 25, 2008 at 5:27 PM // reply »
1 Comments

I want to change the value of my tables column if a date column is over three days old, like deleting a reservation after three days, anyone got any ideas, am using JSP and SQL for my program.


Jul 10, 2008 at 4:54 AM // reply »
1 Comments

m working in c#.when i retrieve records from access db then an exception throws that data type mismatch exception.
although i used a date field with type date/time and here in application when i write query
select * from tab wher date > '"+date1.text+"';
then grid cannot fill can any1 tell me the sol.
thanx


Jul 10, 2008 at 8:11 AM // reply »
11,238 Comments

@shoaib,

Try outputting the SQL string rather than executing it. You might find that there is an error or unexpected value being used.


Sue
Jun 10, 2010 at 5:47 AM // reply »
2 Comments

Hi.. isnull(somedate,0) would return "1900-01-01 00:00:00.000" for null.. my Q is.. how to return "-" instead?

I'm a newbie.. how do i change it to String?


Jun 10, 2010 at 8:48 AM // reply »
11,238 Comments

@Sue,

I'm not sure you can really change data types mid-column (so to speak). For something like that, I'd just return NULL for the date and then on the programming side, check to see if the column value is a date:

<cfif isDate( query.dateColumn )> .... </cfif>

(or in whatever programming language you are using).


Sue
Jun 16, 2010 at 10:56 PM // reply »
2 Comments

Thanks for your respond. I've figured out the solution.

isnull(CAST(CONVERT(varchar(11), a.icSUBDATE, 106)AS varchar(11)),'-') as SubmitDocToInsCo

it will return a dash '-' if the date is NULL..

Cheers!


Sep 29, 2010 at 5:06 AM // reply »
2 Comments

Hii ben,

i have problem with comparision with date&time.i have one column which has datetime datatype. my data like "2010-11-20 12:45:50". now i have a another datetime like "2010-11-20 12:00:50". if i want to compare these in where clause then how can i do it ??


Oct 5, 2010 at 10:38 PM // reply »
11,238 Comments

@Bhavin,

Have you tried just using a greater-than, less-than operator? Example:

WHERE dateOne > dateTwo


Oct 6, 2010 at 5:19 AM // reply »
2 Comments

@ben,

yah...i tried it before your reply and it works.by the way thanks of replay...


Oct 10, 2010 at 4:33 PM // reply »
11,238 Comments

@Bhavin,

Awesome - glad you got it working.


Sep 13, 2011 at 6:36 AM // reply »
1 Comments

i have a problem when i want to select enddate -now()<=5 and enddate-now()>0 but it not work .
what could i do if want to select data from table when edate-now()lies between 0 to 5


Feb 10, 2013 at 9:52 PM // reply »
1 Comments

the BETWEEN ... AND comparison operator is the equivalent of:

[expression] >= [value1] AND [expression] <= [value2]

In other words BOTH [value1] and [value2] are included in results, so I don't think this is correct:

"and the second value is exclusive"



Post A Comment

Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.

Please review the following issues:

Author Name:


Author Email:

Author Website:

Comment:

Supported HTML tags for formatting: <strong>bold</strong>   <em>italic</em>   <code>code</code>







  • Help Wanted - Find Your Next ColdFusion Job
Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
May 17, 2013 at 7:42 PM
HashKeyCopier - An AngularJS Utility Class For Merging Cached And Live Data
Ben - thanks so much for posting these Angular articles and findings, they've been a huge help towards learning one of the more 'complex' JavaScript frameworks out there (IMO). I have been using Angu ... read »
May 16, 2013 at 5:01 PM
UPDATE: Parsing CSV Data Files In ColdFusion With csvToArray()
Your code was the closest thing I've found to obtaining some direction for converting ISO fields to values that CF can translate properly. Thank you for posting! ... read »
May 15, 2013 at 10:37 PM
Very Simple Pusher And ColdFusion Powered Chat
hi id making plz easy ... read »
May 15, 2013 at 6:07 PM
Making SOAP Web Service Requests With ColdFusion And CFHTTP
Ben, you once again saved my bacon at work. Thank you, thank you, thank you! ... read »
May 15, 2013 at 4:15 PM
What If All User Interface (UI) Data Came In Reports?
@Josh, Thanks! @Ben, I definitely recommend the David West book "Object Thinking" I've been quoting from. It goes deeply into the philosophy and history of OO programming. His breadth ... read »
May 15, 2013 at 11:36 AM
Ask Ben: Print Part Of A Web Page With jQuery
I found this helpfull when you need to keep (refresh) the original parent page after closing the iframe child print dialog (Hoping you're not using a form at this time so it won't submit again): On ... read »
May 14, 2013 at 7:13 PM
What If All User Interface (UI) Data Came In Reports?
@Jonah, If there's any books you'd recommend on the subject of domain modelling, I'd love to hear it. I just downloaded the free PDF of "Domain Driven Design Quickly". Figured I'd give it ... read »
May 14, 2013 at 6:57 PM
The UX Of Prototyping: Low-Fidelity Is The New High-Fidelity
@Phillip, I'm not sure I follow what you mean? Are you saying that you looked at the list of widgets provided by the jQuery UI and let that be your style guide? ... read »
InVision App - Prototyping Made Beautiful With Prototyping Tools