0

In my database, I have a column with a check-in date and a column with a check-out date. I need to select every row that has a check-in date <= 7/30/2017 and a check-out date that is >= 7/30/2017.

This is the code I have now:

SELECT * 
FROM `v_reservation_records` 
WHERE cast(checkin as date) <= '7/30/2017' 
AND cast(checkout as date) >= '7/30/2017'

Here is an example date from the DB:

2018-09-18

When I run this query, I do not get any results, but I know that I have a check-in date equal to 7/30/2017. What am I missing? Or is there an easier way to accomplish my goal?

6
  • What is the data type of the columns? Commented Sep 11, 2017 at 19:35
  • The data type is date. Commented Sep 11, 2017 at 19:39
  • 1
    Then just use '2017-07-30' instead of '7/30/2017'. And don't cast date to date. Commented Sep 11, 2017 at 19:40
  • SELECT * FROM v_reservation_records WHERE checkin <= '2017-30-7' AND checkout >= '2017-30-7' Commented Sep 11, 2017 at 19:44
  • Running this still returns no results. If you're right though, it looks like I have a formatting problem instead of a coding problem. :) Commented Sep 11, 2017 at 19:46

2 Answers 2

1

Assuming that you are casting valid values for date
You should convert also the literal the date properly

SELECT * 
FROM `v_reservation_records` 
WHERE cast(checkin as date) <= str_to_date('7/30/2017' , '%d/%m/%Y')
AND cast(checkout as date) >= str_to_date('7/30/2017' , '%d/%m/%Y')

and you can also use between

SELECT * 
FROM `v_reservation_records` 
WHERE str_to_date('7/30/2017','%d/%m/%Y') 
        between cast(checkin as date) AND cast(checkout as date) 
Sign up to request clarification or add additional context in comments.

2 Comments

It turns out that your second answer solved the problem. Thanks!
@Paul Spiegel, thanks for your troubleshooting as well!
0

Try like this

SELECT * 
FROM `v_reservation_records` 
WHERE DATE_FORMAT(checkin, '%m/%d/%Y') between '7/30/2017' 
AND '7/30/2017'

2 Comments

This is not a good idea, because it spoils the possibility of using an index. Just use date values in the canonical YYYY-MM-DD format.
This would not work because the check out date is not guaranteed to be the date that I'm searching for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.