Thursday, 30 August 2018

SQL query does not select all rows between dates

My SQL query doesn't select all the rows I asked for. It only considers the Day part of the datetime; months don't get any attention.

This is my query:
SELECT *
FROM Reservations
WHERE ReservationDate >= '24/04/2015' AND ReservationDate <= '24/03/2015'"

There are no results for these dates, but when the dates are changed to:
SELECT *
FROM Reservations
WHERE ReservationDate >= '24/04/2015' AND ReservationDate <= '17/03/2015'"

I get 2 results when ReservationDate= "17/04/2015 15:02:03" and "21/04/2015 16:05:56".
By the way, ReservationDate field is on string format. It's the same results even when it's on DateTime.
 ReservationID  FriendID    TableNumber ReservationDate ReservationStatus
16  58767732    32  21/04/2015 17:06:54 False
17  -1  32  21/04/2015 17:10:41 False
18  -1  2   21/04/2015 17:17:23 False
2   58767732    3 04/04/2015 19:37:17   False
3   -1  7   04/04/2015 19:37:43 False
4   -1  5   04/04/2015 23:24:24 False
5   -1  31 05/04/2015 16:29:02  False
6   -1  6   05/04/2015 16:40:29 False 7 -1  6   05/04/2015 17:12:47 False
8   58767732 32 09/04/2015 16:24:00 False
9   -1  6   09/04/2015 16:25:03 False


Try using the between operator for dates
    select * from Reservations
    where
        ReservationDate  between '17/03/2015'
    and
        DATE_ADD('24/04/2015',INTERVAL 1 DAY) // or something like that

Also, in MySQL you can use the DATE function to extract the date from a datetime:
    select * from Reservations
    where
         DATE(ReservationDate) BETWEEN '17/03/2015' AND '24/03/2015'

If you are using MS Sql Server, there are some other workarounds to get the date from a string.
UPDATE:
Since @Netanelgo said he is using MS Access:
Try CDate() to convert your string into a date.
select  *  from Reservations
where CDate(date) between #17/03/2015# and #24/03/2015#;

If it doesn't work because CDate does not reconize your format you can use DateSerial(year, month, day) to build a Date. You will need to use mid$ and Cint() to build the year, month and day arguments. Something like this for a format "yyyy-mm-dd":
DateSerial(CInt(mid(date, 1, 4)), CInt(mid(date, 6, 2)), CInt(mid(date, 9, 2))

0 comments:

Post a Comment