I would like to select all the records in a table between two dates. I have a query like:
SELECT * FROM <table> WHERE (thedate BETWEEN DATE('2012-04-01') AND DATE('2012-06-30'))
This is fine for HSQL, Oracle, PostgreSQL, but it doesn’t work in SQL Server due to the lack of the Date function. Is there a way to get this to work generally for all databases (including SQL Server) or do I need to use an ORM like Hibernate (I know I should, but I’m specifically asking if this can be done in SQL)?
There’s no need for the Date(…) as far as i can tell. This example seems to work
Edit Btw worth looking at This Question with the date time answer (will post here just to save effort)
The between statement can cause issues with range boundaries for dates as
is really interpreted as
so will miss anything that occurred during the day of Jan 31st. In this case, you will have to use:
or
UPDATE: It is entirely possible to have records created within that last second of the day, with a datetime as late as 01/01/2009 23:59:59.997!!
For this reason, the
BETWEEN (firstday) AND (lastday 23:59:59)approach is not recommended.Use the
myDate >= (firstday) AND myDate < (Lastday+1)approach instead.